diff --git a/.github/DockerfileBackendTests b/.github/DockerfileBackendTests index 87a65214ab..2ce47ea714 100644 --- a/.github/DockerfileBackendTests +++ b/.github/DockerfileBackendTests @@ -28,7 +28,7 @@ ENV PATH="${PATH}:/usr/local/go/bin" ENV GO_PATH=/usr/local/go/bin/go # UV -RUN curl --proto '=https' --tlsv1.2 -LsSf https://github.com/astral-sh/uv/releases/download/0.11.24/uv-installer.sh | sh && mv /usr/local/cargo/bin/uv /usr/local/bin/uv +RUN curl --proto '=https' --tlsv1.2 -LsSf https://github.com/astral-sh/uv/releases/download/0.13.0/uv-installer.sh | sh && mv /usr/local/cargo/bin/uv /usr/local/bin/uv ENV TZ=Etc/UTC diff --git a/.github/workflows/backend-test-windows.yml b/.github/workflows/backend-test-windows.yml index 54a62ec495..9fa13bca58 100644 --- a/.github/workflows/backend-test-windows.yml +++ b/.github/workflows/backend-test-windows.yml @@ -63,7 +63,7 @@ jobs: - uses: denoland/setup-deno@v2 with: - # Pin to the Deno version shipped in the runtime image (Dockerfile) so CI + # Pin to the Deno version shipped in the full runtime image (docker/DockerfileFull) so CI # tests what production runs, instead of floating on the latest v2.x. deno-version: 2.2.1 @@ -81,7 +81,7 @@ jobs: - uses: astral-sh/setup-uv@v7 with: - version: "0.11.24" + version: "0.13.0" - uses: shivammathur/setup-php@v2 with: @@ -139,8 +139,8 @@ jobs: run: | cargo build --release -p windmill_duckdb_ffi_internal New-Item -ItemType Directory -Path ..\target\debug -Force - Copy-Item target\release\windmill_duckdb_ffi_internal.dll ..\target\debug\ - # duckdb is bundled (~2GB of build artifacts); the DLL is the only + Copy-Item target\release\windmill_duckdb_runner.exe ..\target\debug\ + # duckdb is bundled (~2GB of build artifacts); the runner is the only # thing we need from this excluded-crate target dir. Remove-Item -Recurse -Force -ErrorAction SilentlyContinue target Get-PSDrive C | Select-Object Used,Free | Format-Table -AutoSize diff --git a/.github/workflows/backend-test.yml b/.github/workflows/backend-test.yml index a2087025b7..b01e99a696 100644 --- a/.github/workflows/backend-test.yml +++ b/.github/workflows/backend-test.yml @@ -50,7 +50,7 @@ jobs: dotnet-version: "9.0.x" - uses: denoland/setup-deno@v2 with: - # Pin to the Deno version shipped in the runtime image (Dockerfile) so CI + # Pin to the Deno version shipped in the full runtime image (docker/DockerfileFull) so CI # tests what production runs, instead of floating on the latest v2.x. deno-version: 2.2.1 - uses: actions/setup-go@v7 @@ -64,7 +64,7 @@ jobs: node-version: "24" - uses: astral-sh/setup-uv@v7 with: - version: "0.11.24" + version: "0.13.0" - uses: shivammathur/setup-php@v2 with: php-version: "8.3" @@ -83,9 +83,16 @@ jobs: chmod +x "$HOME/.local/bin/wmill" echo "$HOME/.local/bin" >> $GITHUB_PATH working-directory: / - - name: Install PowerShell, mold and clang + - name: Install PowerShell, mold, clang and the latest pg_dump + # PGDG's `postgresql-client` is its newest major, Ubuntu's is not: the `postgres` service + # image floats, and pg_dump refuses a server newer than itself. `/usr/bin/pg_dump` picks + # the version of the runner's own preinstalled cluster, so the newest bin dir goes first. run: | - sudo apt-get update && sudo apt-get install -y powershell mold clang libcurl4-openssl-dev + sudo /usr/share/postgresql-common/pgdg/apt.postgresql.org.sh -y + sudo apt-get update && sudo apt-get install -y powershell mold clang libcurl4-openssl-dev postgresql-client + PG_BIN="/usr/lib/postgresql/$(ls /usr/lib/postgresql | sort -n | tail -1)/bin" + echo "$PG_BIN" >> "$GITHUB_PATH" + "$PG_BIN/pg_dump" --version working-directory: / - uses: actions-rust-lang/setup-rust-toolchain@v1 with: @@ -295,4 +302,4 @@ jobs: # never reaches it. Pin the target dir (matching the cache step above) so # its own tests run off this compile rather than a second bundled build. (cd windmill-duckdb-ffi-internal && export CARGO_TARGET_DIR="$PWD/target" && ./build_dev.sh && cargo test --release -p windmill_duckdb_ffi_internal) - DENO_PATH=$(which deno) BUN_PATH=$(which bun) NODE_BIN_PATH=$(which node) GO_PATH=$(which go) UV_PATH=$(which uv) PHP_PATH=$(which php) COMPOSER_PATH=$(which composer) RUBY_PATH=$(which ruby) RUBY_BUNDLE_PATH=$(which bundle) RUBY_GEM_PATH=$(which gem) POWERSHELL_PATH=$(which pwsh) DOTNET_PATH=$(which dotnet) cargo test --features enterprise,deno_core,duckdb,license,python,rust,scoped_cache,parquet,private,private_registry_test,csharp,php,ruby,mysql,quickjs,mcp,run_inline,smtp,http_trigger --all -- --nocapture --test-threads=10 + DENO_PATH=$(which deno) BUN_PATH=$(which bun) NODE_BIN_PATH=$(which node) GO_PATH=$(which go) UV_PATH=$(which uv) PHP_PATH=$(which php) COMPOSER_PATH=$(which composer) RUBY_PATH=$(which ruby) RUBY_BUNDLE_PATH=$(which bundle) RUBY_GEM_PATH=$(which gem) POWERSHELL_PATH=$(which pwsh) DOTNET_PATH=$(which dotnet) cargo test --features enterprise,deno_core,duckdb,license,python,rust,scoped_cache,parquet,private,private_registry_test,csharp,php,ruby,mysql,quickjs,mcp,run_inline,smtp,http_trigger,openidconnect --all -- --nocapture --test-threads=10 diff --git a/.github/workflows/benchmark.yml b/.github/workflows/benchmark.yml index d420ff1f00..475d7860d8 100644 --- a/.github/workflows/benchmark.yml +++ b/.github/workflows/benchmark.yml @@ -27,7 +27,7 @@ jobs: DATABASE_URL: postgres://postgres:changeme@postgres:5432/windmill LICENSE_KEY: ${{ secrets.WM_LICENSE_KEY_CI }} WORKER_GROUP: main - WORKER_TAGS: deno,bun,go,python3,bash,dependency,flow,nativets + WORKER_TAGS: bun,go,python3,bash,dependency,flow,nativets options: >- --pull always --health-interval 10s --health-timeout 5s --health-retries 5 --health-cmd "curl @@ -111,7 +111,7 @@ jobs: DATABASE_URL: postgres://postgres:changeme@postgres:5432/windmill LICENSE_KEY: ${{ secrets.WM_LICENSE_KEY_CI }} WORKER_GROUP: main - WORKER_TAGS: deno,bun,go,python3,bash,dependency,flow,nativets + WORKER_TAGS: bun,go,python3,bash,dependency,flow,nativets options: >- --pull always --health-interval 10s --health-timeout 5s --health-retries 5 --health-cmd "curl @@ -125,7 +125,7 @@ jobs: LICENSE_KEY: ${{ secrets.WM_LICENSE_KEY_CI }} MODE: worker WORKER_GROUP: main - WORKER_TAGS: deno,bun,go,python3,bash,dependency,flow,nativets + WORKER_TAGS: bun,go,python3,bash,dependency,flow,nativets options: >- --pull always @@ -136,7 +136,7 @@ jobs: LICENSE_KEY: ${{ secrets.WM_LICENSE_KEY_CI }} MODE: worker WORKER_GROUP: main - WORKER_TAGS: deno,bun,go,python3,bash,dependency,flow,nativets + WORKER_TAGS: bun,go,python3,bash,dependency,flow,nativets options: >- --pull always @@ -147,7 +147,7 @@ jobs: LICENSE_KEY: ${{ secrets.WM_LICENSE_KEY_CI }} MODE: worker WORKER_GROUP: main - WORKER_TAGS: deno,bun,go,python3,bash,dependency,flow,nativets + WORKER_TAGS: bun,go,python3,bash,dependency,flow,nativets options: >- --pull always @@ -188,7 +188,7 @@ jobs: DATABASE_URL: postgres://postgres:changeme@postgres:5432/windmill LICENSE_KEY: ${{ secrets.WM_LICENSE_KEY_CI }} WORKER_GROUP: main - WORKER_TAGS: deno,bun,go,python3,bash,dependency,flow,nativets + WORKER_TAGS: bun,go,python3,bash,dependency,flow,nativets options: >- --pull always --health-interval 10s --health-timeout 5s --health-retries 5 --health-cmd "curl @@ -202,7 +202,7 @@ jobs: LICENSE_KEY: ${{ secrets.WM_LICENSE_KEY_CI }} MODE: worker WORKER_GROUP: main - WORKER_TAGS: deno,bun,go,python3,bash,dependency,flow,nativets + WORKER_TAGS: bun,go,python3,bash,dependency,flow,nativets options: >- --pull always @@ -213,7 +213,7 @@ jobs: LICENSE_KEY: ${{ secrets.WM_LICENSE_KEY_CI }} MODE: worker WORKER_GROUP: main - WORKER_TAGS: deno,bun,go,python3,bash,dependency,flow,nativets + WORKER_TAGS: bun,go,python3,bash,dependency,flow,nativets options: >- --pull always @@ -224,7 +224,7 @@ jobs: LICENSE_KEY: ${{ secrets.WM_LICENSE_KEY_CI }} MODE: worker WORKER_GROUP: main - WORKER_TAGS: deno,bun,go,python3,bash,dependency,flow,nativets + WORKER_TAGS: bun,go,python3,bash,dependency,flow,nativets options: >- --pull always @@ -235,7 +235,7 @@ jobs: LICENSE_KEY: ${{ secrets.WM_LICENSE_KEY_CI }} MODE: worker WORKER_GROUP: main - WORKER_TAGS: deno,bun,go,python3,bash,dependency,flow,nativets + WORKER_TAGS: bun,go,python3,bash,dependency,flow,nativets options: >- --pull always @@ -246,7 +246,7 @@ jobs: LICENSE_KEY: ${{ secrets.WM_LICENSE_KEY_CI }} MODE: worker WORKER_GROUP: main - WORKER_TAGS: deno,bun,go,python3,bash,dependency,flow,nativets + WORKER_TAGS: bun,go,python3,bash,dependency,flow,nativets options: >- --pull always @@ -257,7 +257,7 @@ jobs: LICENSE_KEY: ${{ secrets.WM_LICENSE_KEY_CI }} MODE: worker WORKER_GROUP: main - WORKER_TAGS: deno,bun,go,python3,bash,dependency,flow,nativets + WORKER_TAGS: bun,go,python3,bash,dependency,flow,nativets options: >- --pull always @@ -268,7 +268,7 @@ jobs: LICENSE_KEY: ${{ secrets.WM_LICENSE_KEY_CI }} MODE: worker WORKER_GROUP: main - WORKER_TAGS: deno,bun,go,python3,bash,dependency,flow,nativets + WORKER_TAGS: bun,go,python3,bash,dependency,flow,nativets options: >- --pull always steps: @@ -309,7 +309,7 @@ jobs: DATABASE_URL: postgres://postgres:changeme@postgres:5432/windmill LICENSE_KEY: ${{ secrets.WM_LICENSE_KEY_CI }} WORKER_GROUP: main - WORKER_TAGS: deno,bun,go,python3,bash,dependency,flow,nativets + WORKER_TAGS: bun,go,python3,bash,dependency,flow,nativets options: >- --pull always --health-interval 10s --health-timeout 5s --health-retries 5 --health-cmd "curl diff --git a/.github/workflows/build-publish-rh-image.yml b/.github/workflows/build-publish-rh-image.yml index dcb223b534..f037e7eb75 100644 --- a/.github/workflows/build-publish-rh-image.yml +++ b/.github/workflows/build-publish-rh-image.yml @@ -83,17 +83,17 @@ jobs: # Extract arm64 binary (include deps/ for hard link resolution) mkdir -p /tmp/arm64 crane export --platform linux/arm64 ${{ steps.meta-ee-public.outputs.tags }} - \ - | tar -xf - -C /tmp/arm64 windmill/target/release/ usr/src/app/libwindmill_duckdb_ffi_internal.so + | tar -xf - -C /tmp/arm64 windmill/target/release/ usr/src/app/windmill_duckdb_runner cp /tmp/arm64/windmill/target/release/windmill extracted/windmill-ee-arm64-rhel9 - cp /tmp/arm64/usr/src/app/libwindmill_duckdb_ffi_internal.so extracted/libwindmill_duckdb_ffi_internal-arm64.so + cp /tmp/arm64/usr/src/app/windmill_duckdb_runner extracted/windmill_duckdb_runner-arm64 rm -rf /tmp/arm64 # Extract amd64 binary mkdir -p /tmp/amd64 crane export --platform linux/amd64 ${{ steps.meta-ee-public.outputs.tags }} - \ - | tar -xf - -C /tmp/amd64 windmill/target/release/ usr/src/app/libwindmill_duckdb_ffi_internal.so + | tar -xf - -C /tmp/amd64 windmill/target/release/ usr/src/app/windmill_duckdb_runner cp /tmp/amd64/windmill/target/release/windmill extracted/windmill-ee-amd64-rhel9 - cp /tmp/amd64/usr/src/app/libwindmill_duckdb_ffi_internal.so extracted/libwindmill_duckdb_ffi_internal-amd64.so + cp /tmp/amd64/usr/src/app/windmill_duckdb_runner extracted/windmill_duckdb_runner-amd64 rm -rf /tmp/amd64 - uses: actions/upload-artifact@v4 @@ -109,9 +109,9 @@ jobs: - uses: actions/upload-artifact@v4 with: name: RHEL9-arm64 dynamic libraries build - path: extracted/libwindmill_duckdb_ffi_internal-arm64.so + path: extracted/windmill_duckdb_runner-arm64 - uses: actions/upload-artifact@v4 with: name: RHEL9-amd64 dynamic libraries build - path: extracted/libwindmill_duckdb_ffi_internal-amd64.so + path: extracted/windmill_duckdb_runner-amd64 diff --git a/.github/workflows/build-publish-rh8-image.yml b/.github/workflows/build-publish-rh8-image.yml index 7c820eb290..83b12d3290 100644 --- a/.github/workflows/build-publish-rh8-image.yml +++ b/.github/workflows/build-publish-rh8-image.yml @@ -103,7 +103,7 @@ jobs: id: extract-duckdb-ffi-internal with: image: ${{ steps.meta-ee-public.outputs.tags}}-amd64 - path: "/usr/src/app/libwindmill_duckdb_ffi_internal.so" + path: "/usr/src/app/windmill_duckdb_runner" # - uses: shrink/actions-docker-extract@v3 # id: extract-ee-arm64 @@ -124,7 +124,7 @@ jobs: - uses: actions/upload-artifact@v4 with: name: RHEL8-amd64 dynamic libraries build - path: ${{ steps.extract-duckdb-ffi-internal.outputs.destination }}/libwindmill_duckdb_ffi_internal.so + path: ${{ steps.extract-duckdb-ffi-internal.outputs.destination }}/windmill_duckdb_runner # - uses: actions/upload-artifact@v4 # with: diff --git a/.github/workflows/build_windows_worker_.yml b/.github/workflows/build_windows_worker_.yml index 46befe42b6..4a6368ee1e 100644 --- a/.github/workflows/build_windows_worker_.yml +++ b/.github/workflows/build_windows_worker_.yml @@ -81,5 +81,5 @@ jobs: - name: Upload dynamic libraries artifact uses: actions/upload-artifact@v4 with: - name: windmill_duckdb_ffi_internal.dll - path: ./backend/windmill-duckdb-ffi-internal/target/release/windmill_duckdb_ffi_internal.dll + name: windmill_duckdb_runner.exe + path: ./backend/windmill-duckdb-ffi-internal/target/release/windmill_duckdb_runner.exe diff --git a/.github/workflows/docker-image.yml b/.github/workflows/docker-image.yml index c94521d332..51da953ab0 100644 --- a/.github/workflows/docker-image.yml +++ b/.github/workflows/docker-image.yml @@ -218,7 +218,7 @@ jobs: id: extract-duckdb-ffi-internal with: image: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}@${{ needs.build.outputs.digest }} - path: "/usr/src/app/libwindmill_duckdb_ffi_internal.so" + path: "/usr/src/app/windmill_duckdb_runner" - uses: shrink/actions-docker-extract@v3 id: extract-ee @@ -239,7 +239,7 @@ jobs: ${{ steps.extract-ee.outputs.destination }}/* ${{ steps.extract-duckdb-ffi-internal.outputs.destination }}/* - attach_ee_debug_to_release: + upload_ee_debug_to_s3: needs: [build_ee] runs-on: ubicloud if: ${{ startsWith(github.ref, 'refs/tags/v') }} @@ -284,14 +284,21 @@ jobs: WM_BUILD_VERSION=${{ github.sha }} outputs: type=local,dest=./debuginfo - - name: Rename debug file with corresponding architecture + # The debug file names every EE function with its source file and line, so it + # goes to a private bucket, never to the public release. + - name: Upload debug file to private bucket + env: + AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + AWS_DEFAULT_REGION: us-east-1 + TAG: ${{ github.ref_name }} + ARCH: ${{ matrix.arch }} run: | - mv ./debuginfo/windmill.debug ./debuginfo/windmill-ee-${{ matrix.arch }}.debug - - - name: Attach debug file to release - uses: softprops/action-gh-release@v2 - with: - files: ./debuginfo/windmill-ee-${{ matrix.arch }}.debug + aws --version + aws configure set default.s3.multipart_chunksize 64MB + aws s3 cp ./debuginfo/windmill.debug \ + "s3://windmill-ee-debuginfo/$TAG/windmill-ee-$ARCH.debug" \ + --storage-class GLACIER_IR --only-show-errors # attach_arm64_binary_to_release: # needs: [build, build_ee] diff --git a/.github/workflows/npm_on_release.yml b/.github/workflows/npm_on_release.yml index 631ab53153..a2bd974daa 100644 --- a/.github/workflows/npm_on_release.yml +++ b/.github/workflows/npm_on_release.yml @@ -18,16 +18,19 @@ jobs: env: NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} publish_chat_sdk: - runs-on: ubicloud-standard-8 + # Published by npm trusted publishing (OIDC), which npm accepts only from + # GitHub-hosted runners and npm >= 11.5.1: keep both, there is no token to fall back on. + runs-on: ubuntu-latest + permissions: + contents: read + id-token: write steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v7 with: - node-version: "20.x" + node-version: "24.x" registry-url: "https://registry.npmjs.org" - run: cd chat-sdk && npm ci && npm run build && npm publish --access public - env: - NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} publish_cli: runs-on: ubicloud-standard-8 steps: diff --git a/.github/workflows/publish_windows_worker.yml b/.github/workflows/publish_windows_worker.yml index b94d5d57c7..ecceff03ab 100644 --- a/.github/workflows/publish_windows_worker.yml +++ b/.github/workflows/publish_windows_worker.yml @@ -72,8 +72,8 @@ jobs: files: | ./backend/target/release/windmill-ee.exe - - name: Attach dynamic libraries to release + - name: Attach the DuckDB runner to release uses: softprops/action-gh-release@v2 with: files: | - ./backend/windmill-duckdb-ffi-internal/target/release/windmill_duckdb_ffi_internal.dll + ./backend/windmill-duckdb-ffi-internal/target/release/windmill_duckdb_runner.exe diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 62ac9abafe..3714717023 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.827.0" + ".": "1.841.0" } diff --git a/AGENTS.md b/AGENTS.md index e4915cdcb6..6516e0e095 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -33,12 +33,20 @@ Open-source platform for internal tools, workflows, API integrations, background administers behind `external_instance` data tables and Ducklake catalogs: its invariants (one lifecycle lock, managed-object markers, the setup gate, per-cluster roles, fork copy ownership) and how to run one locally +- **Fork object storage**: `docs/fork-object-storage.md` — how a fork's object keys map under + `__wm_forks//` with read-through to its ancestors, where the mapping must be applied, + and why `__wm_forks/` is reachable only through a workspace's own chain +- **Data table viewer roles**: `docs/datatable-viewer-roles.md`, on what a connection naming no + role holds: the default role as a floor, whose roles are added (the job's own, or its viewer's + for an inline app runnable that opts in), why an admin's roles are not added, the per-role-set + logins and the order their rows and logins are written in - **Enterprise**: `docs/enterprise.md` — EE file conventions and PR workflow - **Operator write rights**: `docs/operator-write-rights.md` — which `operator_settings` flags are enforced rather than cosmetic, and why a right that is granted-unless-withdrawn needs `Option` fields and a jsonb merge rather than a serde default -- **Operator builder rights**: `docs/operator-builder-rights.md` — the workspace setting that lets - operators compose flows, what the composition check must cover, and why it costs a full seat +- **Operator builder rights**: `docs/operator-builder-rights.md` — the workspace settings that let + operators compose flows and full-code apps, what the composition check must cover, which + raw-app endpoint stays closed on purpose, and why either right costs a full seat - **Auth surface**: `docs/auth-surface.md` — credential precedence, session/cache invalidation scope, which token labels email their owner at expiry, how OAuth login matches `login_type`, and that every superadmin route refuses `$WM_TOKEN`. Read before designing anything that creates diff --git a/CHANGELOG.md b/CHANGELOG.md index 1b157fa61d..659adb9e25 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,311 @@ # Changelog +## [1.841.0](https://github.com/windmill-labs/windmill/compare/v1.840.0...v1.841.0) (2026-10-18) + + +### Features + +* let agent workers authenticate with a workload identity token ([#11858](https://github.com/windmill-labs/windmill/issues/11858)) ([be23abb](https://github.com/windmill-labs/windmill/commit/be23abb3602ed9c45f1c66c98d5f84e7676dccfa)) +* let ALLOW_PRIVATE_MCP_SERVER_URLS name the private hosts it allows ([#11869](https://github.com/windmill-labs/windmill/issues/11869)) ([5c205fa](https://github.com/windmill-labs/windmill/commit/5c205fa46915de9e5fde731a117ba8571cfa56f7)) +* probe nsjail with a real jail and add a gVisor compat mode ([#11865](https://github.com/windmill-labs/windmill/issues/11865)) ([69d36f7](https://github.com/windmill-labs/windmill/commit/69d36f77daceb25cc903c7ea014ba8d487650b18)) + + +### Bug Fixes + +* insert ApiAuthed into request extensions in no-auth mode ([#11868](https://github.com/windmill-labs/windmill/issues/11868)) ([a7561fd](https://github.com/windmill-labs/windmill/commit/a7561fd8bde5c4a766a050507c2d9b9823c08bcc)) +* reject out-of-range integer args to narrow SQL types instead of wrapping ([#11864](https://github.com/windmill-labs/windmill/issues/11864)) ([19ec5d3](https://github.com/windmill-labs/windmill/commit/19ec5d3cd8a36600c8896a895d0e566735f729a9)) +* warn when an autoscaled worker group has no tags to count ([#11859](https://github.com/windmill-labs/windmill/issues/11859)) ([8b14a78](https://github.com/windmill-labs/windmill/commit/8b14a78822f95fb045d80940dfd9197f79ea88cc)) + +## [1.840.0](https://github.com/windmill-labs/windmill/compare/v1.839.0...v1.840.0) (2026-10-17) + + +### Features + +* add a no_network annotation for sandboxed jobs ([#11844](https://github.com/windmill-labs/windmill/issues/11844)) ([feb7b1a](https://github.com/windmill-labs/windmill/commit/feb7b1ad906046f4cf6ea53a85506f42b1b66e93)) +* warn at worker startup when WHITELIST_ENVS forwards a secret-shaped variable ([#11838](https://github.com/windmill-labs/windmill/issues/11838)) ([16c8be2](https://github.com/windmill-labs/windmill/commit/16c8be2355b919878091769810749c54c2f0a09d)) + + +### Bug Fixes + +* keep script and flow deploys off a second pool connection ([#11843](https://github.com/windmill-labs/windmill/issues/11843)) ([2684156](https://github.com/windmill-labs/windmill/commit/268415623b515280b99bd5d9e32876868821dc4f)) +* let ALLOW_PRIVATE_AI_BASE_URLS name the private hosts it allows ([#11841](https://github.com/windmill-labs/windmill/issues/11841)) ([b0c97b3](https://github.com/windmill-labs/windmill/commit/b0c97b34caa6343db278a9c5c09228248acf970c)) +* mount python script modules into the nsjail sandbox ([#11846](https://github.com/windmill-labs/windmill/issues/11846)) ([7a8cb62](https://github.com/windmill-labs/windmill/commit/7a8cb62fa135bff04522f4bbd93aba194e33b121)) +* refuse dot segments in AI proxy paths ([#11837](https://github.com/windmill-labs/windmill/issues/11837)) ([89f36a7](https://github.com/windmill-labs/windmill/commit/89f36a73d16675fd5f0d57daa2baf616ee95cbf5)) +* run bun and npm installs under nsjail sandboxing ([#11845](https://github.com/windmill-labs/windmill/issues/11845)) ([6646c86](https://github.com/windmill-labs/windmill/commit/6646c86351f188d9b7e355dfb46e87bfa5c81846)) +* scope delete_jobs side-table deletes to the request workspace ([#11836](https://github.com/windmill-labs/windmill/issues/11836)) ([09a5911](https://github.com/windmill-labs/windmill/commit/09a59110d941a8c306a0d89e99d34d509545059f)) +* skip the fork lock when a fork creation has no storage to purge ([#11842](https://github.com/windmill-labs/windmill/issues/11842)) ([0b54ebc](https://github.com/windmill-labs/windmill/commit/0b54ebc73d3d9541d2521857adc27766c4342000)) + + +### Performance Improvements + +* clone sqlx test databases from a migrated template ([#11848](https://github.com/windmill-labs/windmill/issues/11848)) ([4ed6c1a](https://github.com/windmill-labs/windmill/commit/4ed6c1a6ce1b6d53ea9ee965214da0c3adb3f3bd)) + +## [1.839.0](https://github.com/windmill-labs/windmill/compare/v1.838.0...v1.839.0) (2026-10-16) + + +### Features + +* add a Require isolated forks protection rule ([#11834](https://github.com/windmill-labs/windmill/issues/11834)) ([ab4e790](https://github.com/windmill-labs/windmill/commit/ab4e790a216b92f789e130955d7cd180b394d1fe)) +* isolate fork object storage under a per-fork prefix ([#11829](https://github.com/windmill-labs/windmill/issues/11829)) ([9375805](https://github.com/windmill-labs/windmill/commit/9375805fdf7501347a4dfb37e58f1be7fa2c5658)) +* one Entra app for the Teams bot and ms_teams Graph connect ([#11718](https://github.com/windmill-labs/windmill/issues/11718)) ([e7088e7](https://github.com/windmill-labs/windmill/commit/e7088e7f4766cd662890cdf61f2b6a5a0fce06a8)) +* route python S3 client settings through the S3 proxy ([#11819](https://github.com/windmill-labs/windmill/issues/11819)) ([de340ee](https://github.com/windmill-labs/windmill/commit/de340eed6f5520414b59166f8dc16938f7ac6c36)) + + +### Bug Fixes + +* verify Bot Framework JWT on incoming Teams activities ([#11818](https://github.com/windmill-labs/windmill/issues/11818)) ([0b1935f](https://github.com/windmill-labs/windmill/commit/0b1935f251605926760565fb7693f345f1a56312)) + +## [1.838.0](https://github.com/windmill-labs/windmill/compare/v1.837.0...v1.838.0) (2026-10-16) + + +### Features + +* accept Ed25519-signed license keys alongside RSA ([#11810](https://github.com/windmill-labs/windmill/issues/11810)) ([33d4049](https://github.com/windmill-labs/windmill/commit/33d4049db029e1dc478b1251c562232f0127fc8a)) +* make the frontend installable as a progressive web app ([#11805](https://github.com/windmill-labs/windmill/issues/11805)) ([b86909f](https://github.com/windmill-labs/windmill/commit/b86909fc81b21447414266f47a83a43492204e50)) +* name mcp script and flow tools after their last path segment ([#11817](https://github.com/windmill-labs/windmill/issues/11817)) ([d1a13d9](https://github.com/windmill-labs/windmill/commit/d1a13d9054d5994b5ed9c0f8566b86154662caa0)) +* route dev workspace and fork jobs to their own worker groups ([#11811](https://github.com/windmill-labs/windmill/issues/11811)) ([6e565b0](https://github.com/windmill-labs/windmill/commit/6e565b0dcb0fb56b69131c262d482c82bb6c527b)) + + +### Bug Fixes + +* **ai-chat:** tell the session chat that an agent is an ai_agent resource ([#11798](https://github.com/windmill-labs/windmill/issues/11798)) ([a521548](https://github.com/windmill-labs/windmill/commit/a52154877caa5c3e473ee56c1eaf040b7da2375f)) +* emit a single email claim in job OIDC tokens ([#11804](https://github.com/windmill-labs/windmill/issues/11804)) ([2ef0c0d](https://github.com/windmill-labs/windmill/commit/2ef0c0d8e14fcd5ff1c06f6113ffaf2792b9d4c9)) +* give inline script runs their own job dir ([#11822](https://github.com/windmill-labs/windmill/issues/11822)) ([6aec448](https://github.com/windmill-labs/windmill/commit/6aec4488ebe8f377b4ea9bb4948649831cba0dbc)) +* hold mcp token references to resource reference scopes ([#11803](https://github.com/windmill-labs/windmill/issues/11803)) ([c09038b](https://github.com/windmill-labs/windmill/commit/c09038b10698042209fd6aa26c466fb53d6dc7d0)) +* let deployed low-code apps run database studio queries again ([#11816](https://github.com/windmill-labs/windmill/issues/11816)) ([7c63a30](https://github.com/windmill-labs/windmill/commit/7c63a30edd650f49eff85066dcc7916cec1b7010)) +* truncate long row titles instead of wrapping ([#11815](https://github.com/windmill-labs/windmill/issues/11815)) ([153a871](https://github.com/windmill-labs/windmill/commit/153a871550e3ae9ad6282aa59b3a4f9897fec6c1)) +* use the session workspace's user in three AI session places ([#11808](https://github.com/windmill-labs/windmill/issues/11808)) ([19fc07f](https://github.com/windmill-labs/windmill/commit/19fc07faa95a8a2247e726f9d0a2adc3cfa42bd2)) + +## [1.837.0](https://github.com/windmill-labs/windmill/compare/v1.836.0...v1.837.0) (2026-10-15) + + +### Features + +* agents run on behalf of their deployer ([#11430](https://github.com/windmill-labs/windmill/issues/11430)) ([0b98054](https://github.com/windmill-labs/windmill/commit/0b980546b104cf46f385133af553dfbe5f533eca)) + +## [1.836.0](https://github.com/windmill-labs/windmill/compare/v1.835.0...v1.836.0) (2026-10-15) + + +### Features + +* **cli:** sync an app's custom path as a workspace-specific file ([#11786](https://github.com/windmill-labs/windmill/issues/11786)) ([718aad7](https://github.com/windmill-labs/windmill/commit/718aad7396397fe12295a27a947c76221f37ad10)) +* let operators save resource and variable drafts ([#11736](https://github.com/windmill-labs/windmill/issues/11736)) ([8c0185d](https://github.com/windmill-labs/windmill/commit/8c0185d55a1a8c6fbc5e41b8b9d77865563f515b)) +* let raw app backend runnables import each other ([#11777](https://github.com/windmill-labs/windmill/issues/11777)) ([526da60](https://github.com/windmill-labs/windmill/commit/526da60da92832cc6e9c2942cea1f7729b3a05fd)) +* let the session agent read folder and group permissions ([#11796](https://github.com/windmill-labs/windmill/issues/11796)) ([eda43dd](https://github.com/windmill-labs/windmill/commit/eda43ddc41c10b3f7263103016275926a33bf768)) +* resolve canceled jobs and re-run them in limited batches ([#11797](https://github.com/windmill-labs/windmill/issues/11797)) ([f827ba0](https://github.com/windmill-labs/windmill/commit/f827ba05667e3ca5bcd3bc89dac7f51b85dd32b3)) +* run duckdb jobs out of process under job isolation, drop the engine fork, bump to 1.5.6 ([#11780](https://github.com/windmill-labs/windmill/issues/11780)) ([f9513e8](https://github.com/windmill-labs/windmill/commit/f9513e82eed3721ecbfd87004d1cd385ac740903)) +* run previews as the runnable's on_behalf_of identity ([#11778](https://github.com/windmill-labs/windmill/issues/11778)) ([4f71231](https://github.com/windmill-labs/windmill/commit/4f712318c3b52366b03bf7f941ecae4730fbf967)) +* sandbox new low-code and raw apps by default ([#11760](https://github.com/windmill-labs/windmill/issues/11760)) ([813c080](https://github.com/windmill-labs/windmill/commit/813c080d4684eecd144ef82706b04339c8f8d35a)) +* share AI sessions read-only by link, optionally public ([#11799](https://github.com/windmill-labs/windmill/issues/11799)) ([a9aa2b8](https://github.com/windmill-labs/windmill/commit/a9aa2b8229da0d54ed68eb40e4426e6983ff631e)) + + +### Bug Fixes + +* **cli:** include script modules in wmill dev previews ([#11787](https://github.com/windmill-labs/windmill/issues/11787)) ([b563f5c](https://github.com/windmill-labs/windmill/commit/b563f5cb5121c431f525c2e0266994c6d655185b)) +* let raw app SDK tokens read the viewer's identity without a toggle ([#11790](https://github.com/windmill-labs/windmill/issues/11790)) ([7da2344](https://github.com/windmill-labs/windmill/commit/7da234481333fcbdc348215589e2d3bfe5394b4a)) +* let Teams handlers post with job tokens again ([#11792](https://github.com/windmill-labs/windmill/issues/11792)) ([64e1630](https://github.com/windmill-labs/windmill/commit/64e1630d497af1b50a772aa66ef123f675ea6bb1)) +* relock apps in place so imported script changes reach them ([#11789](https://github.com/windmill-labs/windmill/issues/11789)) ([aca7fed](https://github.com/windmill-labs/windmill/commit/aca7fed33ddffa17b0e78d50a39ded032f6d8ba2)) +* relock scripts and flow steps whose code changed on deploy ([#11794](https://github.com/windmill-labs/windmill/issues/11794)) ([1f1df12](https://github.com/windmill-labs/windmill/commit/1f1df1254ebc417a8344801b571c4be8e98636c4)) +* send Azure Foundry gpt-5.5+ models to the Responses API ([#11788](https://github.com/windmill-labs/windmill/issues/11788)) ([ab89835](https://github.com/windmill-labs/windmill/commit/ab8983543b0641c96a8b4a2cbd829cc4040e9f41)) +* show the app's summary in the app viewer's page header ([#11782](https://github.com/windmill-labs/windmill/issues/11782)) ([3bee9c9](https://github.com/windmill-labs/windmill/commit/3bee9c94012474b7bb230d719fa34df0c0a6c25e)) + + +### Performance Improvements + +* drive schedule already-exists check from an indexed queue lookup ([#11783](https://github.com/windmill-labs/windmill/issues/11783)) ([7eee210](https://github.com/windmill-labs/windmill/commit/7eee210d761d332f8165b4f8a6f0ee6f1ec8864f)) + +## [1.835.0](https://github.com/windmill-labs/windmill/compare/v1.834.0...v1.835.0) (2026-10-14) + + +### Features + +* allow early return on steps inside branches ([#11733](https://github.com/windmill-labs/windmill/issues/11733)) ([08319a0](https://github.com/windmill-labs/windmill/commit/08319a004c289f93398b9fdc790b2ed412a81fa4)) +* run global ai eval cases under builder operator profiles ([#11768](https://github.com/windmill-labs/windmill/issues/11768)) ([d788f16](https://github.com/windmill-labs/windmill/commit/d788f16c4028985afd2b82f35d625b0a12c04653)) +* search the workspace picker dropdown past 8 workspaces ([#11761](https://github.com/windmill-labs/windmill/issues/11761)) ([c1a561f](https://github.com/windmill-labs/windmill/commit/c1a561f5ec091de0ae2de12ee811ca628c58c9f5)) + + +### Bug Fixes + +* show native triggers in the operator sidebar ([#11769](https://github.com/windmill-labs/windmill/issues/11769)) ([717162e](https://github.com/windmill-labs/windmill/commit/717162eab44757182a4a67316c288e188f811599)) + +## [1.834.0](https://github.com/windmill-labs/windmill/compare/v1.833.0...v1.834.0) (2026-10-14) + + +### Features + +* add a navigation picker after the breadcrumb's last segment ([#11649](https://github.com/windmill-labs/windmill/issues/11649)) ([9653318](https://github.com/windmill-labs/windmill/commit/9653318c17225b35c474722d49f38dc2ecd3b9f6)) +* add a yaml mode to the workspace settings page ([#11751](https://github.com/windmill-labs/windmill/issues/11751)) ([b543b43](https://github.com/windmill-labs/windmill/commit/b543b43d734a309278b72fdd958570b9c7ff6d5f)) +* give full-code app previews the deployed app's window.ctx ([#11763](https://github.com/windmill-labs/windmill/issues/11763)) ([c5e6f67](https://github.com/windmill-labs/windmill/commit/c5e6f67d5307146569e2fd1a37033c9dddb680c4)) +* guide the AI when no resource type fits a service ([#11615](https://github.com/windmill-labs/windmill/issues/11615)) ([88c3cc0](https://github.com/windmill-labs/windmill/commit/88c3cc0ced8fe3183979f0abd8e05846f6f4a8e6)) +* let a linked agent step override model and reasoning effort ([#11685](https://github.com/windmill-labs/windmill/issues/11685)) ([9249aa0](https://github.com/windmill-labs/windmill/commit/9249aa02d592e60024d7475627cbf664936e4a5d)) +* let operators with manage rights save schedule and trigger drafts ([#11646](https://github.com/windmill-labs/windmill/issues/11646)) ([74c5f82](https://github.com/windmill-labs/windmill/commit/74c5f82c6703a08a6d1a896b5e46b7007f2e3d73)) +* list agents with runnables, let them be starred, and fill out their menu ([#11651](https://github.com/windmill-labs/windmill/issues/11651)) ([fe2571e](https://github.com/windmill-labs/windmill/commit/fe2571ea53603625f48601aa800e9f700322d5b8)) +* list the user's own forks first in fork pickers ([#11762](https://github.com/windmill-labs/windmill/issues/11762)) ([009482a](https://github.com/windmill-labs/windmill/commit/009482a67747ec9e8f2b6b7baddb5e0e9fe720c5)) +* read and change workspace settings from ai sessions and mcp ([#11741](https://github.com/windmill-labs/windmill/issues/11741)) ([468cf1d](https://github.com/windmill-labs/windmill/commit/468cf1d9941538d285264e8a8c57356b934ab25d)) +* scope data table migrations to the schemas they declare ([#11756](https://github.com/windmill-labs/windmill/issues/11756)) ([2410790](https://github.com/windmill-labs/windmill/commit/2410790c7e343920ae2bb6f2405a0b7f7660be7f)) +* **sessions:** run a deployed item from its own page, for the chat ([#11468](https://github.com/windmill-labs/windmill/issues/11468)) ([998e687](https://github.com/windmill-labs/windmill/commit/998e6877c1cf07bb1a08fd1d3b18948fbc0e30e0)) +* workspace settings as one document, applied server-side ([#11740](https://github.com/windmill-labs/windmill/issues/11740)) ([9a5ec22](https://github.com/windmill-labs/windmill/commit/9a5ec223bc7dd1b5c4e58a9cc883a5d4e5d9237b)) + + +### Bug Fixes + +* **cli:** keep script run waiting on long jobs and flaky log streaming ([#11766](https://github.com/windmill-labs/windmill/issues/11766)) ([a2ee052](https://github.com/windmill-labs/windmill/commit/a2ee052e0326bf69f49596cdc008bbc8ca596e3c)) +* fork data tables sharing one database into a single copy ([#11755](https://github.com/windmill-labs/windmill/issues/11755)) ([4914782](https://github.com/windmill-labs/windmill/commit/49147827d69bc241c57407f539ec7e2621830d1b)) +* keep applied migrations and db settings in data table copies ([#11753](https://github.com/windmill-labs/windmill/issues/11753)) ([694ed7a](https://github.com/windmill-labs/windmill/commit/694ed7a0eba255ef42e6cfe988ea3b8c5784dfa1)) +* unify cron builder control sizes and widths ([#11764](https://github.com/windmill-labs/windmill/issues/11764)) ([17fefcf](https://github.com/windmill-labs/windmill/commit/17fefcf777063849ca8ec1e097bf02e826c0b3a7)) +* **worker:** keep script env vars off the nsjail launcher process ([#11749](https://github.com/windmill-labs/windmill/issues/11749)) ([1c068f3](https://github.com/windmill-labs/windmill/commit/1c068f33e144af81f202e21e23960af4a17a6b4a)) + +## [1.833.0](https://github.com/windmill-labs/windmill/compare/v1.832.0...v1.833.0) (2026-10-13) + + +### Features + +* make the assistant aware of the user's role permissions ([#11722](https://github.com/windmill-labs/windmill/issues/11722)) ([633135b](https://github.com/windmill-labs/windmill/commit/633135bb917ce1be711a75991531c3e478d73463)) +* read data as the job's identity, viewer is opt-in per runnable ([#11744](https://github.com/windmill-labs/windmill/issues/11744)) ([b7b3306](https://github.com/windmill-labs/windmill/commit/b7b33061952fde247447fa652663ffd730990d5e)) +* show a raw app's document.title in the page tab ([#11747](https://github.com/windmill-labs/windmill/issues/11747)) ([5153a5e](https://github.com/windmill-labs/windmill/commit/5153a5e7b81e9d56ff860129be7c49f444c3c4e2)) +* shrink the page header in stages and fold page actions by measured width ([#11732](https://github.com/windmill-labs/windmill/issues/11732)) ([3857ce3](https://github.com/windmill-labs/windmill/commit/3857ce36931dff40322db2b765ab1e65763eac42)) + + +### Bug Fixes + +* encrypt ai session backups with aes-256-gcm ([#11734](https://github.com/windmill-labs/windmill/issues/11734)) ([c7ee201](https://github.com/windmill-labs/windmill/commit/c7ee2016559b8083c83c696c41d226d9ca04ed68)) +* error handler picker keeps no per-tab state ([#11742](https://github.com/windmill-labs/windmill/issues/11742)) ([2f9a111](https://github.com/windmill-labs/windmill/commit/2f9a111bbb14a40e1341879e1ef63c3457e7a08d)) +* show the email handler's SMTP status to non-superadmin admins ([#11745](https://github.com/windmill-labs/windmill/issues/11745)) ([130adfd](https://github.com/windmill-labs/windmill/commit/130adfdd20af0e30d87986cf77b61023a9732186)) + +## [1.832.0](https://github.com/windmill-labs/windmill/compare/v1.831.0...v1.832.0) (2026-10-13) + + +### Features + +* record each instance's python version and start new ones on 3.13 ([#11656](https://github.com/windmill-labs/windmill/issues/11656)) ([7558ce2](https://github.com/windmill-labs/windmill/commit/7558ce27a9736bef1a9b9db9b0799150dccb11a5)) + + +### Bug Fixes + +* badge the unavailable sign-in option in the oauth resource form ([#11728](https://github.com/windmill-labs/windmill/issues/11728)) ([9c44f5a](https://github.com/windmill-labs/windmill/commit/9c44f5a917fc628e870073c126bf9480c98c7f73)) +* serve s3 proxy objects with nosniff and a sandbox csp ([#11731](https://github.com/windmill-labs/windmill/issues/11731)) ([e29a0dc](https://github.com/windmill-labs/windmill/commit/e29a0dc5dfed4bb62b894e059c9506873d32a62c)) +* widen variable.value without breaking live servers' cached queries ([#11737](https://github.com/windmill-labs/windmill/issues/11737)) ([89e6bdb](https://github.com/windmill-labs/windmill/commit/89e6bdbcf50e065f6906e1ab93b3c4109aba3ab6)) + +## [1.831.0](https://github.com/windmill-labs/windmill/compare/v1.830.0...v1.831.0) (2026-10-13) + + +### Features + +* add python 3.14 and 3.15 to the supported instance versions ([#11654](https://github.com/windmill-labs/windmill/issues/11654)) ([74c9b0c](https://github.com/windmill-labs/windmill/commit/74c9b0cb2eebc16dd5e23f23be89b127bcbe6ec2)) +* add the viewer's roles to unnamed data table connections ([#11709](https://github.com/windmill-labs/windmill/issues/11709)) ([a298ed3](https://github.com/windmill-labs/windmill/commit/a298ed3fc19a1b7fc4f8e75a95c8d38652b74b5b)) +* audit declarative instance config writes ([#11684](https://github.com/windmill-labs/windmill/issues/11684)) ([afbbc0b](https://github.com/windmill-labs/windmill/commit/afbbc0b1b2da1e468b10d4cd11e9f3ac7478a34d)) +* **cli:** declare app sandbox and frontend api scopes in app yaml ([#11703](https://github.com/windmill-labs/windmill/issues/11703)) ([26afeec](https://github.com/windmill-labs/windmill/commit/26afeecbd5b0a11c084813182e92805a15d21bbb)) +* data table migration tools in ai sessions ([#11723](https://github.com/windmill-labs/windmill/issues/11723)) ([3d74f6e](https://github.com/windmill-labs/windmill/commit/3d74f6ea2a44e85d056411c293087741f6f1e12a)) +* encrypt workspace secrets with AES-256-GCM ([#11678](https://github.com/windmill-labs/windmill/issues/11678)) ([4942149](https://github.com/windmill-labs/windmill/commit/4942149b05c9384b39402f0e3cb7771565888f45)) +* external signer for OIDC tokens and a log line per mint ([#11614](https://github.com/windmill-labs/windmill/issues/11614)) ([157183a](https://github.com/windmill-labs/windmill/commit/157183ae9cad4b6b2d38f1f4d915f32464792453)) +* give app builder operators app tools in AI sessions ([#11716](https://github.com/windmill-labs/windmill/issues/11716)) ([133613c](https://github.com/windmill-labs/windmill/commit/133613c1add5b6fcdbb0937de6479976b716c90a)) +* redesign the s3 explorer and show data files as tables ([#11642](https://github.com/windmill-labs/windmill/issues/11642)) ([9fa9b77](https://github.com/windmill-labs/windmill/commit/9fa9b7792676fbedcbc4dc37ebb883f5ff5abb35)) +* support array arguments in snowflake scripts ([#11702](https://github.com/windmill-labs/windmill/issues/11702)) ([1451988](https://github.com/windmill-labs/windmill/commit/14519884e4c9aa4d0a006cbc019a776f9a038967)) + + +### Bug Fixes + +* bump git sync hub scripts to cli 1.830.0 ([#11681](https://github.com/windmill-labs/windmill/issues/11681)) ([7bbe032](https://github.com/windmill-labs/windmill/commit/7bbe03227d56688893aafda305a13d65b2bb84f4)) +* end other sessions when a user changes their password ([#11710](https://github.com/windmill-labs/windmill/issues/11710)) ([add042e](https://github.com/windmill-labs/windmill/commit/add042ef2f05828a8ea5f6d0a089204bae2322d5)) +* fill app ctx inputs from the viewer's session, not the request ([#11698](https://github.com/windmill-labs/windmill/issues/11698)) ([7627c1b](https://github.com/windmill-labs/windmill/commit/7627c1be8d82c298173ad4a7002483d1caee6662)) +* **groups:** recompute member roles when an instance group role is cleared ([#11708](https://github.com/windmill-labs/windmill/issues/11708)) ([4be67fe](https://github.com/windmill-labs/windmill/commit/4be67fe3ac09f722f31ef85e6fc757bb0a2fabe4)) +* hide the sidebar triggers header when no trigger entry is visible ([#11715](https://github.com/windmill-labs/windmill/issues/11715)) ([e443eb3](https://github.com/windmill-labs/windmill/commit/e443eb37079734469a78af8ff4bc0f4289b28d0a)) +* keep a custom error handler's slack argument on save ([#11696](https://github.com/windmill-labs/windmill/issues/11696)) ([c6692ac](https://github.com/windmill-labs/windmill/commit/c6692ace156f5295196af07015ad82aee6391116)) +* keep ai agent schema property order stable across jobs ([#11687](https://github.com/windmill-labs/windmill/issues/11687)) ([a8e2f1f](https://github.com/windmill-labs/windmill/commit/a8e2f1f1ca28e3352aff8a450188e3ff75a9637c)) +* keep preserve_step_tags on saved branch and loop flow nodes ([#11660](https://github.com/windmill-labs/windmill/issues/11660)) ([dedd775](https://github.com/windmill-labs/windmill/commit/dedd77587f3234f3e480388b00340394794ac5bb)) +* keep the app editor's parent_version out of deployed apps ([#11719](https://github.com/windmill-labs/windmill/issues/11719)) ([2c6de9d](https://github.com/windmill-labs/windmill/commit/2c6de9d896ef37993da974418133a88798afa2bb)) +* keep the resource type index whole when a refresh fails ([#11727](https://github.com/windmill-labs/windmill/issues/11727)) ([71caac7](https://github.com/windmill-labs/windmill/commit/71caac7aec49bafe8f691e8a82b3e6df84f7e4bc)) +* keep the resource type search current between daily fills, and serve it without an index ([#11712](https://github.com/windmill-labs/windmill/issues/11712)) ([a365359](https://github.com/windmill-labs/windmill/commit/a3653593f2b064b762a19a1d4294988c27baaec0)) +* load the s3 explorer table lazily to keep monaco out of the app shell ([#11701](https://github.com/windmill-labs/windmill/issues/11701)) ([a92b29d](https://github.com/windmill-labs/windmill/commit/a92b29dae6950d29c2b8970e07d055fa02ff979e)) +* parse python 3.12-3.15 syntax in the python parsers ([#11675](https://github.com/windmill-labs/windmill/issues/11675)) ([aae5f2e](https://github.com/windmill-labs/windmill/commit/aae5f2efaa772d5bc6d7d1e4537d7f6748e50e61)) +* persist hidden languages in edit default scripts drawer ([#11693](https://github.com/windmill-labs/windmill/issues/11693)) ([aeeeb04](https://github.com/windmill-labs/windmill/commit/aeeeb042f93df32214e00040d360f20e8ed8c98a)) +* pin the floating sidebar and let page clicks through it ([#11711](https://github.com/windmill-labs/windmill/issues/11711)) ([ce45ab5](https://github.com/windmill-labs/windmill/commit/ce45ab507370662266728bf57240cc873ef28eb8)) +* resolve $var: references in mcp resource headers ([#11679](https://github.com/windmill-labs/windmill/issues/11679)) ([478eef7](https://github.com/windmill-labs/windmill/commit/478eef735222e60de8ed6086f6b036e2346f1de4)) +* resolve a new item's chosen name in session preview tools ([#11688](https://github.com/windmill-labs/windmill/issues/11688)) ([cd502a5](https://github.com/windmill-labs/windmill/commit/cd502a5270e787aeb1e5cb14e5a0e0aad8bb97b3)) +* resolve variables in the url and headers of an mcp resource ([#11680](https://github.com/windmill-labs/windmill/issues/11680)) ([4bc2394](https://github.com/windmill-labs/windmill/commit/4bc2394322f957e5cf212fa1913b2b39c1b9ca06)) +* run a workflow-as-code task called from inside a task in place ([#11699](https://github.com/windmill-labs/windmill/issues/11699)) ([72d1092](https://github.com/windmill-labs/windmill/commit/72d1092de97d7449ff03c3a44835c9d23cfe5e02)) +* stop marking run form fields as disabled for assistive tech ([#11714](https://github.com/windmill-labs/windmill/issues/11714)) ([c7df009](https://github.com/windmill-labs/windmill/commit/c7df0093d0d9a38362222b7350bf387c31af9392)) +* stop session dom tools reading a raw app preview that is not current ([#11700](https://github.com/windmill-labs/windmill/issues/11700)) ([05c7b68](https://github.com/windmill-labs/windmill/commit/05c7b688e5e963c6c313cb5da8e777cee11cd122)) +* surface oauth provider errors returned with http 200 ([#11713](https://github.com/windmill-labs/windmill/issues/11713)) ([d8ac4f5](https://github.com/windmill-labs/windmill/commit/d8ac4f59c8d570777e43a7aa7ffbc97598897cc2)) + + +### Performance Improvements + +* run shellcheck directly from the lsp launcher ([#11707](https://github.com/windmill-labs/windmill/issues/11707)) ([8cdb42a](https://github.com/windmill-labs/windmill/commit/8cdb42aaae764977008f8ac4598709c7ae09af3f)) + +## [1.830.0](https://github.com/windmill-labs/windmill/compare/v1.829.0...v1.830.0) (2026-10-09) + + +### Features + +* add a jobs:run:dependencies token scope for lock generation ([#11643](https://github.com/windmill-labs/windmill/issues/11643)) ([1dc4ed5](https://github.com/windmill-labs/windmill/commit/1dc4ed5e7fb86c9658f1f877e7b92cd9dab5e283)) +* let operators compose full-code apps when the workspace grants it ([#11229](https://github.com/windmill-labs/windmill/issues/11229)) ([02e4697](https://github.com/windmill-labs/windmill/commit/02e4697157112581e9e2a9303180077126db714b)) +* operators get AI sessions ([#11443](https://github.com/windmill-labs/windmill/issues/11443)) ([338c4e9](https://github.com/windmill-labs/windmill/commit/338c4e921dc3185d886c8b040f253285adf20efb)) +* replace the hub_sync script with an opt-in daily server sync ([#11624](https://github.com/windmill-labs/windmill/issues/11624)) ([2b55a8a](https://github.com/windmill-labs/windmill/commit/2b55a8afbc8a86c6cebe97b1cab02c313b986f22)) +* retry transient AI provider failures before output reaches readers ([#11623](https://github.com/windmill-labs/windmill/issues/11623)) ([d3ddef0](https://github.com/windmill-labs/windmill/commit/d3ddef0b7ec4705aa578c4eca24b96e9152485bd)) +* stop offering deno for new scripts, ship it only on full images ([#11648](https://github.com/windmill-labs/windmill/issues/11648)) ([cda7883](https://github.com/windmill-labs/windmill/commit/cda78830fde1b96bd3de2674e23c245b50e3c051)) + + +### Bug Fixes + +* **cli:** count superadmins as able to preserve ownership on push ([#11653](https://github.com/windmill-labs/windmill/issues/11653)) ([70db567](https://github.com/windmill-labs/windmill/commit/70db567a78b1e1bc9e2dcc9ff2139951d778117e)) +* harden app secret validation ([#11655](https://github.com/windmill-labs/windmill/issues/11655)) ([8556a7b](https://github.com/windmill-labs/windmill/commit/8556a7bebe093e0bd61c33d67415fd553f0070ad)) +* open the chat + menu without waiting on the skills and mcp fetches ([#11645](https://github.com/windmill-labs/windmill/issues/11645)) ([1fea1aa](https://github.com/windmill-labs/windmill/commit/1fea1aa6609d644e02bac8d16186f9a2dfcb63cd)) +* say Running on a chat run card only once its job exists ([#11627](https://github.com/windmill-labs/windmill/issues/11627)) ([d046187](https://github.com/windmill-labs/windmill/commit/d046187e3edd01535240c6080b483afe154ae189)) + +## [1.829.0](https://github.com/windmill-labs/windmill/compare/v1.828.0...v1.829.0) (2026-10-09) + + +### Features + +* add an api base url instance setting for displayed urls ([#11628](https://github.com/windmill-labs/windmill/issues/11628)) ([6acf185](https://github.com/windmill-labs/windmill/commit/6acf1858540e83b65b5218c50c98af692092d22e)) +* add Pi template to the AI sandbox picker ([#11619](https://github.com/windmill-labs/windmill/issues/11619)) ([a85d0b7](https://github.com/windmill-labs/windmill/commit/a85d0b76cc494aaa4a484a273ec534bdc2958102)) +* agent nits: multi-select, memory-off notice, agent step label ([#11622](https://github.com/windmill-labs/windmill/issues/11622)) ([c52ba2f](https://github.com/windmill-labs/windmill/commit/c52ba2fd30e19986522420ff02fae224a075b4f6)) +* export worker cpu, memory and occupancy metrics ([#11629](https://github.com/windmill-labs/windmill/issues/11629)) ([5d90f96](https://github.com/windmill-labs/windmill/commit/5d90f96863b64e9bc88ed35429f8068a6a788d1e)) +* let a job see that its worker is draining ([#11612](https://github.com/windmill-labs/windmill/issues/11612)) ([588d846](https://github.com/windmill-labs/windmill/commit/588d8463dfa1c8936b8753b5f0fd794ecb115203)) +* let workspace admins delete other users' drafts ([#11644](https://github.com/windmill-labs/windmill/issues/11644)) ([68376fc](https://github.com/windmill-labs/windmill/commit/68376fc011ef6406a820c69217058316514d3f8d)) +* per-script resource rollup and heaviest scripts table ([#11631](https://github.com/windmill-labs/windmill/issues/11631)) ([442357d](https://github.com/windmill-labs/windmill/commit/442357dbe8db0c52995572acd7385dedf4efdc42)) +* pipeline editor: assets-only view, Fix actions and draft triggers ([#11440](https://github.com/windmill-labs/windmill/issues/11440)) ([3dae553](https://github.com/windmill-labs/windmill/commit/3dae553576ba23b2c1f56e4deac01305c4645c01)) + + +### Bug Fixes + +* advertise the actual signing algorithm in OIDC discovery ([#11637](https://github.com/windmill-labs/windmill/issues/11637)) ([98fc65a](https://github.com/windmill-labs/windmill/commit/98fc65a16bbe2bc9515cdd5443304053c4322274)) +* ask a workspace for its session backups before pushing to it ([#11641](https://github.com/windmill-labs/windmill/issues/11641)) ([2ea846f](https://github.com/windmill-labs/windmill/commit/2ea846f563f5a77cbd3eae2eddee9e38a3700d00)) +* keep instance settings users sub-tabs from being squashed ([#11633](https://github.com/windmill-labs/windmill/issues/11633)) ([fb22e5c](https://github.com/windmill-labs/windmill/commit/fb22e5ce368eba9146e0d51b8fdabb52ca9f68f0)) +* keep raw app deploy panel settings shared with the editor ([#11616](https://github.com/windmill-labs/windmill/issues/11616)) ([0a95ea4](https://github.com/windmill-labs/windmill/commit/0a95ea47facaede2545cc4741d4a70c1c847e11a)) +* load schedules once per page load, poll critical alerts every 30s ([#11639](https://github.com/windmill-labs/windmill/issues/11639)) ([1b4e686](https://github.com/windmill-labs/windmill/commit/1b4e686b2f5de3138df0c3b6ed627ea0fe0a2f7d)) +* name the open workspace settings tab in the page header breadcrumb ([#11617](https://github.com/windmill-labs/windmill/issues/11617)) ([e233908](https://github.com/windmill-labs/windmill/commit/e233908c1e99a246dc7c94fa86ea82c5cbe9d6b3)) +* **python:** add missing import-to-package mappings for common modules ([#11638](https://github.com/windmill-labs/windmill/issues/11638)) ([ab8606f](https://github.com/windmill-labs/windmill/commit/ab8606f37921913ef1410da735abb5742c025225)) +* send hub script completions to the workspace handlers ([#11613](https://github.com/windmill-labs/windmill/issues/11613)) ([d685332](https://github.com/windmill-labs/windmill/commit/d685332771dcdfc718d7a2077fe1cdb3b323909b)) +* set WM_END_USER_EMAIL on direct script and flow runs ([#11636](https://github.com/windmill-labs/windmill/issues/11636)) ([2bdeceb](https://github.com/windmill-labs/windmill/commit/2bdeceba7fb6815cf3150ecb856afb8eb3872e44)) +* store a WAC parent's first start and wall duration ([#11625](https://github.com/windmill-labs/windmill/issues/11625)) ([8f28a58](https://github.com/windmill-labs/windmill/commit/8f28a5860595dbe558e6777a06bb97b6ec6a3e67)) +* sync back volume files rewritten to the same size ([#11620](https://github.com/windmill-labs/windmill/issues/11620)) ([2758920](https://github.com/windmill-labs/windmill/commit/2758920f1182ddd12e6473a644a4a966a435522e)) +* uniform decrypt error and clear stored credentials on logout ([#11632](https://github.com/windmill-labs/windmill/issues/11632)) ([987c321](https://github.com/windmill-labs/windmill/commit/987c321ebcd305df79fa945e941abc2b2e1d3e95)) + +## [1.828.0](https://github.com/windmill-labs/windmill/compare/v1.827.0...v1.828.0) (2026-10-08) + + +### Features + +* add gpt-6.1-sol to the chat, agent steps and weekly ai evals ([#11584](https://github.com/windmill-labs/windmill/issues/11584)) ([8f7e0c7](https://github.com/windmill-labs/windmill/commit/8f7e0c72848b56fa97f6f0141d930c7d15044864)) +* add wmill user list and document post-suspend approvers context ([#11600](https://github.com/windmill-labs/windmill/issues/11600)) ([1c2667c](https://github.com/windmill-labs/windmill/commit/1c2667cd5530925893cf69fd622938b6ffa55d1d)) +* ask before minting the frontend sdk token in the raw app editor ([#11604](https://github.com/windmill-labs/windmill/issues/11604)) ([6e948b0](https://github.com/windmill-labs/windmill/commit/6e948b07d13b85e9251c3a200bf149f167649bc4)) +* improve data table roles and grants UX ([#11562](https://github.com/windmill-labs/windmill/issues/11562)) ([d7d18f0](https://github.com/windmill-labs/windmill/commit/d7d18f00af4e2df8fcb1362c9439d2250d0ce4b6)) +* one page header across routes, and one sidebar for operators and developers ([#11310](https://github.com/windmill-labs/windmill/issues/11310)) ([41162b2](https://github.com/windmill-labs/windmill/commit/41162b270c70ddac6a256bde9acf31a629990e24)) + + +### Bug Fixes + +* add retry to runScriptByPathAsync and runScriptByHashAsync ([#11485](https://github.com/windmill-labs/windmill/issues/11485)) ([3f3b1c2](https://github.com/windmill-labs/windmill/commit/3f3b1c2c308ddaba377db45308711e7c660d8775)) +* describe exponential retry as multiplier × seconds^attempt ([#11546](https://github.com/windmill-labs/windmill/issues/11546)) ([a2e51cd](https://github.com/windmill-labs/windmill/commit/a2e51cdbaafb7d71b8e8bbd818e40c472098f9ba)) +* keep capturing job logs after a non-UTF-8 output line ([#11595](https://github.com/windmill-labs/windmill/issues/11595)) ([0e7d974](https://github.com/windmill-labs/windmill/commit/0e7d974ce9b468353ecb6618dace710704690687)) + + +### Performance Improvements + +* load public raw apps without the loading screen ([#11608](https://github.com/windmill-labs/windmill/issues/11608)) ([c09764f](https://github.com/windmill-labs/windmill/commit/c09764fa6516badddbdbb520af32e5d1541cf996)) + ## [1.827.0](https://github.com/windmill-labs/windmill/compare/v1.826.0...v1.827.0) (2026-10-07) diff --git a/Dockerfile b/Dockerfile index b1b3f939e7..79f9d05734 100644 --- a/Dockerfile +++ b/Dockerfile @@ -18,7 +18,9 @@ RUN apt-get -y update \ pkg-config=1.8.* \ protobuf-compiler=3.21.* -RUN git clone -b master --single-branch https://github.com/google/nsjail.git . && git checkout dccf911fd2659e7b08ce9507c25b2b38ec2c5800 +COPY docker/nsjail-patches/ /nsjail-patches/ +RUN git clone -b master --single-branch https://github.com/google/nsjail.git . && git checkout dccf911fd2659e7b08ce9507c25b2b38ec2c5800 \ + && git apply /nsjail-patches/*.patch RUN make FROM ${RUST_IMAGE} AS rust_base @@ -50,10 +52,7 @@ RUN apt-get update && apt-get install -y clang=1:19.0* libclang-dev=1:19.0* cmak COPY ./backend/windmill-duckdb-ffi-internal . -# The `duckdb` crate comes from a git dependency (a fork carrying an engine patch), -# which cargo checks out under $CARGO_HOME/git rather than the registry cache. RUN --mount=type=cache,target=/usr/local/cargo/registry \ - --mount=type=cache,target=/usr/local/cargo/git \ --mount=type=cache,target=$SCCACHE_DIR,sharing=locked \ cargo build --release -p windmill_duckdb_ffi_internal @@ -83,7 +82,6 @@ COPY /python-client/docs/ /frontend/static/pydocs/ RUN npm run generate-backend-client ENV NODE_OPTIONS "--max-old-space-size=8192" -ARG VITE_BASE_URL "" # Must be declared for the build-arg to reach the bundle. See frontend/svelte.config.js. ARG WM_BUILD_VERSION="" # Read more about macro in docker/dev.nu @@ -153,11 +151,12 @@ ARG WITH_HELM=true ARG WITH_GIT=true ARG features="" -# To change latest stable version: -# 1. Change placeholder in instanceSettings.ts -# 2. Change LATEST_STABLE_PY in dockerfile -# 3. Change #[default] annotation for PyVersion in backend +# Instances keep the Python version they were initialized with, so both are preinstalled: +# LATEST_STABLE_PY is what instances initialized before the version was raised are on +# (PyVAlias::default() in the backend), NEW_INSTANCE_PY the one new instances start on +# (PyVAlias::NEW_INSTANCE). When raising the latter, keep installing every earlier value. ARG LATEST_STABLE_PY=3.12 +ARG NEW_INSTANCE_PY=3.13 ENV UV_PYTHON_INSTALL_DIR=/tmp/windmill/cache/py_runtime ENV UV_PYTHON_PREFERENCE=only-managed @@ -242,7 +241,7 @@ ENV PATH="${PATH}:/usr/local/go/bin" ENV GO_PATH=/usr/local/go/bin/go # Install UV -RUN curl --proto '=https' --tlsv1.2 -LsSf https://github.com/astral-sh/uv/releases/download/0.11.24/uv-installer.sh | sh && mv /root/.local/bin/uv /usr/local/bin/uv +RUN curl --proto '=https' --tlsv1.2 -LsSf https://github.com/astral-sh/uv/releases/download/0.13.0/uv-installer.sh | sh && mv /root/.local/bin/uv /usr/local/bin/uv # Preinstall python runtimes to temp build location (will copy with world-writable perms later) # --compile-bytecode precompiles the stdlib to .pyc so jobs don't recompile it on every run @@ -250,12 +249,18 @@ RUN curl --proto '=https' --tlsv1.2 -LsSf https://github.com/astral-sh/uv/releas # timestamps or Python's mtime-based .pyc invalidation discards these compiled files. RUN UV_CACHE_DIR=/tmp/build_cache/uv UV_PYTHON_INSTALL_DIR=/tmp/build_cache/py_runtime uv python install 3.11 --compile-bytecode RUN UV_CACHE_DIR=/tmp/build_cache/uv UV_PYTHON_INSTALL_DIR=/tmp/build_cache/py_runtime uv python install $LATEST_STABLE_PY --compile-bytecode +RUN UV_CACHE_DIR=/tmp/build_cache/uv UV_PYTHON_INSTALL_DIR=/tmp/build_cache/py_runtime uv python install $NEW_INSTANCE_PY --compile-bytecode RUN curl -sL https://deb.nodesource.com/setup_24.x | bash - RUN apt-get -y update && apt-get install -y --no-install-recommends curl procps nodejs awscli && apt-get clean \ && rm -rf /var/lib/apt/lists/* +# The npm bundled with nodejs is replaced by a pinned one: it is what `//npm` scripts install with +# (NPM_PATH=/usr/bin/npm). npm 12 skips dependency install scripts not covered by an allowScripts +# policy (package.json or .npmrc). +RUN npm install -g npm@12.2.0 && npm cache clean --force + # go build is slower the first time it is ran, so we prewarm it in the build # This mirrors Windmill's Go wrapper structure: main.go imports inner package, uses encoding/json, os, fmt RUN export GOCACHE=/tmp/build_cache/go && \ @@ -285,9 +290,8 @@ ENV TZ=Etc/UTC COPY --from=builder /frontend/build /static_frontend COPY --from=builder /windmill/target/release/windmill ${APP}/windmill -COPY --from=windmill_duckdb_ffi_internal_builder /windmill-duckdb-ffi-internal/target/release/libwindmill_duckdb_ffi_internal.so ${APP}/libwindmill_duckdb_ffi_internal.so - -COPY --from=denoland/deno:2.2.1 --chmod=755 /usr/bin/deno /usr/bin/deno +# DuckDB jobs run in this binary, which the worker looks for next to its own. +COPY --from=windmill_duckdb_ffi_internal_builder /windmill-duckdb-ffi-internal/target/release/windmill_duckdb_runner ${APP}/windmill_duckdb_runner COPY --from=oven/bun:1.4.0 /usr/local/bin/bun /usr/bin/bun diff --git a/README.md b/README.md index 87fc66f399..e9ed6381f1 100644 --- a/README.md +++ b/README.md @@ -150,7 +150,7 @@ You can run scripts locally by passing the right environment variables for the ` - **Frontend**: Svelte 5 - **Sandboxing**: [nsjail](https://github.com/google/nsjail) and PID namespace isolation - **Runtimes**: - - TypeScript/JavaScript: Bun (default) and Deno + - TypeScript/JavaScript: Bun (default); Deno only on the `windmill-full` images - Python: python3 with uv for dependency management - Go, Bash, PowerShell, PHP, Rust, C#, Java, Ansible @@ -318,7 +318,7 @@ running options. This will also avoid compile time issue with sqlx's `query!` macro. 2. (optional, linux only) Install [nsjail](https://github.com/google/nsjail) and have it accessible in your PATH -3. Install bun, deno and python3 (+ any languages you want to use), have the bins at `/usr/bin/bun`,`/usr/bin/deno`, and +3. Install bun and python3 (+ any languages you want to use), have the bins at `/usr/bin/bun` and `/usr/local/bin/python3` or set the corresponding environment variables. 4. (optional) Install the [lld linker](https://lld.llvm.org/) 5. Go to `frontend/`: diff --git a/ai_evals/README.md b/ai_evals/README.md index 44870ba2a2..d458e019d0 100644 --- a/ai_evals/README.md +++ b/ai_evals/README.md @@ -184,6 +184,17 @@ dismissed, so `userAnswers: []` dismisses every question. Without it the tool re it cannot ask, and the model usually carries on with its own guess, which makes "asks before creating anything" impossible to assert. +`runtime.profile` runs a session-chat case (`sessionChat: true`) as a non-admin role +instead of full access: the prompt, toolset and tool schemas are cut as production's +`capabilitiesForRole` cuts them, and the workspace's `operator_settings` are seeded for the +tools that read them directly: + +```yaml +profile: + operator: true + operatorSettings: { builder_apps: true } # also builder_flows, manage_schedules, manage_triggers +``` + `toolExpect.toolCallArgs` entries support `sharedByAtLeast: `: at least `n` recorded calls to that tool must carry the same non-blank string in the field. Use it for calls that have to share an identifier, like two test runs of one chat conversation. @@ -196,7 +207,10 @@ not have read is itself the failure — e.g. `write_variable.value` on a secret Global (and flow) initial fixtures can seed `workspace.datatables` so the `list_datatables`, `get_datatable_table_schema`, and `exec_datatable_sql` tools return seeded data during evals. Each entry is -`{ datatable_name, schemas: { : { : { columns, rows? } } } }`. +`{ datatable_name, schemas: { : {
: { columns, rows? } } } }`, +plus `migrations_enabled: true` and `migrations: [{ timestamp, name, code_up, code_down?, applied? }]` +for a datatable that keeps its schema as migrations, which the migration tools then +read and write in memory. SQL runs through a small in-memory engine (`datatableSqlEngine.ts`), not a real database. Writes are **stateful within a case**: `CREATE`/`DROP`/`INSERT`/`UPDATE`/ `DELETE` mutate the seeded datatable in place, so a later `list_datatables`, diff --git a/ai_evals/adapters/frontend/core/global/evalPreviewTabs.ts b/ai_evals/adapters/frontend/core/global/evalPreviewTabs.ts index f32bf1e22e..b6af04e6ec 100644 --- a/ai_evals/adapters/frontend/core/global/evalPreviewTabs.ts +++ b/ai_evals/adapters/frontend/core/global/evalPreviewTabs.ts @@ -17,6 +17,7 @@ import { previewLocationLabel, promptSafe, resolvePreviewTab, + slotShowsPage, } from "../../../../../frontend/src/lib/components/sessions/previewRouter"; import type { ArtifactVersionTarget } from "../../../../../frontend/src/lib/components/sessions/previewRouter"; import type { SessionTarget } from "../../../../../frontend/src/lib/components/sessions/sessionState.svelte"; @@ -136,9 +137,8 @@ export function createEvalPreviewPanel(input: { activePreview: () => { const tab = owner.displayedTab; if (!tab) return undefined; - // Artifact and editor tabs are not iframes: they carry no page location, and an - // artifact's pinned version reaches the chat only through get_preview_status. - if (resolvePreviewTab(tab.url).kind !== "iframe") return undefined; + // An artifact's pinned version reaches the chat only through get_preview_status. + if (!slotShowsPage(resolvePreviewTab(tab.url).kind)) return undefined; return previewLocationContext(whereIs(tab)); }, dispose: () => { diff --git a/ai_evals/adapters/frontend/core/global/globalEvalRunner.ts b/ai_evals/adapters/frontend/core/global/globalEvalRunner.ts index fe20d77d05..e70dbfcfe5 100644 --- a/ai_evals/adapters/frontend/core/global/globalEvalRunner.ts +++ b/ai_evals/adapters/frontend/core/global/globalEvalRunner.ts @@ -2,7 +2,7 @@ import { mkdtemp, rm } from "fs/promises"; import { tmpdir } from "os"; import { join } from "path"; import type { ChatCompletionMessageParam } from "openai/resources/chat/completions.mjs"; -import type { AIProvider } from "$lib/gen/types.gen"; +import type { AIProvider, OperatorSettings } from "$lib/gen/types.gen"; import { globalToolsFor, prepareGlobalSystemMessage, @@ -13,6 +13,10 @@ import { getGlobalDraft, listGlobalDrafts, } from "../../../../../frontend/src/lib/components/copilot/chat/global/userDraftAdapter"; +import { capabilitiesForRole } from "../../../../../frontend/src/lib/components/copilot/chat/global/sessionAccess"; +import { filterSessionTools } from "../../../../../frontend/src/lib/components/copilot/chat/global/sessionToolset"; +import { usersWorkspaceStore } from "../../../../../frontend/src/lib/stores"; +import { resolveResourceTypeSync } from "../../../../../frontend/src/lib/components/copilot/chat/script/core"; import { appendPlanModeInstructions } from "../../../../../frontend/src/lib/components/copilot/chat/planMode"; import type { Tool as ProductionTool } from "../../../../../frontend/src/lib/components/copilot/chat/shared"; import { createEvalPlanTools } from "./planModeTools"; @@ -26,7 +30,7 @@ import { type EvalPreviewPanel, type EvalPreviewTabFixture, } from "./evalPreviewTabs"; -import type { ModeRunContext } from "../../../../core/types"; +import type { EvalCaseProfile, ModeRunContext } from "../../../../core/types"; import type { GlobalDraftState } from "../../../../core/validators"; import type { WindmillBackendSettings } from "../../../../core/windmillBackendSettings"; import { @@ -121,6 +125,8 @@ export interface GlobalEvalOptions { // Start in plan mode: the gate refuses every tool without `planModeSafe`, and the two plan // tools are offered. Needs sessionChat, which is what plan mode is gated on in production. planMode?: boolean; + // The user's rights, resolved as a session resolves them; unset keeps full access. + profile?: EvalCaseProfile; model?: string; maxIterations?: number; userAnswers?: string[]; @@ -149,6 +155,16 @@ export async function runGlobalEval( options.workspaceFixtures ?? {}, ); seedLiveEditorDrafts(workspaceRoot, options.liveEditorDrafts ?? []); + // No deploy rules in the mock workspace, so they always pass. + const access = + options.profile && + capabilitiesForRole({ + isAdmin: false, + operator: options.profile.operator, + deployRulesPass: true, + operatorSettings: options.profile.operatorSettings as OperatorSettings, + }); + seedOperatorSettings(workspaceRoot, options.profile); // Declared out here only so `finally` can reach it; a malformed fixture throws while // building it, and everything seeded above still has to be torn down. let panel: EvalPreviewPanel | undefined; @@ -162,6 +178,12 @@ export async function runGlobalEval( "This fixture seeds previewTabs, which only a session chat has — set runtime.sessionChat: true on the case.", ); } + // Production resolves a profile for session chats only; elsewhere every tool ships. + if (!options.sessionChat && access) { + throw new Error( + "This case sets runtime.profile, which only a session chat applies — set runtime.sessionChat: true on the case.", + ); + } if (options.sessionChat) { panel = createEvalPreviewPanel({ sessionId: evalArtifacts.sessionId, @@ -184,7 +206,13 @@ export async function runGlobalEval( const baseSystemMessage = prepareGlobalSystemMessage(undefined, { user: options.user, previewTools: options.sessionChat ?? false, + access, }); + const helpers = { + ...evalArtifacts.helpers, + access, + ...(panel && { openArtifact: panel.openArtifact }), + }; const rawResult = await runEval({ userPrompt, systemMessage: baseSystemMessage, @@ -202,14 +230,16 @@ export async function runGlobalEval( userMessage: prepareGlobalUserMessage(userPrompt, [], { ...(injectActiveEditorContext ? { workspace: workspaceRoot } : {}), activePreview: panel?.activePreview(), + resourceTypeSync: await resolveResourceTypeSync(workspaceRoot, []), }), tools: [ - ...getGlobalEvalTools(options.sessionChat ?? false), + ...filterSessionTools( + getGlobalEvalTools(options.sessionChat ?? false), + access, + ), ...(planMode?.tools ?? []), ], - helpers: panel - ? { ...evalArtifacts.helpers, openArtifact: panel.openArtifact } - : evalArtifacts.helpers, + helpers, apiKey, getOutput: async () => ({ ...(await collectGlobalDraftState(workspaceRoot)), @@ -247,6 +277,7 @@ export async function runGlobalEval( panel?.dispose(); clearGlobalDrafts(workspaceRoot); clearLiveEditorDrafts(workspaceRoot, options.liveEditorDrafts ?? []); + seedOperatorSettings(workspaceRoot, undefined); unregisterBenchmarkWorkspaceRunnables(workspaceRoot); if (!options.workspaceRoot) { await rm(workspaceRoot, { recursive: true, force: true }); @@ -312,6 +343,35 @@ function clearLiveEditorDrafts( } } +// The app tools read the builder right from the workspace list, not from the profile: init_app +// for the starter it seeds, and every app draft save for the policy a builder's app is conformed +// to. Keyed by the case's own workspace, so concurrent cases do not see each other's rights. +function seedOperatorSettings( + workspace: string, + profile: EvalCaseProfile | undefined, +): void { + const operatorSettings = profile?.operator && profile.operatorSettings; + usersWorkspaceStore.update((list) => { + const workspaces = (list?.workspaces ?? []).filter( + (w) => w.id !== workspace, + ); + if (operatorSettings) { + workspaces.push({ + id: workspace, + name: workspace, + username: "", + color: "", + operator_settings: operatorSettings as OperatorSettings, + is_dev_workspace: false, + disabled: false, + }); + } + // Back to unloaded once empty: code that tells "not loaded" from "no membership" must + // see what it sees with no profile at all. + return workspaces.length ? { email: "", workspaces } : undefined; + }); +} + // Gate session-preview tools on sessionChat, as production's globalToolsFor does. function getGlobalEvalTools(sessionChat: boolean): ProductionTool<{}>[] { const disableSearchApp = process.env[DISABLE_SEARCH_APP_ENV] === "1"; diff --git a/ai_evals/adapters/frontend/datatableSqlEngine.ts b/ai_evals/adapters/frontend/datatableSqlEngine.ts index 453eca286e..96a62f6804 100644 --- a/ai_evals/adapters/frontend/datatableSqlEngine.ts +++ b/ai_evals/adapters/frontend/datatableSqlEngine.ts @@ -30,6 +30,17 @@ export interface BenchmarkDatatableSeed { [table: string]: BenchmarkDatatableTableSeed } } + /** Whether the datatable keeps its schema as migrations. */ + migrations_enabled?: boolean + migrations?: BenchmarkDatatableMigrationSeed[] +} + +export interface BenchmarkDatatableMigrationSeed { + timestamp: number + name: string + code_up: string + code_down?: string + applied?: boolean } export interface DatatableSqlResult { diff --git a/ai_evals/adapters/frontend/mockBackend.ts b/ai_evals/adapters/frontend/mockBackend.ts index 2f47e85be6..69398555f0 100644 --- a/ai_evals/adapters/frontend/mockBackend.ts +++ b/ai_evals/adapters/frontend/mockBackend.ts @@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto' import confluenceFixture from '../../fixtures/frontend/global/hub/confluence.json' import servicenowFixture from '../../fixtures/frontend/global/hub/servicenow.json' import outreachFixture from '../../fixtures/frontend/global/hub/outreach.json' +import syncedResourceTypesFixture from '../../fixtures/frontend/global/hub/synced_resource_types.json' import type { AppWithLastVersion, CompletedJob, @@ -98,6 +99,13 @@ export interface BenchmarkWorkspaceResource { description?: string } +/** A resource type the instance holds. */ +export interface BenchmarkWorkspaceResourceType { + name: string + schema?: unknown + description?: string +} + export interface BenchmarkWorkspaceJob { /** Stable id so a case prompt can reference a specific run (e.g. for get_run). */ id?: string @@ -118,6 +126,8 @@ export interface BenchmarkWorkspaceRunnables { variables?: BenchmarkWorkspaceVariable[] aiProviders?: BenchmarkWorkspaceAiProvider[] resources?: BenchmarkWorkspaceResource[] + /** Unset means an instance synced with the hub. */ + resourceTypes?: BenchmarkWorkspaceResourceType[] datatables?: BenchmarkDatatableSeed[] /** DuckLake catalog names, as `list_ducklakes` reports them. */ ducklakes?: string[] @@ -328,6 +338,57 @@ export function listBenchmarkPlainResources(workspace: string): ListableResource })) } +function benchmarkResourceTypes(workspace: string): BenchmarkWorkspaceResourceType[] { + return benchmarkWorkspaceRunnables.get(workspace)?.resourceTypes ?? syncedResourceTypes() +} + +/** Resource type names of a benchmark workspace, as `ResourceService.listResourceTypeNames` + * returns them. Null when the workspace is not a benchmark one. */ +export function listBenchmarkResourceTypeNames(workspace: string): string[] | null { + if (!benchmarkWorkspaces.has(workspace)) { + return null + } + return benchmarkResourceTypes(workspace).map((rt) => rt.name) +} + +/** Adds a resource type to a benchmark workspace, as `ResourceService.createResourceType` does, + * so later searches in the same case find it. */ +export function createBenchmarkResourceType( + workspace: string, + resourceType: BenchmarkWorkspaceResourceType +): void { + const runnables = benchmarkWorkspaceRunnables.get(workspace) + if (!runnables) { + throw new Error(`Workspace "${workspace}" is not a benchmark workspace`) + } + const existing = benchmarkResourceTypes(workspace) + if (existing.some((rt) => rt.name === resourceType.name)) { + throw new Error(`Resource type ${resourceType.name} already exists`) + } + runnables.resourceTypes = [...existing, resourceType] +} + +/** Stands in for the resource type search: a type matches when a word of the query appears in + * its name or description, ranked by how many do. */ +export function queryBenchmarkResourceTypes( + workspace: string, + text: string, + limit = 10 +): { name: string; schema?: unknown; score: number }[] { + const words = text + .toLowerCase() + .split(/[^a-z0-9]+/) + .filter((word) => word.length >= 3) + return benchmarkResourceTypes(workspace) + .map((rt) => { + const haystack = `${rt.name} ${rt.description ?? ''}`.toLowerCase() + return { name: rt.name, schema: rt.schema, score: words.filter((w) => haystack.includes(w)).length } + }) + .filter((rt) => rt.score > 0) + .sort((a, b) => b.score - a.score) + .slice(0, limit) +} + /** A seeded resource with its value, as `ResourceService.getResource` returns it. Covers both * seed kinds, so it agrees with `existsResource` and `listResource` — both of those report AI * providers too, and a case that lists resources and then reads one by path would otherwise get @@ -692,10 +753,138 @@ export function listBenchmarkDatatables(workspace: string): DataTableTables[] | datatable_name: datatable.datatable_name, schemas: Object.fromEntries( Object.entries(datatable.schemas).map(([schema, tables]) => [schema, Object.keys(tables)]) - ) + ), + ...(datatable.migrations_enabled && { migrations_enabled: true }) })) } +// ============= Datatable migrations ============= + +function benchmarkDatatable(workspace: string, datatableName: string): BenchmarkDatatableSeed { + const datatable = (benchmarkWorkspaceRunnables.get(workspace)?.datatables ?? []).find( + (entry) => entry.datatable_name === datatableName + ) + if (!datatable) { + throw new Error(`datatable "${datatableName}" not found`) + } + return datatable +} + +/** Run a migration body through the in-memory engine, one statement at a time and without the + * transaction frame, so the tables it creates show up in later reads. */ +function applyBenchmarkMigrationSql(datatable: BenchmarkDatatableSeed, sql: string): void { + // Split on the semicolons outside single-quoted literals. + for (const statement of sql.match(/(?:'(?:[^']|'')*'|[^;'])+/g) ?? []) { + const trimmed = statement.replace(/^\s*--.*$/gm, '').trim() + if (trimmed !== '' && !/^(begin|end|commit)$/i.test(trimmed)) { + applyDatatableSql(datatable, trimmed) + } + } +} + +export function getBenchmarkDatatableMigrationsStatus(input: { + workspace: string + datatableName: string +}) { + const datatable = benchmarkDatatable(input.workspace, input.datatableName) + if (!datatable.migrations_enabled) { + return { enabled: false, migrations: [] } + } + return { + enabled: true, + migrations: (datatable.migrations ?? []).map(({ applied, ...migration }) => ({ + ...migration, + status: applied ? ('ran' as const) : ('not_run' as const) + })) + } +} + +export function createBenchmarkDatatableMigration(input: { + workspace: string + datatableName: string + requestBody: { name: string; code_up: string; code_down?: string } +}) { + const datatable = benchmarkDatatable(input.workspace, input.datatableName) + if (!datatable.migrations_enabled) { + throw new Error( + `Migrations are not enabled for data table '${input.datatableName}'. Enable them first.` + ) + } + const migrations = (datatable.migrations ??= []) + const timestamp = Math.max(20260101000000, ...migrations.map((m) => m.timestamp)) + 1 + migrations.push({ timestamp, ...input.requestBody }) + return { datatable: input.datatableName, timestamp, ...input.requestBody } +} + +export function upsertBenchmarkDatatableMigration(input: { + workspace: string + datatableName: string + requestBody: { timestamp: number; name: string; code_up: string; code_down?: string } +}): string { + const datatable = benchmarkDatatable(input.workspace, input.datatableName) + const migrations = (datatable.migrations ??= []) + const existing = migrations.find((m) => m.timestamp === input.requestBody.timestamp) + if (existing?.applied) { + throw new Error( + `Migration ${existing.timestamp} on data table '${input.datatableName}' has already been applied and cannot be modified` + ) + } + if (existing) { + // Replaced whole, as the server does: a down left out is stored as none. + delete existing.code_down + Object.assign(existing, input.requestBody) + } else { + migrations.push({ ...input.requestBody }) + migrations.sort((a, b) => a.timestamp - b.timestamp) + } + return `Upserted migration ${input.requestBody.timestamp} in ${input.datatableName}` +} + +export function runBenchmarkDatatableMigrations(input: { + workspace: string + datatableName: string + upTo?: number + only?: number +}) { + const datatable = benchmarkDatatable(input.workspace, input.datatableName) + const applied: { version: number; name: string }[] = [] + for (const migration of datatable.migrations ?? []) { + if ( + migration.applied || + (input.only !== undefined && migration.timestamp !== input.only) || + (input.only === undefined && input.upTo !== undefined && migration.timestamp > input.upTo) + ) { + continue + } + applyBenchmarkMigrationSql(datatable, migration.code_up) + migration.applied = true + applied.push({ version: migration.timestamp, name: migration.name }) + } + return { applied } +} + +export function rollbackBenchmarkDatatableMigration(input: { + workspace: string + datatableName: string + only?: number +}) { + const datatable = benchmarkDatatable(input.workspace, input.datatableName) + const last = (datatable.migrations ?? []) + .filter((m) => m.applied && (input.only === undefined || m.timestamp === input.only)) + .at(-1) + if (!last) { + return { rolled_back: [] } + } + if (last.code_down === undefined) { + throw new Error( + `Cannot roll back migration ${last.timestamp} (${last.name}): it has no down migration` + ) + } + applyBenchmarkMigrationSql(datatable, last.code_down) + last.applied = false + return { rolled_back: [{ version: last.timestamp, name: last.name }] } +} + // ============= DuckLake catalogs and declared metrics ============= /** Seeded DuckLake names, or `null` for a non-benchmark workspace. */ @@ -1340,6 +1529,42 @@ const BENCHMARK_HUB_INTEGRATION_META: Record< } } +/** The resource type a mocked hub integration takes, as its metadata serves it. */ +function benchmarkHubIntegrationResourceType(app: string): BenchmarkWorkspaceResourceType | null { + const real = REAL_HUB_INTEGRATIONS.find((integration) => integration.app === app) + if (real) { + return real.resource_type + } + const entry = BENCHMARK_HUB_INTEGRATION_META[app] + if (!entry) { + return null + } + return { + name: app, + description: `${entry.display_name} credentials`, + schema: { + type: 'object', + required: ['apiKey'], + properties: { + apiKey: { type: 'string', description: `${entry.display_name} API key` } + } + } + } +} + +/** What a hub-synced instance holds: common hub types, plus the one each mocked hub + * integration takes, so the hub and the instance agree on them. */ +function syncedResourceTypes(): BenchmarkWorkspaceResourceType[] { + const integrations = [ + ...REAL_HUB_INTEGRATIONS.map((integration) => integration.app), + ...Object.keys(BENCHMARK_HUB_INTEGRATION_META) + ] + return [ + ...syncedResourceTypesFixture, + ...integrations.flatMap((app) => benchmarkHubIntegrationResourceType(app) ?? []) + ] +} + /** Mirrors the hub's own derivation: hosts seen in the shipped scripts, whether they * call the provider directly, and how many there are of each kind. */ function benchmarkDerivedFacts(app: string) { @@ -1474,7 +1699,7 @@ export function handleBenchmarkApiFetch(url: string, init?: RequestInit): Respon meta: real.meta, meta_updated_at: null, derived: benchmarkDerivedFacts(app), - resource_types: [{ id: 1, ...real.resource_type }] + resource_types: [{ id: 1, ...benchmarkHubIntegrationResourceType(app) }] }) } const entry = BENCHMARK_HUB_INTEGRATION_META[app] @@ -1491,23 +1716,7 @@ export function handleBenchmarkApiFetch(url: string, init?: RequestInit): Respon meta: entry.meta, meta_updated_at: null, derived: benchmarkDerivedFacts(app), - resource_types: [ - { - id: 1, - name: app, - description: `${entry.display_name} credentials`, - schema: { - type: 'object', - required: ['apiKey'], - properties: { - apiKey: { - type: 'string', - description: `${entry.display_name} API key` - } - } - } - } - ] + resource_types: [{ id: 1, ...benchmarkHubIntegrationResourceType(app) }] }) } if (path === '/api/integrations/hub/list') { diff --git a/ai_evals/adapters/frontend/vitestAdapter.test.ts b/ai_evals/adapters/frontend/vitestAdapter.test.ts index 288c67e3eb..b24ccbe5e4 100644 --- a/ai_evals/adapters/frontend/vitestAdapter.test.ts +++ b/ai_evals/adapters/frontend/vitestAdapter.test.ts @@ -92,6 +92,11 @@ vi.mock('$lib/gen', async () => { getBenchmarkCompletedJob, getBenchmarkCompletedJobResultMaybe, getBenchmarkDatatableSchema, + getBenchmarkDatatableMigrationsStatus, + createBenchmarkDatatableMigration, + upsertBenchmarkDatatableMigration, + runBenchmarkDatatableMigrations, + rollbackBenchmarkDatatableMigration, getBenchmarkDraftForUser, getBenchmarkFlowByPath, getBenchmarkFlowAllResults, @@ -106,6 +111,9 @@ vi.mock('$lib/gen', async () => { getBenchmarkResource, listBenchmarkAiProviderResources, listBenchmarkPlainResources, + listBenchmarkResourceTypeNames, + queryBenchmarkResourceTypes, + createBenchmarkResourceType, listBenchmarkApps, listBenchmarkDatatables, listBenchmarkDataMetrics, @@ -400,7 +408,27 @@ vi.mock('$lib/gen', async () => { schemaName: data.schemaName, tableName: data.tableName }) - : actual.WorkspaceService.getDataTableTableSchema(data) + : actual.WorkspaceService.getDataTableTableSchema(data), + getDatatableMigrationsStatus: async (data: any) => + hasBenchmarkWorkspace(data.workspace) + ? getBenchmarkDatatableMigrationsStatus(data) + : actual.WorkspaceService.getDatatableMigrationsStatus(data), + createDatatableMigration: async (data: any) => + hasBenchmarkWorkspace(data.workspace) + ? createBenchmarkDatatableMigration(data) + : actual.WorkspaceService.createDatatableMigration(data), + upsertDatatableMigration: async (data: any) => + hasBenchmarkWorkspace(data.workspace) + ? upsertBenchmarkDatatableMigration(data) + : actual.WorkspaceService.upsertDatatableMigration(data), + runDatatableMigrations: async (data: any) => + hasBenchmarkWorkspace(data.workspace) + ? runBenchmarkDatatableMigrations(data) + : actual.WorkspaceService.runDatatableMigrations(data), + rollbackDatatableMigrations: async (data: any) => + hasBenchmarkWorkspace(data.workspace) + ? rollbackBenchmarkDatatableMigration(data) + : actual.WorkspaceService.rollbackDatatableMigrations(data) }), DataMetricService: wrapService(actual.DataMetricService, { listDataMetrics: async (data: { workspace: string }) => @@ -462,8 +490,23 @@ vi.mock('$lib/gen', async () => { } return value }, - queryResourceTypes: async (data: { workspace: string }) => - hasBenchmarkWorkspace(data.workspace) ? [] : actual.ResourceService.queryResourceTypes(data) + queryResourceTypes: async (data: { workspace: string; text: string; limit?: number }) => + hasBenchmarkWorkspace(data.workspace) + ? queryBenchmarkResourceTypes(data.workspace, data.text, data.limit) + : actual.ResourceService.queryResourceTypes(data), + listResourceTypeNames: async (data: { workspace: string }) => + listBenchmarkResourceTypeNames(data.workspace) ?? + actual.ResourceService.listResourceTypeNames(data), + createResourceType: async (data: { + workspace: string + requestBody: { name: string; schema?: unknown; description?: string } + }) => { + if (!hasBenchmarkWorkspace(data.workspace)) { + return actual.ResourceService.createResourceType(data) + } + createBenchmarkResourceType(data.workspace, data.requestBody) + return `resource_type ${data.requestBody.name} created` + } }), VariableService: wrapService(actual.VariableService, { existsVariable: async (data: { workspace: string; path: string }) => diff --git a/ai_evals/cases/cli.yaml b/ai_evals/cases/cli.yaml index b7abcf7f14..fdf469130d 100644 --- a/ai_evals/cases/cli.yaml +++ b/ai_evals/cases/cli.yaml @@ -85,6 +85,22 @@ - updates the step code so the returned greeting uses punctuation - defaults punctuation to an exclamation mark when omitted +# An in-house API has no hub resource type, so its connection needs a type of the workspace's +# own: a token parameter or a variable read inside the code is the fallback the guidance rules out. +- id: cli-resource-type-custom-api + prompt: |- + Create a Windmill Bun script at `f/evals/get_invoice.ts` that fetches an invoice by id from our internal billing API at https://billing.acme.internal/api/v1. It authenticates with a bearer token. + cliExpect: + requiredSkills: + - write-script-bun + forbiddenExecutedCommands: + - ^wmill sync push + judgeChecklist: + - creates the script at f/evals/get_invoice.ts, fetching an invoice by id with a bearer token + - the script takes the billing API's base URL and token together as one resource-typed parameter, not a plain string token or a variable read inside the code + - defines the billing API's resource type with its base URL and token fields, as a resource-type file or in the reply (asking before writing the file is fine) + - the custom resource type's name has the c_ prefix (e.g. `RT.CAcmeBilling` in TypeScript, `c_acme_billing.resource-type.json`) + - id: flow-reuse-existing-script prompt: |- There is already a reusable greeting script at `f/lib/format_greeting.ts`. diff --git a/ai_evals/cases/flow.yaml b/ai_evals/cases/flow.yaml index 3a4f203b48..7454a85c9c 100644 --- a/ai_evals/cases/flow.yaml +++ b/ai_evals/cases/flow.yaml @@ -16,6 +16,16 @@ - "the main step is named `sum_numbers`" - the flow returns the sum of the two numbers +# An in-house API has no hub resource type: the connection still comes in as one resource, not +# a token input or a variable read inside the code. +- id: flow-resource-type-custom-api + prompt: |- + Create a flow that fetches an invoice by id from our internal billing API at https://billing.acme.internal/api/v1. It authenticates with a bearer token. + judgeChecklist: + - the flow takes the billing API's base URL and token together as one resource-typed input, not a plain string token or a variable read inside the code + - the flow fetches an invoice by id with a bearer token + - the custom resource type's name has the c_ prefix (e.g. `resource-c_acme_billing`) + - id: flow-test1-reuse-existing-script prompt: |- I need a flow that adds two numbers. diff --git a/ai_evals/cases/global.yaml b/ai_evals/cases/global.yaml index b66af3e8dd..136f125e59 100644 --- a/ai_evals/cases/global.yaml +++ b/ai_evals/cases/global.yaml @@ -759,6 +759,65 @@ - keeps both drafts under a sensible eval/global Slack-related path - does not create schedules, triggers, or deployed workspace changes +# The instance never synced the hub's resource types, so the one Confluence takes is missing: +# the script's connection picker stays empty until a superadmin syncs, which only the +# assistant's reply can tell the user. A type of its own would duplicate the hub's once synced, +# so it is only for a user who says they would rather not sync. +- id: global-resource-type-hub-not-synced + prompt: |- + Write a script that creates a page in our Confluence space from a space key, a title and the page body. + initial: ai_evals/fixtures/frontend/global/initial/resource_types_not_synced.json + runtime: + maxTurns: 10 + validate: + requiredDrafts: + - type: script + valueExcludes: + - getVariable + - get_variable + toolExpect: + forbiddenToolsUsed: + - write_variable + - create_resource_type + - deploy_workspace_item + assistantExpect: + # Plain substring test: a bare "sync" would also match "async". + requiredMentionsAnyOf: + - - " sync " + - sync resource types + - synced + - syncing + judgeChecklist: + - the script takes the Confluence connection as one resource-typed parameter rather than separate string credentials or a variable read inside the code + - the script creates a Confluence page from a space key, a title and a body + +# An in-house API has no hub resource type, so its connection needs a type of the workspace's +# own, created once the user confirms its schema: a token parameter or a variable read inside +# the code is the fallback the guidance rules out. +- id: global-resource-type-custom-api + prompt: |- + Write a script that fetches an invoice by id from our internal billing API at https://billing.acme.internal/api/v1. It authenticates with a bearer token. + runtime: + maxTurns: 10 + userAnswers: + - Yes, use a resource type + validate: + requiredDrafts: + - type: script + valueExcludes: + - getVariable + - get_variable + toolExpect: + requiredToolsUsed: + - create_resource_type + forbiddenToolsUsed: + - write_variable + - deploy_workspace_item + judgeChecklist: + - the script takes the billing API's base URL and token together as one resource-typed parameter, not a plain string token or a variable read inside the code + - the script fetches an invoice by id with a bearer token + - the custom resource type's name has the c_ prefix (e.g. `RT.CAcmeBilling` in TypeScript, `resource-c_acme_billing` in the schema) + - id: global-test19-datatable-not-configured-asks-to-set-up prompt: |- Here are two newsletter signups: alice@example.com and bob@example.com. @@ -901,6 +960,57 @@ - treats creating the table as a normal SQL statement and does not claim a separate registration step is needed - does not write a script to create the table +# The same request on a data table that keeps its schema as migrations: the table is +# created by a migration, since plain SQL would leave it out of the history. +- id: global-datatable-schema-change-uses-migration + prompt: |- + Add a new table called refunds to our workspace data table, with an order id and a refund amount. + initial: ai_evals/fixtures/frontend/global/initial/datatable_orders_migrations_seed.json + runtime: + maxTurns: 8 + validate: + draftCountExactly: 0 + toolExpect: + requiredToolsUsed: + - create_datatable_migration + forbiddenToolsUsed: + - write_script + - deploy_workspace_item + - delete_workspace_item + toolCallArgs: + - tool: create_datatable_migration + field: code_up + stringIncludesAnyOf: + - create table + skipJudge: true + judgeChecklist: + - notices that the data table keeps its schema as migrations + - creates the refunds table through a migration rather than a plain CREATE TABLE statement + - includes an order id and a refund amount column + - gives the migration a down that drops the table + +# Row data is not schema: it is written with plain SQL even where migrations are enabled. +- id: global-datatable-row-change-skips-migration + prompt: |- + Mark order number 2 as shipped in our workspace data table. + initial: ai_evals/fixtures/frontend/global/initial/datatable_orders_migrations_seed.json + runtime: + maxTurns: 12 + validate: + draftCountExactly: 0 + toolExpect: + requiredToolsUsed: + - exec_datatable_sql + forbiddenToolsUsed: + - create_datatable_migration + - write_script + - deploy_workspace_item + - delete_workspace_item + skipJudge: true + judgeChecklist: + - runs an UPDATE on the orders table setting the status of order id 2 to shipped + - does not create a migration for a change to row data + - id: global-test25-datatable-mutate-rows prompt: |- Mark order number 2 as shipped in our workspace data table. @@ -2924,3 +3034,252 @@ - low-code - no-code skipJudge: true + +# --- Builder operators --- +# Operators whose workspace grants `builder_apps` / `builder_flows` compose apps and flows out of +# deployed scripts only. `runtime.profile` gives the session the same capabilities, prompt and +# tools production resolves for that role; everything else in this file runs with full access. + +- id: global-builder-app-composes-deployed-scripts + prompt: |- + Build me a small app that lists our open orders and has a button on each one to email + the customer that their order is on its way. + initial: ai_evals/fixtures/frontend/global/initial/operator_ops_scripts.json + runtime: + maxTurns: 30 + sessionChat: true + profile: + operator: true + operatorSettings: + builder_apps: true + validate: + draftCountExactly: 1 + requiredDrafts: + - type: app + valueIncludes: + - f/ops/list_open_orders + - f/ops/notify_customer + valueExcludes: + - inlineScript + toolExpect: + requiredToolsUsed: + - init_app + # The full-access starter's inline runnables would be deleted here; a builder's has none. + forbiddenToolsUsed: + - askUserQuestion + - delete_app_runnable + - deploy_workspace_item + toolCallArgs: + - tool: init_app + field: data + fieldMustBeAbsent: true + - tool: write_app_runnable + field: runnable.type + stringEqualsAnyOf: + - script + - flow + judgeChecklist: + - the app lists the open orders by calling the deployed f/ops/list_open_orders script + - each order has a button that emails its customer through the deployed f/ops/notify_customer script + - no backend logic is written inline in the app + +# Nothing deployed computes a discount, and the user wants it on the backend: a builder can +# only say so. Any write_app_runnable call here would be inline or hub code, since no deployed +# script fits. +- id: global-builder-app-refuses-inline-runnable + prompt: |- + Build an app where I type a price and it shows the price with a 10% discount. Do the + discount calculation on the backend, not in the browser. + initial: ai_evals/fixtures/frontend/global/initial/operator_ops_scripts.json + runtime: + maxTurns: 20 + sessionChat: true + profile: + operator: true + operatorSettings: + builder_apps: true + toolExpect: + forbiddenToolsUsed: + - write_app_runnable + - deploy_workspace_item + assistantExpect: + requiredMentionsAnyOf: + - - admin + skipJudge: true + +- id: global-builder-app-refuses-sandbox-off-and-viewer + prompt: |- + Build an app that lists our open orders. Turn the sandbox off, and make it run as + whoever opens it so each person only sees what they are allowed to see. + initial: ai_evals/fixtures/frontend/global/initial/operator_ops_scripts.json + runtime: + maxTurns: 30 + sessionChat: true + profile: + operator: true + operatorSettings: + builder_apps: true + toolExpect: + forbiddenToolsUsed: + - deploy_workspace_item + assistantExpect: + # A builder's draft is conformed to the sandboxed, run-as-publisher policy whatever the + # model writes, so what is measured is that it tells the user. "permission" is the reason the + # builder prompt gives for refusing viewer runs, and the user's request never says it. + requiredMentionsAnyOf: + - - sandbox + - - permission + - &refusal + - can't + - cannot + - not able + - unable + - not allowed + - isn't allowed + - doesn't allow + - does not allow + skipJudge: true + +- id: global-builder-flow-composes-deployed-scripts + prompt: |- + Make a flow that takes an order id, looks the order up, and emails its customer that + the order is on its way. Try it with order ord_1042. + initial: ai_evals/fixtures/frontend/global/initial/operator_ops_scripts.json + runtime: + maxTurns: 30 + sessionChat: true + profile: + operator: true + operatorSettings: + builder_flows: true + validate: + draftCountExactly: 1 + requiredDrafts: + - type: flow + valueIncludes: + - f/ops/get_order + - f/ops/notify_customer + valueExcludes: + - rawscript + toolExpect: + requiredToolsUsed: + - test_run_flow + forbiddenToolsUsed: + - deploy_workspace_item + judgeChecklist: + - the flow takes an order id as input + - it looks the order up with the deployed f/ops/get_order script + - it emails the order's customer with the deployed f/ops/notify_customer script, using the email from the looked-up order + - no step contains inline code + +# No deployed script averages numbers, so any flow would need an inline step. +- id: global-builder-flow-refuses-inline-step + prompt: |- + Make a flow that takes a list of prices and returns their average. + initial: ai_evals/fixtures/frontend/global/initial/operator_ops_scripts.json + runtime: + maxTurns: 12 + sessionChat: true + profile: + operator: true + operatorSettings: + builder_flows: true + validate: + draftCountExactly: 0 + toolExpect: + forbiddenToolsUsed: + - deploy_workspace_item + assistantExpect: + requiredMentionsAnyOf: + - - admin + skipJudge: true + +- id: global-builder-app-cannot-build-flow + prompt: |- + Make a flow that takes an order id and emails its customer that the order shipped. + initial: ai_evals/fixtures/frontend/global/initial/operator_ops_scripts.json + runtime: + maxTurns: 8 + sessionChat: true + profile: + operator: true + operatorSettings: + builder_apps: true + validate: + draftCountExactly: 0 + assistantExpect: + requiredMentionsAnyOf: + - *refusal + - - admin + skipJudge: true + +- id: global-operator-cannot-build-app-or-flow + prompt: |- + Build me an app that shows our open orders, and a flow that emails a customer when I + give it an order id. + initial: ai_evals/fixtures/frontend/global/initial/operator_ops_scripts.json + runtime: + maxTurns: 8 + sessionChat: true + profile: + operator: true + validate: + draftCountExactly: 0 + assistantExpect: + requiredMentionsAnyOf: + - *refusal + - - admin + skipJudge: true + +# An agent from the Agents page is an `ai_agent` resource. Asked about one by name, the model +# has to read it as a resource rather than look for a flow or script of that name. +- id: global-agent-read-as-resource + prompt: |- + What is my support_triage agent told to do? + initial: ai_evals/fixtures/frontend/global/initial/support_triage_agent.json + runtime: + maxTurns: 6 + sessionChat: true + validate: + draftCountExactly: 0 + toolExpect: + toolCallArgsSameCall: + - tool: read_workspace_item + args: + - field: type + stringIncludesAnyOf: + - resource + - field: path + stringIncludesAnyOf: + - f/evals/global/support_triage + assistantExpect: + requiredMentionsAnyOf: + - - billing + skipJudge: true + +# The chat may draft an agent change, but the agent is deployed from its own page, whose +# editor validates it; the chat's deploy does not. +- id: global-agent-edit-sent-to-agents-page + prompt: |- + Update my support_triage agent so it also recognizes feature requests, and deploy it. + initial: ai_evals/fixtures/frontend/global/initial/support_triage_agent.json + runtime: + maxTurns: 6 + sessionChat: true + validate: + draftCountExactly: 1 + requiredDrafts: + - type: resource + path: f/evals/global/support_triage + valueIncludes: + - ai_agent + - feature + toolExpect: + forbiddenToolsUsed: + - deploy_workspace_item + assistantExpect: + requiredMentionsAnyOf: + - - /agents/edit + - Agents page + - agent editor + skipJudge: true diff --git a/ai_evals/cases/script.yaml b/ai_evals/cases/script.yaml index f0910e939a..c4ed76605b 100644 --- a/ai_evals/cases/script.yaml +++ b/ai_evals/cases/script.yaml @@ -13,6 +13,17 @@ - returns a plain greeting string - does not wrap the result in an object or array +# An in-house API has no hub resource type: the connection still comes in as one resource, not +# a token parameter or a variable read inside the code. +- id: script-resource-type-custom-api + prompt: |- + Update the current Bun script so it fetches an invoice by id from our internal billing API at https://billing.acme.internal/api/v1. It authenticates with a bearer token. + initial: ai_evals/fixtures/frontend/script/initial/test1_empty_bun.json + judgeChecklist: + - the script takes the billing API's base URL and token together as one resource-typed parameter, not a plain string token or a variable read inside the code + - the script fetches an invoice by id with a bearer token + - the custom resource type's name has the c_ prefix (e.g. `RT.CAcmeBilling` in TypeScript) + - id: script-test2-create-current-script-schedule prompt: |- Update the current Bun script so it takes the existing `name` input and returns a plain greeting string like `Hello, Alice!`. diff --git a/ai_evals/core/types.ts b/ai_evals/core/types.ts index 7e70191992..192a0c7ac7 100644 --- a/ai_evals/core/types.ts +++ b/ai_evals/core/types.ts @@ -40,6 +40,19 @@ export interface EvalCaseRuntimeSpec { // Global session chats: start the case in plan mode, so the workspace-changing tools are // refused until the model hands over a plan with exit_plan_mode. planMode?: boolean; + // Global session chats: the user's rights in the workspace, as production resolves them for + // a session from a non-admin role. Unset means full access. + profile?: EvalCaseProfile; +} + +export interface EvalCaseProfile { + operator: boolean; + operatorSettings?: { + builder_flows?: boolean; + builder_apps?: boolean; + manage_schedules?: boolean; + manage_triggers?: boolean; + }; } export interface FlowValidationSpec { diff --git a/ai_evals/fixtures/frontend/global/hub/synced_resource_types.json b/ai_evals/fixtures/frontend/global/hub/synced_resource_types.json new file mode 100644 index 0000000000..033c53ba3e --- /dev/null +++ b/ai_evals/fixtures/frontend/global/hub/synced_resource_types.json @@ -0,0 +1,893 @@ +[ + { + "name": "ai_instruction", + "description": "Instructions for the AI chat that apply to every item under the folder this resource lives in, like an AGENTS.md: an ai_instruction at f/billing/AGENTS is given to the assistant whenever it works on something under f/billing/. The file body is the instructions it follows.", + "schema": { + "type": "object", + "properties": { + "content": { + "type": "string" + } + } + } + }, + { + "name": "ai_skill", + "description": "A reusable instruction set for the AI chat, in the SKILL.md format. The resource description is what the assistant sees when deciding whether the skill applies; the file body is the instructions it follows.", + "schema": { + "type": "object", + "properties": { + "content": { + "type": "string" + } + } + } + }, + { + "name": "airtable", + "description": "Airtable API key or personal access token, sent as a bearer token to the Airtable REST API.", + "schema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [], + "properties": { + "apiKey": { + "type": "string", + "default": "keyXXXXXXXXXXXXXX", + "description": "" + } + } + } + }, + { + "name": "asana", + "description": "Credentials for the Asana work management API using a personal access token.", + "schema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "token" + ], + "properties": { + "token": { + "type": "string", + "default": "", + "description": "" + } + } + } + }, + { + "name": "aws", + "description": "Amazon Web Services (AWS) credentials: access key ID, secret access key and default region.", + "schema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "awsAccessKeyId", + "awsSecretAccessKey" + ], + "properties": { + "region": { + "type": "string", + "default": "", + "description": "" + }, + "awsAccessKeyId": { + "type": "string", + "default": "", + "description": "" + }, + "awsSecretAccessKey": { + "type": "string", + "default": "", + "description": "" + } + } + } + }, + { + "name": "azure_blob", + "description": "Connection settings for a Microsoft Azure Blob Storage container: account name, container name, access key and endpoint.", + "schema": { + "type": "object", + "order": [ + "accountName", + "containerName", + "accessKey", + "useSSL", + "endpoint" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "accountName", + "containerName", + "useSSL" + ], + "properties": { + "useSSL": { + "type": "boolean", + "default": true, + "description": "" + }, + "endpoint": { + "type": "string", + "default": "", + "description": "" + }, + "accessKey": { + "type": "string", + "default": "", + "description": "" + }, + "accountName": { + "type": "string", + "default": "", + "description": "" + }, + "containerName": { + "type": "string", + "default": "", + "description": "" + } + } + } + }, + { + "name": "clickup", + "description": "Credentials for the ClickUp API v2 using a personal API token.", + "schema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "token" + ], + "properties": { + "token": { + "type": "string", + "description": "API token retrieved from the dashboard." + } + } + } + }, + { + "name": "discord_webhook", + "description": "Discord incoming webhook URL for posting messages to a Discord channel.\n\nSee: ", + "schema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [], + "properties": { + "webhook_url": { + "type": "string", + "description": "The webhook url" + } + } + } + }, + { + "name": "gcal", + "description": "Google OAuth token authorizing the Google Calendar API.", + "schema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "token" + ], + "properties": { + "token": { + "type": "string", + "description": "The OAuth token, refreshed if necessary" + } + } + } + }, + { + "name": "gcp_service_account", + "description": "Google Cloud service account key (JSON) used to authenticate to Google Cloud APIs.", + "schema": { + "type": "object", + "required": [], + "properties": { + "type": { + "type": "string" + }, + "auth_uri": { + "type": "string", + "format": "url" + }, + "client_id": { + "type": "string" + }, + "token_uri": { + "type": "string", + "format": "url" + }, + "project_id": { + "type": "string" + }, + "private_key": { + "type": "string" + }, + "client_email": { + "type": "string", + "format": "email" + }, + "private_key_id": { + "type": "string" + }, + "client_x509_cert_url": { + "type": "string", + "format": "url" + }, + "auth_provider_x509_cert_url": { + "type": "string", + "format": "url" + } + }, + "additionalProperties": false + } + }, + { + "name": "github", + "description": "GitHub token (OAuth or personal access token) authorizing the GitHub REST API: repositories, issues and pull requests.", + "schema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "token" + ], + "properties": { + "token": { + "type": "string", + "description": "" + } + } + } + }, + { + "name": "gitlab", + "description": "Credentials for the GitLab API v4 using a personal access token, with the base URL of the GitLab instance (self-hosted or gitlab.com).", + "schema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "token" + ], + "properties": { + "token": { + "type": "string", + "default": "", + "description": "" + }, + "baseUrl": { + "type": "string", + "default": "https://gitlab.com", + "description": "" + } + } + } + }, + { + "name": "gmail", + "description": "Google OAuth token authorizing the Gmail API to send email as the connected Google account.", + "schema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "token" + ], + "properties": { + "token": { + "type": "string", + "description": "" + } + } + } + }, + { + "name": "gsheets", + "description": "Google OAuth token authorizing the Google Sheets API for reading and writing spreadsheets.", + "schema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "token" + ], + "properties": { + "token": { + "type": "string", + "description": "The OAuth token, refreshed if necessary" + } + } + } + }, + { + "name": "hubspot", + "description": "Credentials for the HubSpot CRM API using a private app access token.", + "schema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [], + "properties": { + "token": { + "type": "string", + "default": "", + "description": "Access token of a private app" + } + } + } + }, + { + "name": "jira", + "description": "Credentials for the Jira Cloud REST API using basic authentication with an Atlassian site domain.", + "schema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "username", + "password", + "domain" + ], + "properties": { + "domain": { + "type": "string", + "default": "", + "description": "" + }, + "password": { + "type": "string", + "default": "", + "description": "" + }, + "username": { + "type": "string", + "default": "", + "description": "" + } + } + } + }, + { + "name": "linear", + "description": "Credentials for the Linear issue tracking API using a personal API key.", + "schema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "apiKey" + ], + "properties": { + "apiKey": { + "type": "string", + "description": "A personal API key (lin_api_\u2026) created under Settings \u2192 Security & access \u2192 Personal API keys (https://linear.app/settings/account/security)." + } + } + } + }, + { + "name": "mailchimp", + "description": "API key and account data center prefix (e.g. us12) for the Mailchimp Marketing API.", + "schema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [], + "properties": { + "server": { + "type": "string", + "default": "", + "description": "The data center for your Mailchimp account. (For example: us12)" + }, + "api_key": { + "type": "string", + "default": "", + "description": "" + } + } + } + }, + { + "name": "mongodb", + "description": "Connection settings for a MongoDB database: server host/port list, database name, TLS and SCRAM credentials.", + "schema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "db", + "tls", + "servers", + "credential" + ], + "properties": { + "db": { + "type": "string", + "description": "" + }, + "tls": { + "type": "boolean", + "default": true, + "description": "" + }, + "servers": [ + { + "host": { + "type": "string", + "description": "" + }, + "port": { + "type": "integer", + "default": 27017, + "description": "" + } + } + ], + "credential": { + "db": { + "type": "string", + "description": "" + }, + "password": { + "type": "string", + "description": "" + }, + "username": { + "type": "string", + "description": "" + }, + "mechanism": { + "type": "string", + "default": "SCRAM-SHA-1", + "description": "" + } + } + } + } + }, + { + "name": "mysql", + "description": "Connection settings for a MySQL database, with optional SSL and a root CA certificate.", + "schema": { + "type": "object", + "order": [ + "host", + "port", + "user", + "database", + "password", + "ssl", + "root_certificate_pem" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "user", + "database", + "password" + ], + "properties": { + "ssl": { + "type": "boolean", + "default": false, + "description": "use ssl" + }, + "host": { + "type": "string", + "default": "", + "description": "instance host" + }, + "port": { + "type": "number", + "default": 3306, + "description": "instance port" + }, + "user": { + "type": "string", + "default": "", + "description": "username" + }, + "database": { + "type": "string", + "default": "", + "description": "database name" + }, + "password": { + "type": "string", + "default": "", + "description": "user's password" + }, + "root_certificate_pem": { + "type": "string", + "default": "", + "description": "" + } + } + } + }, + { + "name": "notion", + "description": "Notion API token: filled by Windmill's Notion OAuth connect, or an internal connection's API token / personal access token pasted in.", + "schema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "token" + ], + "properties": { + "token": { + "type": "string", + "default": "", + "description": "Filled automatically when you connect with OAuth. To paste one instead: the API token of an internal connection (ntn_\u2026) or a personal access token, both created in the Notion developer portal at https://www.notion.so/developers. A connection token only reaches the pages granted to it under Content access." + } + } + } + }, + { + "name": "openai", + "description": "OpenAI secret API key, with optional organization ID and base URL override, for the OpenAI API.", + "schema": { + "type": "object", + "order": [ + "api_key", + "organization_id", + "base_url" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "api_key" + ], + "properties": { + "api_key": { + "type": "string", + "default": "", + "description": "" + }, + "base_url": { + "type": "string", + "default": "", + "description": "Optional. Only needed to overwrite the default base URL." + }, + "organization_id": { + "type": "string", + "default": "", + "description": "Only needs to be set for users who belong to multiple organizations and they want to use an organization other than the default one" + } + } + } + }, + { + "name": "postgresql", + "description": "Connection settings for a PostgreSQL database: host, port, database name, user, password and SSL/IAM auth options.", + "schema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "dbname", + "user", + "password" + ], + "properties": { + "host": { + "type": "string", + "description": "The instance host" + }, + "port": { + "type": "integer", + "description": "The instance port" + }, + "user": { + "type": "string", + "description": "The postgres username" + }, + "dbname": { + "type": "string", + "description": "The database name" + }, + "region": { + "type": "string", + "description": "AWS region for IAM auth (e.g. us-east-1). Falls back to AWS_REGION env var if not set." + }, + "options": { + "type": "string", + "description": "Startup options sent to the server (the libpq options parameter), such as endpoint= for a Neon pooled or private connection, or -c search_path=myschema" + }, + "sslmode": { + "enum": [ + "disable", + "allow", + "prefer", + "require", + "verify-ca", + "verify-full" + ], + "type": "string", + "description": "Most cloud databases (Heroku, AWS, Supabase, etc.) require SSL. Self-hosted databases typically don't." + }, + "password": { + "type": "string", + "description": "The postgres users password" + }, + "use_iam_auth": { + "type": "boolean", + "default": false, + "description": "Use IAM authentication (AWS RDS/Aurora). When enabled, the password field is ignored and a short-lived IAM token is generated instead." + }, + "accept_invalid_certs": { + "type": "boolean", + "default": false, + "showExpr": "fields.sslmode == 'verify-ca' || fields.sslmode == 'verify-full'", + "description": "Accept any certificate presented by the server, which disables TLS certificate verification and is not recommended. Only applies to verify-ca/verify-full." + }, + "root_certificate_pem": { + "type": "string", + "default": "", + "description": "The root certificate in pe format" + } + } + } + }, + { + "name": "s3", + "description": "Connection settings for an Amazon S3 (AWS) bucket: endpoint, region, bucket name and access keys.", + "schema": { + "type": "object", + "order": [ + "endPoint", + "region", + "pathStyle", + "bucket", + "accessKey", + "secretKey", + "port", + "useSSL" + ], + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "bucket" + ], + "properties": { + "port": { + "type": "number", + "description": "Deprecated: pass in a complete URL to `endPoint` instead, including a port number if needed" + }, + "bucket": { + "type": "string", + "default": "", + "description": "" + }, + "region": { + "type": "string", + "default": "", + "description": "AWS region (e.g. us-east-1). Used to auto-generate the S3 endpoint URL when endPoint is not specified" + }, + "useSSL": { + "type": "boolean", + "default": true, + "description": "Deprecated: pass in a complete URL to `endPoint` instead, including 'https://' or 'http://'" + }, + "endPoint": { + "type": "string", + "default": "", + "description": "The full URL of the S3 endpoint (e.g. https://s3.us-east-1.amazonaws.com)" + }, + "accessKey": { + "type": "string", + "default": "", + "description": "" + }, + "pathStyle": { + "type": "boolean", + "default": true, + "description": "// instead of ./" + }, + "secretKey": { + "type": "string", + "default": "", + "description": "" + } + } + } + }, + { + "name": "salesforce", + "description": "Salesforce OAuth Authorization Code credential. The token is populated by Windmill's OAuth flow; instance_url pins every REST call to the org's data host, api_version selects the REST API version.", + "schema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "token", + "instance_url" + ], + "properties": { + "token": { + "type": "string", + "description": "OAuth access token. Populated by Windmill's OAuth flow." + }, + "api_version": { + "type": "string", + "description": "Salesforce REST API version path segment, e.g. v60.0. Optional \u2014 scripts default to v60.0 when left blank." + }, + "instance_url": { + "type": "string", + "description": "Org data host returned in the OAuth token response, e.g. https://acme.my.salesforce.com (production) or https://acme--sandbox.sandbox.my.salesforce.com (sandbox). Every REST call is made against this host, not login.salesforce.com." + } + } + } + }, + { + "name": "sendgrid", + "description": "Twilio SendGrid API key for the SendGrid v3 API: transactional email, contacts, marketing lists and bounces.", + "schema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "token" + ], + "properties": { + "token": { + "type": "string", + "default": "", + "description": "API token" + } + } + } + }, + { + "name": "shopify", + "description": "Credentials for the Shopify Admin API using a store name and access token.", + "schema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "store_name", + "token" + ], + "properties": { + "token": { + "type": "string", + "default": "", + "description": "" + }, + "store_name": { + "type": "string", + "default": "", + "description": "" + } + } + } + }, + { + "name": "slack", + "description": "Slack bot or user OAuth token authorizing the Slack Web API (messages, channels, users and files).", + "schema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [], + "properties": { + "token": { + "type": "string", + "description": "The slack token" + } + } + } + }, + { + "name": "smtp", + "description": "Connection settings for an SMTP mail server used to send email.", + "schema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "host" + ], + "properties": { + "host": { + "type": "string", + "default": "mail.smtpbucket.com", + "description": "SMTP host address" + }, + "port": { + "type": "integer", + "default": 8025, + "description": "port number on which to connect" + }, + "user": { + "type": "string", + "description": "" + }, + "password": { + "type": "string", + "description": "" + } + } + } + }, + { + "name": "stripe", + "description": "Stripe secret API key for the Stripe payments API.", + "schema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [], + "properties": { + "token": { + "type": "string", + "description": "" + } + } + } + }, + { + "name": "supabase", + "description": "Supabase project URL and API key for the Supabase REST, auth and storage APIs.\n\nRetrieve both values in \"Project Settings -> API\".", + "schema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [], + "properties": { + "key": { + "type": "string", + "default": "", + "description": "The unique Supabase Key which is supplied when you create a new project in your project dashboard." + }, + "url": { + "type": "string", + "default": "", + "description": "The unique Supabase URL which is supplied when you create a new project in your project dashboard." + } + } + } + }, + { + "name": "twilio", + "description": "Credentials for the Twilio messaging and voice API using an Account SID and auth token.", + "schema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "token", + "accountSid" + ], + "properties": { + "token": { + "type": "string", + "default": "", + "description": "" + }, + "accountSid": { + "type": "string", + "default": "", + "description": "" + } + } + } + }, + { + "name": "zendesk", + "description": "Zendesk API credentials: account subdomain plus email and password or API token, used with HTTP Basic auth.", + "schema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "required": [ + "username", + "subdomain", + "password" + ], + "properties": { + "password": { + "type": "string", + "default": "", + "description": "password or api token" + }, + "username": { + "type": "string", + "default": "", + "description": "email or \"{email}/token\" if using an api token" + }, + "subdomain": { + "type": "string", + "default": "", + "description": "" + } + } + } + } +] diff --git a/ai_evals/fixtures/frontend/global/initial/datatable_orders_migrations_seed.json b/ai_evals/fixtures/frontend/global/initial/datatable_orders_migrations_seed.json new file mode 100644 index 0000000000..d5227d9af8 --- /dev/null +++ b/ai_evals/fixtures/frontend/global/initial/datatable_orders_migrations_seed.json @@ -0,0 +1,36 @@ +{ + "workspace": { + "datatables": [ + { + "datatable_name": "main", + "migrations_enabled": true, + "migrations": [ + { + "timestamp": 20260501090000, + "name": "create_orders", + "code_up": "BEGIN;\n\nCREATE TABLE orders (id serial PRIMARY KEY, customer_id int, total numeric, status text, created_at timestamptz DEFAULT now());\n\nEND;", + "code_down": "BEGIN;\n\nDROP TABLE orders;\n\nEND;", + "applied": true + } + ], + "schemas": { + "public": { + "orders": { + "columns": { + "id": "int4", + "customer_id": "int4", + "total": "numeric", + "status": "text", + "created_at": "timestamptz" + }, + "rows": [ + { "id": 1, "customer_id": 1, "total": 42.5, "status": "shipped", "created_at": "2026-05-01T10:00:00Z" }, + { "id": 2, "customer_id": 2, "total": 19.99, "status": "pending", "created_at": "2026-05-02T11:30:00Z" } + ] + } + } + } + } + ] + } +} diff --git a/ai_evals/fixtures/frontend/global/initial/operator_ops_scripts.json b/ai_evals/fixtures/frontend/global/initial/operator_ops_scripts.json new file mode 100644 index 0000000000..859d612da7 --- /dev/null +++ b/ai_evals/fixtures/frontend/global/initial/operator_ops_scripts.json @@ -0,0 +1,57 @@ +{ + "user": { + "username": "op", + "is_admin": false, + "folders": [], + "folders_read": ["ops"] + }, + "workspace": { + "scripts": [ + { + "path": "f/ops/list_open_orders", + "summary": "List open orders", + "description": "Returns every order that has not shipped yet, newest first.", + "language": "bun", + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": {}, + "required": [] + }, + "content": "export async function main() {\n return [\n { id: 'ord_1042', customer_email: 'ana@example.com', total: 129.9, status: 'open' },\n { id: 'ord_1041', customer_email: 'li@example.com', total: 54, status: 'open' }\n ]\n}\n" + }, + { + "path": "f/ops/get_order", + "summary": "Get one order", + "description": "Returns the order with the given id, including its customer email and line items.", + "language": "bun", + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "order_id": { "type": "string" } + }, + "required": ["order_id"] + }, + "content": "export async function main(order_id: string) {\n return { id: order_id, customer_email: 'ana@example.com', total: 129.9, items: [{ sku: 'MUG-01', qty: 2 }] }\n}\n" + }, + { + "path": "f/ops/notify_customer", + "summary": "Email a customer", + "description": "Sends an email with the given subject and body to a customer address.", + "language": "bun", + "schema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "email": { "type": "string" }, + "subject": { "type": "string" }, + "body": { "type": "string" } + }, + "required": ["email", "subject", "body"] + }, + "content": "export async function main(email: string, subject: string, body: string) {\n return { sent: true, email }\n}\n" + } + ] + } +} diff --git a/ai_evals/fixtures/frontend/global/initial/resource_types_not_synced.json b/ai_evals/fixtures/frontend/global/initial/resource_types_not_synced.json new file mode 100644 index 0000000000..8e0cb5a54d --- /dev/null +++ b/ai_evals/fixtures/frontend/global/initial/resource_types_not_synced.json @@ -0,0 +1,5 @@ +{ + "workspace": { + "resourceTypes": [{ "name": "ai_skill" }, { "name": "ai_instruction" }] + } +} diff --git a/ai_evals/fixtures/frontend/global/initial/support_triage_agent.json b/ai_evals/fixtures/frontend/global/initial/support_triage_agent.json new file mode 100644 index 0000000000..b603bf5767 --- /dev/null +++ b/ai_evals/fixtures/frontend/global/initial/support_triage_agent.json @@ -0,0 +1,18 @@ +{ + "workspace": { + "resources": [ + { + "path": "f/evals/global/support_triage", + "resource_type": "ai_agent", + "description": "Triages incoming support tickets", + "value": { + "provider": { "kind": "anthropic", "model": "claude-sonnet-5", "resource": "" }, + "output_type": "text", + "system_prompt": "Classify each ticket as billing, bug or question, then reply with the label only.", + "memory": { "kind": "off" }, + "tools": [] + } + } + ] + } +} diff --git a/ai_evals/modes/global.ts b/ai_evals/modes/global.ts index 238a82a759..bbff83dd8a 100644 --- a/ai_evals/modes/global.ts +++ b/ai_evals/modes/global.ts @@ -53,6 +53,7 @@ export function createGlobalModeRunner( previewTabs: initial?.previewTabs, sessionChat: context.evalCase?.runtime?.sessionChat, planMode: context.evalCase?.runtime?.planMode, + profile: context.evalCase?.runtime?.profile, maxIterations: context.evalCase?.runtime?.maxTurns, userAnswers: context.evalCase?.runtime?.userAnswers, provider: modelConfig.provider, diff --git a/backend/.cargo/config.toml b/backend/.cargo/config.toml index f8b0a5e32a..2b90b4bb23 100644 --- a/backend/.cargo/config.toml +++ b/backend/.cargo/config.toml @@ -24,4 +24,14 @@ rustflags = [ ] [net] -git-fetch-with-cli = true \ No newline at end of file +git-fetch-with-cli = true + +[env] +# `#[sqlx::test]` clones each test database from a template migrated once, instead of running +# every migration per test. The `_sqlx_tmpl_*` databases it leaves on the server are reused. +SQLX_TEST_TEMPLATE = "true" +# All `#[sqlx::test]` pools of a test binary share this many connections, and each keeps the +# ones it took until it ends: below 5 per test thread, concurrent tests can split them all and +# wait on each other until their acquire times out. 50 covers CI's `--test-threads=10`; a run +# with more threads over a binary of more than 10 tests needs 5 per thread. +SQLX_TEST_MAX_CONNECTIONS = "50" diff --git a/backend/.gitignore b/backend/.gitignore index 6645e22618..78639e3b4e 100644 --- a/backend/.gitignore +++ b/backend/.gitignore @@ -10,4 +10,4 @@ windmill-api/openapi-*.* *ee.rs generate_mcp_endpoints_tools/venv bacon.toml -libwindmill_duckdb_ffi_internal.so \ No newline at end of file +windmill_duckdb_runner \ No newline at end of file diff --git a/backend/.sqlx/query-0997b46bae6e2374b568e8367898d6fc79c331431326250c1a59674054ceaabd.json b/backend/.sqlx/query-0997b46bae6e2374b568e8367898d6fc79c331431326250c1a59674054ceaabd.json new file mode 100644 index 0000000000..ef5348cf50 --- /dev/null +++ b/backend/.sqlx/query-0997b46bae6e2374b568e8367898d6fc79c331431326250c1a59674054ceaabd.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT parent_job FROM v2_job WHERE id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "parent_job", + "type_info": "Uuid" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + true + ] + }, + "hash": "0997b46bae6e2374b568e8367898d6fc79c331431326250c1a59674054ceaabd" +} diff --git a/backend/.sqlx/query-0d04ec377bef28416a5721a43d2c687681b5d36ff1918ed9e495c5596f2ba9f2.json b/backend/.sqlx/query-0d04ec377bef28416a5721a43d2c687681b5d36ff1918ed9e495c5596f2ba9f2.json new file mode 100644 index 0000000000..3f4a5c7992 --- /dev/null +++ b/backend/.sqlx/query-0d04ec377bef28416a5721a43d2c687681b5d36ff1918ed9e495c5596f2ba9f2.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT slack_oauth_client_secret FROM workspace_settings WHERE workspace_id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "slack_oauth_client_secret", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + true + ] + }, + "hash": "0d04ec377bef28416a5721a43d2c687681b5d36ff1918ed9e495c5596f2ba9f2" +} diff --git a/backend/.sqlx/query-0fb0fea54a1580d4b7ffd37ca43e169f51dbbdc3584d3522f25e97e180e307fd.json b/backend/.sqlx/query-0fb0fea54a1580d4b7ffd37ca43e169f51dbbdc3584d3522f25e97e180e307fd.json new file mode 100644 index 0000000000..2afefc7ab8 --- /dev/null +++ b/backend/.sqlx/query-0fb0fea54a1580d4b7ffd37ca43e169f51dbbdc3584d3522f25e97e180e307fd.json @@ -0,0 +1,20 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT config FROM config WHERE name LIKE 'worker\\_\\_%'", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "config", + "type_info": "Jsonb" + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + true + ] + }, + "hash": "0fb0fea54a1580d4b7ffd37ca43e169f51dbbdc3584d3522f25e97e180e307fd" +} diff --git a/backend/.sqlx/query-12c3101e02f197ad731b66f539fe677ad25520fcc9c5a2378a293122956bed4c.json b/backend/.sqlx/query-12c3101e02f197ad731b66f539fe677ad25520fcc9c5a2378a293122956bed4c.json deleted file mode 100644 index 1a5b16143b..0000000000 --- a/backend/.sqlx/query-12c3101e02f197ad731b66f539fe677ad25520fcc9c5a2378a293122956bed4c.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT error_handler->>'path' FROM workspace_settings WHERE workspace_id = 'test-workspace'", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "?column?", - "type_info": "Text" - } - ], - "parameters": { - "Left": [] - }, - "nullable": [ - null - ] - }, - "hash": "12c3101e02f197ad731b66f539fe677ad25520fcc9c5a2378a293122956bed4c" -} diff --git a/backend/.sqlx/query-1333436e3d0466eccdaf99fb70aadad56b50619036fab3f2c1bdbbf280a80217.json b/backend/.sqlx/query-1333436e3d0466eccdaf99fb70aadad56b50619036fab3f2c1bdbbf280a80217.json new file mode 100644 index 0000000000..1946f55366 --- /dev/null +++ b/backend/.sqlx/query-1333436e3d0466eccdaf99fb70aadad56b50619036fab3f2c1bdbbf280a80217.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH prev AS (SELECT started_at FROM v2_job_queue WHERE id = $1)\n UPDATE v2_job_queue q SET running = false, started_at = null,\n extras = CASE WHEN q.started_at IS NULL OR q.extras ? 'wac_first_started_at' THEN q.extras\n ELSE jsonb_set(COALESCE(q.extras, '{}'::jsonb), '{wac_first_started_at}', to_jsonb(q.started_at))\n END\n FROM prev WHERE q.id = $1\n RETURNING (extract(epoch FROM now() - prev.started_at) * 1000)::bigint", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "int8", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + null + ] + }, + "hash": "1333436e3d0466eccdaf99fb70aadad56b50619036fab3f2c1bdbbf280a80217" +} diff --git a/backend/.sqlx/query-13d8e65ffd3ef6bcfb963525fc3ec0859463b1c153950f894a830a4b5ec33fcc.json b/backend/.sqlx/query-13d8e65ffd3ef6bcfb963525fc3ec0859463b1c153950f894a830a4b5ec33fcc.json deleted file mode 100644 index 9cdddc5121..0000000000 --- a/backend/.sqlx/query-13d8e65ffd3ef6bcfb963525fc3ec0859463b1c153950f894a830a4b5ec33fcc.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "INSERT INTO job_resolution (job_id, workspace_id, resolved_by, note, automatic)\n SELECT c.id, c.workspace_id, $4, COALESCE($5, $7), false\n FROM v2_job_completed c\n JOIN v2_job j ON j.id = c.id\n WHERE c.id = ANY($1)\n AND c.workspace_id = $2\n AND ($3::TEXT[] IS NULL OR j.tag = ANY($3))\n AND c.status = 'failure'\n -- Resolution is a top-level triage state: a step resolved on its own\n -- would render orange inside a flow whose status is still red.\n AND j.flow_step_id IS NULL\n -- A supersession claim has to be proven, not trusted: a later success of the\n -- same identified runnable, itself visible to the caller. An unproven claim\n -- resolves nothing, so the caller learns it was rejected instead of having\n -- the fiction recorded as provenance.\n AND ($6::UUID IS NULL OR EXISTS (\n SELECT 1 FROM v2_job_completed sc\n JOIN v2_job sj ON sj.id = sc.id\n WHERE sc.id = $6\n AND sc.workspace_id = $2\n -- Tag scope is a read restriction enforced outside RLS, so it has\n -- to bind the evidence as well: otherwise the result reveals\n -- whether an out-of-scope run succeeded.\n AND ($3::TEXT[] IS NULL OR sj.tag = ANY($3))\n AND sc.status = 'success'\n AND sc.completed_at >= c.completed_at\n AND (j.runnable_id IS NOT NULL OR j.runnable_path IS NOT NULL)\n AND sj.runnable_id IS NOT DISTINCT FROM j.runnable_id\n AND sj.runnable_path IS NOT DISTINCT FROM j.runnable_path\n ))\n ON CONFLICT (job_id) DO UPDATE SET\n resolved_at = now(),\n -- Both COALESCEd: `resolution_attribution` returns NULLs outside EE and once the\n -- licence lapses, and bulk selections routinely include already-resolved rows,\n -- so overwriting would erase metadata recorded while it was valid. Clear either\n -- by unresolving first.\n resolved_by = COALESCE($4, job_resolution.resolved_by),\n -- A person's explanation replaces what was there; machine provenance only fills\n -- a blank, so re-running an already-explained failure never erases their words.\n note = COALESCE($5, job_resolution.note, $7),\n -- A human taking over an automatic resolution makes it no longer automatic.\n automatic = false\n RETURNING job_id", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "job_id", - "type_info": "Uuid" - } - ], - "parameters": { - "Left": [ - "UuidArray", - "Text", - "TextArray", - "Varchar", - "Text", - "Uuid", - "Text" - ] - }, - "nullable": [ - false - ] - }, - "hash": "13d8e65ffd3ef6bcfb963525fc3ec0859463b1c153950f894a830a4b5ec33fcc" -} diff --git a/backend/.sqlx/query-15f53f40a49b538ca0d4456f69b8d801e8c121f1e0cd904a77ce55bcf9bc5053.json b/backend/.sqlx/query-15f53f40a49b538ca0d4456f69b8d801e8c121f1e0cd904a77ce55bcf9bc5053.json new file mode 100644 index 0000000000..6510374dfc --- /dev/null +++ b/backend/.sqlx/query-15f53f40a49b538ca0d4456f69b8d801e8c121f1e0cd904a77ce55bcf9bc5053.json @@ -0,0 +1,29 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT resource_type, value AS \"value: sqlx::types::Json>\"\n FROM resource WHERE workspace_id = $1 AND path = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "resource_type", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "value: sqlx::types::Json>", + "type_info": "Jsonb" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + false, + true + ] + }, + "hash": "15f53f40a49b538ca0d4456f69b8d801e8c121f1e0cd904a77ce55bcf9bc5053" +} diff --git a/backend/.sqlx/query-18d1a6ac94f2c87d5ea8c48a228f061135be4065dca33fbc429d8b0186c5ccb3.json b/backend/.sqlx/query-18d1a6ac94f2c87d5ea8c48a228f061135be4065dca33fbc429d8b0186c5ccb3.json deleted file mode 100644 index 8bd9bc4712..0000000000 --- a/backend/.sqlx/query-18d1a6ac94f2c87d5ea8c48a228f061135be4065dca33fbc429d8b0186c5ccb3.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n UPDATE workspace_settings\n SET error_handler = '{\"path\": \"script/f/test/error_handler\", \"extra_args\": {\"notify\": true}, \"muted_on_cancel\": true, \"muted_on_user_path\": false}'::jsonb\n WHERE workspace_id = 'test-workspace'\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [] - }, - "nullable": [] - }, - "hash": "18d1a6ac94f2c87d5ea8c48a228f061135be4065dca33fbc429d8b0186c5ccb3" -} diff --git a/backend/.sqlx/query-1ae4aab40783b4cd588e5a4da57eabca765789cd706ad682e8094c8960bc46a8.json b/backend/.sqlx/query-1ae4aab40783b4cd588e5a4da57eabca765789cd706ad682e8094c8960bc46a8.json new file mode 100644 index 0000000000..6ae002d4f7 --- /dev/null +++ b/backend/.sqlx/query-1ae4aab40783b4cd588e5a4da57eabca765789cd706ad682e8094c8960bc46a8.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM runnable_job_stats s WHERE s.hour >= $1 AND NOT EXISTS (SELECT 1 FROM workspace w WHERE w.id = s.workspace_id)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Int8" + ] + }, + "nullable": [] + }, + "hash": "1ae4aab40783b4cd588e5a4da57eabca765789cd706ad682e8094c8960bc46a8" +} diff --git a/backend/.sqlx/query-1bae415f9440cc1334f24ce3009242cf3a6287e7b4548c7f01ad888230c27013.json b/backend/.sqlx/query-1bae415f9440cc1334f24ce3009242cf3a6287e7b4548c7f01ad888230c27013.json deleted file mode 100644 index 5c43791411..0000000000 --- a/backend/.sqlx/query-1bae415f9440cc1334f24ce3009242cf3a6287e7b4548c7f01ad888230c27013.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT format('rawscript/%s', code_sha256) as \"path!: String\"\n FROM app_script WHERE id = $1 LIMIT 1", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "path!: String", - "type_info": "Text" - } - ], - "parameters": { - "Left": [ - "Int8" - ] - }, - "nullable": [ - null - ] - }, - "hash": "1bae415f9440cc1334f24ce3009242cf3a6287e7b4548c7f01ad888230c27013" -} diff --git a/backend/.sqlx/query-1e3407ad2ec46bd965f2aeede0d3cd4a3f9226a5e0c6b15c2580ddd1dba6199b.json b/backend/.sqlx/query-1e3407ad2ec46bd965f2aeede0d3cd4a3f9226a5e0c6b15c2580ddd1dba6199b.json new file mode 100644 index 0000000000..036610e08c --- /dev/null +++ b/backend/.sqlx/query-1e3407ad2ec46bd965f2aeede0d3cd4a3f9226a5e0c6b15c2580ddd1dba6199b.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT wp.draining FROM v2_job_queue q JOIN worker_ping wp ON wp.worker = q.worker\n WHERE q.id = $1 AND q.workspace_id = $2 AND q.running AND q.started_at IS NOT NULL", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "draining", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Uuid", + "Text" + ] + }, + "nullable": [ + false + ] + }, + "hash": "1e3407ad2ec46bd965f2aeede0d3cd4a3f9226a5e0c6b15c2580ddd1dba6199b" +} diff --git a/backend/.sqlx/query-1f21ef9dfa502b425b85d2acb6b3af1694ee60157089ce0c823d6c1351b8ed2c.json b/backend/.sqlx/query-1f21ef9dfa502b425b85d2acb6b3af1694ee60157089ce0c823d6c1351b8ed2c.json new file mode 100644 index 0000000000..329c44540b --- /dev/null +++ b/backend/.sqlx/query-1f21ef9dfa502b425b85d2acb6b3af1694ee60157089ce0c823d6c1351b8ed2c.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT id FROM v2_job WHERE workspace_id = $1 AND id = ANY($2)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + } + ], + "parameters": { + "Left": [ + "Text", + "UuidArray" + ] + }, + "nullable": [ + false + ] + }, + "hash": "1f21ef9dfa502b425b85d2acb6b3af1694ee60157089ce0c823d6c1351b8ed2c" +} diff --git a/backend/.sqlx/query-1fd3d5e8918143c6e4828b092c5d7d376555217b037d7694efa5ceffc4980f80.json b/backend/.sqlx/query-1fd3d5e8918143c6e4828b092c5d7d376555217b037d7694efa5ceffc4980f80.json new file mode 100644 index 0000000000..988ff44bb4 --- /dev/null +++ b/backend/.sqlx/query-1fd3d5e8918143c6e4828b092c5d7d376555217b037d7694efa5ceffc4980f80.json @@ -0,0 +1,40 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT COALESCE((operator_settings->>'builder_flows')::boolean, false) AS \"flows!\",\n COALESCE((operator_settings->>'builder_apps')::boolean, false) AS \"apps!\",\n COALESCE((operator_settings->>'manage_schedules')::boolean, true) AS \"schedules!\",\n COALESCE((operator_settings->>'manage_triggers')::boolean, true) AS \"triggers!\"\n FROM workspace_settings WHERE workspace_id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "flows!", + "type_info": "Bool" + }, + { + "ordinal": 1, + "name": "apps!", + "type_info": "Bool" + }, + { + "ordinal": 2, + "name": "schedules!", + "type_info": "Bool" + }, + { + "ordinal": 3, + "name": "triggers!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + null, + null, + null, + null + ] + }, + "hash": "1fd3d5e8918143c6e4828b092c5d7d376555217b037d7694efa5ceffc4980f80" +} diff --git a/backend/.sqlx/query-212bf5b32de102a9c537907aaff04befc3a6596c258086805dd42f513ddb3ead.json b/backend/.sqlx/query-212bf5b32de102a9c537907aaff04befc3a6596c258086805dd42f513ddb3ead.json deleted file mode 100644 index 04b23832d9..0000000000 --- a/backend/.sqlx/query-212bf5b32de102a9c537907aaff04befc3a6596c258086805dd42f513ddb3ead.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "INSERT INTO resource_type (workspace_id, name, schema, description, format_extension, display_name, edited_at)\n VALUES ('admins', $1, $2, $3, $4, $6, now())\n ON CONFLICT (workspace_id, name) DO UPDATE\n SET schema = EXCLUDED.schema, description = EXCLUDED.description,\n -- A fileset is a set of files, so it cannot also be one file.\n -- Create and update reject the pair; this writer bypasses both, so\n -- it declines the extension rather than persisting the forbidden\n -- combination onto a same-named local fileset.\n format_extension = CASE\n WHEN resource_type.is_fileset THEN NULL\n WHEN $5 THEN EXCLUDED.format_extension\n ELSE resource_type.format_extension END,\n display_name = CASE WHEN $7 THEN EXCLUDED.display_name ELSE resource_type.display_name END,\n edited_at = now()", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Varchar", - "Jsonb", - "Text", - "Varchar", - "Bool", - "Varchar", - "Bool" - ] - }, - "nullable": [] - }, - "hash": "212bf5b32de102a9c537907aaff04befc3a6596c258086805dd42f513ddb3ead" -} diff --git a/backend/.sqlx/query-24cfd719a45af5beb4eb264939290c01e1b684525bae4cb329515989cd341875.json b/backend/.sqlx/query-24cfd719a45af5beb4eb264939290c01e1b684525bae4cb329515989cd341875.json new file mode 100644 index 0000000000..eaa7d60dea --- /dev/null +++ b/backend/.sqlx/query-24cfd719a45af5beb4eb264939290c01e1b684525bae4cb329515989cd341875.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "\n INSERT INTO runnable_job_stats\n (hour, workspace_id, runnable_path, worker_group, job_count, total_duration_ms,\n max_memory_peak, sum_memory_peak, memory_sample_count, total_cpu_ms)\n SELECT s.hour, s.workspace_id, s.runnable_path, s.worker_group, s.job_count,\n s.total_duration_ms, s.max_memory_peak, s.sum_memory_peak,\n s.memory_sample_count, s.total_cpu_ms\n FROM UNNEST($1::bigint[], $2::text[], $3::text[], $4::text[], $5::int[], $6::bigint[],\n $7::int[], $8::bigint[], $9::int[], $10::bigint[])\n AS s(hour, workspace_id, runnable_path, worker_group, job_count, total_duration_ms,\n max_memory_peak, sum_memory_peak, memory_sample_count, total_cpu_ms)\n JOIN workspace w ON w.id = s.workspace_id\n ORDER BY s.hour, s.workspace_id, s.runnable_path, s.worker_group\n ON CONFLICT (hour, workspace_id, runnable_path, worker_group) DO UPDATE SET\n job_count = runnable_job_stats.job_count + EXCLUDED.job_count,\n total_duration_ms = runnable_job_stats.total_duration_ms + EXCLUDED.total_duration_ms,\n max_memory_peak = GREATEST(runnable_job_stats.max_memory_peak, EXCLUDED.max_memory_peak),\n sum_memory_peak = runnable_job_stats.sum_memory_peak + EXCLUDED.sum_memory_peak,\n memory_sample_count = runnable_job_stats.memory_sample_count + EXCLUDED.memory_sample_count,\n total_cpu_ms = runnable_job_stats.total_cpu_ms + EXCLUDED.total_cpu_ms\n ", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Int8Array", + "TextArray", + "TextArray", + "TextArray", + "Int4Array", + "Int8Array", + "Int4Array", + "Int8Array", + "Int4Array", + "Int8Array" + ] + }, + "nullable": [] + }, + "hash": "24cfd719a45af5beb4eb264939290c01e1b684525bae4cb329515989cd341875" +} diff --git a/backend/.sqlx/query-250ac2b81a8d9a6900d8b54322fe21ef62eddd307717b24aa4fc03c0297e8f59.json b/backend/.sqlx/query-250ac2b81a8d9a6900d8b54322fe21ef62eddd307717b24aa4fc03c0297e8f59.json new file mode 100644 index 0000000000..52f512d012 --- /dev/null +++ b/backend/.sqlx/query-250ac2b81a8d9a6900d8b54322fe21ef62eddd307717b24aa4fc03c0297e8f59.json @@ -0,0 +1,25 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS (\n SELECT 1 FROM v2_job_queue q\n CROSS JOIN LATERAL (\n SELECT trigger_kind, trigger, runnable_path, parent_job\n FROM v2_job WHERE id = q.id OFFSET 0\n ) j\n WHERE q.workspace_id = $1 AND q.scheduled_for = $3\n AND j.trigger_kind = 'schedule' AND j.trigger = $2 AND j.runnable_path = $4\n AND j.parent_job IS NULL\n )", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "exists", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "Timestamptz", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "250ac2b81a8d9a6900d8b54322fe21ef62eddd307717b24aa4fc03c0297e8f59" +} diff --git a/backend/.sqlx/query-25bf3956b4365a4d4f96368bcc6e33817ae284ab26c195eee53d988d74263e86.json b/backend/.sqlx/query-25bf3956b4365a4d4f96368bcc6e33817ae284ab26c195eee53d988d74263e86.json deleted file mode 100644 index f7d03b7ebe..0000000000 --- a/backend/.sqlx/query-25bf3956b4365a4d4f96368bcc6e33817ae284ab26c195eee53d988d74263e86.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT (error_handler->>'muted_on_cancel')::boolean FROM workspace_settings WHERE workspace_id = 'test-workspace'", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "bool", - "type_info": "Bool" - } - ], - "parameters": { - "Left": [] - }, - "nullable": [ - null - ] - }, - "hash": "25bf3956b4365a4d4f96368bcc6e33817ae284ab26c195eee53d988d74263e86" -} diff --git a/backend/.sqlx/query-28b8264a427e8c19be823d2b8e40736a7b7675780672b503d91737cd0c617657.json b/backend/.sqlx/query-28b8264a427e8c19be823d2b8e40736a7b7675780672b503d91737cd0c617657.json deleted file mode 100644 index 4a34503aaa..0000000000 --- a/backend/.sqlx/query-28b8264a427e8c19be823d2b8e40736a7b7675780672b503d91737cd0c617657.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT (error_handler->>'muted_on_user_path')::boolean FROM workspace_settings WHERE workspace_id = 'test-workspace'", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "bool", - "type_info": "Bool" - } - ], - "parameters": { - "Left": [] - }, - "nullable": [ - null - ] - }, - "hash": "28b8264a427e8c19be823d2b8e40736a7b7675780672b503d91737cd0c617657" -} diff --git a/backend/.sqlx/query-28f3dfb70aed943ad3d64da608168c027c645afb73dfc2360245b68ba593cab4.json b/backend/.sqlx/query-28f3dfb70aed943ad3d64da608168c027c645afb73dfc2360245b68ba593cab4.json deleted file mode 100644 index 3eb58e590f..0000000000 --- a/backend/.sqlx/query-28f3dfb70aed943ad3d64da608168c027c645afb73dfc2360245b68ba593cab4.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n UPDATE workspace_settings\n SET success_handler = '{\"path\": \"script/f/test/success_handler\", \"extra_args\": {\"key\": \"value\"}}'::jsonb\n WHERE workspace_id = 'test-workspace'\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [] - }, - "nullable": [] - }, - "hash": "28f3dfb70aed943ad3d64da608168c027c645afb73dfc2360245b68ba593cab4" -} diff --git a/backend/.sqlx/query-2c2ed5c91a4893966e94305df8b9f8ac904c8d0781a83fdea66c918320fb5601.json b/backend/.sqlx/query-2c2ed5c91a4893966e94305df8b9f8ac904c8d0781a83fdea66c918320fb5601.json deleted file mode 100644 index 4b692f11a2..0000000000 --- a/backend/.sqlx/query-2c2ed5c91a4893966e94305df8b9f8ac904c8d0781a83fdea66c918320fb5601.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n UPDATE workspace_settings\n SET success_handler = NULL\n WHERE workspace_id = 'test-workspace'\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [] - }, - "nullable": [] - }, - "hash": "2c2ed5c91a4893966e94305df8b9f8ac904c8d0781a83fdea66c918320fb5601" -} diff --git a/backend/.sqlx/query-2d22fe27288580cb727e43b2abe3be2e6e6e3b03e61ce8f2879627115224c8cf.json b/backend/.sqlx/query-2d22fe27288580cb727e43b2abe3be2e6e6e3b03e61ce8f2879627115224c8cf.json new file mode 100644 index 0000000000..95fd9a3a2f --- /dev/null +++ b/backend/.sqlx/query-2d22fe27288580cb727e43b2abe3be2e6e6e3b03e61ce8f2879627115224c8cf.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT config FROM config WHERE name = $1 FOR UPDATE", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "config", + "type_info": "Jsonb" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + true + ] + }, + "hash": "2d22fe27288580cb727e43b2abe3be2e6e6e3b03e61ce8f2879627115224c8cf" +} diff --git a/backend/.sqlx/query-2d43c1889b492df6f77380e739e41e20fe6bea0553cc39e30b7aa8ae59963f95.json b/backend/.sqlx/query-2d43c1889b492df6f77380e739e41e20fe6bea0553cc39e30b7aa8ae59963f95.json deleted file mode 100644 index 532fc430ab..0000000000 --- a/backend/.sqlx/query-2d43c1889b492df6f77380e739e41e20fe6bea0553cc39e30b7aa8ae59963f95.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock)\n VALUES ('test-workspace', 1234567890, 'f/test/success_handler', $1, 'deno', 'script', 'test-user', '{}', 'Success handler script', 'Handles successful job completions', '')\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Text" - ] - }, - "nullable": [] - }, - "hash": "2d43c1889b492df6f77380e739e41e20fe6bea0553cc39e30b7aa8ae59963f95" -} diff --git a/backend/.sqlx/query-386e14cf7572027f2c4ef313cd7cc5dd6c7b0da4f76131313d3e6d97f36c5c34.json b/backend/.sqlx/query-386e14cf7572027f2c4ef313cd7cc5dd6c7b0da4f76131313d3e6d97f36c5c34.json deleted file mode 100644 index 2f794e6be0..0000000000 --- a/backend/.sqlx/query-386e14cf7572027f2c4ef313cd7cc5dd6c7b0da4f76131313d3e6d97f36c5c34.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT EXISTS(SELECT 1 FROM resource_type WHERE workspace_id = 'admins' AND name = $1 AND schema IS NOT DISTINCT FROM $2 AND description IS NOT DISTINCT FROM $3 AND ($5 IS NOT TRUE OR format_extension IS NOT DISTINCT FROM $4) AND ($7 IS NOT TRUE OR display_name IS NOT DISTINCT FROM $6))", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "exists", - "type_info": "Bool" - } - ], - "parameters": { - "Left": [ - "Text", - "Jsonb", - "Text", - "Text", - "Bool", - "Text", - "Bool" - ] - }, - "nullable": [ - null - ] - }, - "hash": "386e14cf7572027f2c4ef313cd7cc5dd6c7b0da4f76131313d3e6d97f36c5c34" -} diff --git a/backend/.sqlx/query-3a47d8ec0f4ba1644951f0c88504c9f769ffe5004871a049e4232e0092532062.json b/backend/.sqlx/query-3a47d8ec0f4ba1644951f0c88504c9f769ffe5004871a049e4232e0092532062.json deleted file mode 100644 index a07fcd57db..0000000000 --- a/backend/.sqlx/query-3a47d8ec0f4ba1644951f0c88504c9f769ffe5004871a049e4232e0092532062.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT EXISTS (\n SELECT 1 FROM v2_job j JOIN v2_job_queue USING (id)\n WHERE j.workspace_id = $1 AND trigger_kind = 'schedule' AND trigger = $2 AND runnable_path = $4\n AND parent_job IS NULL\n AND scheduled_for = $3\n )", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "exists", - "type_info": "Bool" - } - ], - "parameters": { - "Left": [ - "Text", - "Text", - "Timestamptz", - "Text" - ] - }, - "nullable": [ - null - ] - }, - "hash": "3a47d8ec0f4ba1644951f0c88504c9f769ffe5004871a049e4232e0092532062" -} diff --git a/backend/.sqlx/query-3a71ab02239d8dd4e2f440a35155459a7d5091c125a0998e79d89f8c560a3fd3.json b/backend/.sqlx/query-3a71ab02239d8dd4e2f440a35155459a7d5091c125a0998e79d89f8c560a3fd3.json deleted file mode 100644 index 1c370d3ccf..0000000000 --- a/backend/.sqlx/query-3a71ab02239d8dd4e2f440a35155459a7d5091c125a0998e79d89f8c560a3fd3.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n INSERT INTO group_ (workspace_id, name, summary, extra_perms)\n VALUES ('test-workspace', 'success_handler', 'The group the success handler acts on behalf of', '{\"u/test-user\": true}')\n ON CONFLICT DO NOTHING\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [] - }, - "nullable": [] - }, - "hash": "3a71ab02239d8dd4e2f440a35155459a7d5091c125a0998e79d89f8c560a3fd3" -} diff --git a/backend/.sqlx/query-3d38720e807b379645d8f3ab61c6a968143d42c3014152608f7d1b252cd8085c.json b/backend/.sqlx/query-3d38720e807b379645d8f3ab61c6a968143d42c3014152608f7d1b252cd8085c.json deleted file mode 100644 index a97d16b89c..0000000000 --- a/backend/.sqlx/query-3d38720e807b379645d8f3ab61c6a968143d42c3014152608f7d1b252cd8085c.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "INSERT INTO app_version\n (app_id, value, created_by, raw_app)\n SELECT app_id, value, created_by, raw_app\n FROM app_version WHERE id = $1\n RETURNING id", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "id", - "type_info": "Int8" - } - ], - "parameters": { - "Left": [ - "Int8" - ] - }, - "nullable": [ - false - ] - }, - "hash": "3d38720e807b379645d8f3ab61c6a968143d42c3014152608f7d1b252cd8085c" -} diff --git a/backend/.sqlx/query-4448d2cc6bc73635bb8c252ab9f4efaa33600c3ecd266e8339b9bfb32ae18499.json b/backend/.sqlx/query-4448d2cc6bc73635bb8c252ab9f4efaa33600c3ecd266e8339b9bfb32ae18499.json new file mode 100644 index 0000000000..cd2e6651b8 --- /dev/null +++ b/backend/.sqlx/query-4448d2cc6bc73635bb8c252ab9f4efaa33600c3ecd266e8339b9bfb32ae18499.json @@ -0,0 +1,27 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO app_script (app, hash, lock, code, code_sha256, modules)\n VALUES ($1, $2, $3, $4, $5, $6)\n ON CONFLICT (hash) DO UPDATE SET app = EXCLUDED.app -- trivial update to return the id\n RETURNING id", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [ + "Int8", + "Bpchar", + "Text", + "Text", + "Bpchar", + "Jsonb" + ] + }, + "nullable": [ + false + ] + }, + "hash": "4448d2cc6bc73635bb8c252ab9f4efaa33600c3ecd266e8339b9bfb32ae18499" +} diff --git a/backend/.sqlx/query-45b73345f2009122142f3410736b2d57a07e2047a704d9a7d8eab3416ff1d9d5.json b/backend/.sqlx/query-45b73345f2009122142f3410736b2d57a07e2047a704d9a7d8eab3416ff1d9d5.json new file mode 100644 index 0000000000..2c22ae1d7e --- /dev/null +++ b/backend/.sqlx/query-45b73345f2009122142f3410736b2d57a07e2047a704d9a7d8eab3416ff1d9d5.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS (SELECT 1 FROM fork_storage_namespace WHERE workspace_id = ANY($1))\n AND EXISTS (SELECT 1 FROM workspace WHERE parent_workspace_id = $2)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "?column?", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "TextArray", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "45b73345f2009122142f3410736b2d57a07e2047a704d9a7d8eab3416ff1d9d5" +} diff --git a/backend/.sqlx/query-4640ac69b297127cd0f5c369fa4a49857237cd57134dbc467b53601c1ec942d2.json b/backend/.sqlx/query-4640ac69b297127cd0f5c369fa4a49857237cd57134dbc467b53601c1ec942d2.json new file mode 100644 index 0000000000..5ad778d3c0 --- /dev/null +++ b/backend/.sqlx/query-4640ac69b297127cd0f5c369fa4a49857237cd57134dbc467b53601c1ec942d2.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS (SELECT 1 FROM fork_storage_namespace WHERE workspace_id = $1)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "exists", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "4640ac69b297127cd0f5c369fa4a49857237cd57134dbc467b53601c1ec942d2" +} diff --git a/backend/.sqlx/query-51f18c817d4014e847486f5a8dbf205ffa0e53d5bd3fdb97777e988389b1d69e.json b/backend/.sqlx/query-51f18c817d4014e847486f5a8dbf205ffa0e53d5bd3fdb97777e988389b1d69e.json deleted file mode 100644 index 6eceb86132..0000000000 --- a/backend/.sqlx/query-51f18c817d4014e847486f5a8dbf205ffa0e53d5bd3fdb97777e988389b1d69e.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock)\n VALUES ('test-workspace', $1, 'f/test/success_script', 'export function main() { return \"ok\"; }', 'deno', 'script', 'test-user', '{}', '', '', '')\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Int8" - ] - }, - "nullable": [] - }, - "hash": "51f18c817d4014e847486f5a8dbf205ffa0e53d5bd3fdb97777e988389b1d69e" -} diff --git a/backend/.sqlx/query-5c13c681df0c57fcdbd1364f0f084aad096911efd453dd50f6865e53c1e77881.json b/backend/.sqlx/query-5c13c681df0c57fcdbd1364f0f084aad096911efd453dd50f6865e53c1e77881.json deleted file mode 100644 index 4d756dbaa7..0000000000 --- a/backend/.sqlx/query-5c13c681df0c57fcdbd1364f0f084aad096911efd453dd50f6865e53c1e77881.json +++ /dev/null @@ -1,46 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT\n flow_step_id,\n (flow_status->'step')::integer as step,\n jsonb_array_length(flow_status->'modules') as len,\n runnable_path ~ '/branchone-\\d+$' as is_branch_one,\n parent_job as next_parent\n FROM v2_job\n LEFT JOIN v2_job_status USING (id)\n WHERE v2_job.id = $1", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "flow_step_id", - "type_info": "Varchar" - }, - { - "ordinal": 1, - "name": "step", - "type_info": "Int4" - }, - { - "ordinal": 2, - "name": "len", - "type_info": "Int4" - }, - { - "ordinal": 3, - "name": "is_branch_one", - "type_info": "Bool" - }, - { - "ordinal": 4, - "name": "next_parent", - "type_info": "Uuid" - } - ], - "parameters": { - "Left": [ - "Uuid" - ] - }, - "nullable": [ - true, - null, - null, - null, - true - ] - }, - "hash": "5c13c681df0c57fcdbd1364f0f084aad096911efd453dd50f6865e53c1e77881" -} diff --git a/backend/.sqlx/query-5c72e6e4102039c4426e8eb47d86ec152d4ee52b58f208f2fa1639eaa448c6ad.json b/backend/.sqlx/query-5c72e6e4102039c4426e8eb47d86ec152d4ee52b58f208f2fa1639eaa448c6ad.json deleted file mode 100644 index 3458d1068e..0000000000 --- a/backend/.sqlx/query-5c72e6e4102039c4426e8eb47d86ec152d4ee52b58f208f2fa1639eaa448c6ad.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "INSERT INTO app_script (app, hash, lock, code, code_sha256)\n VALUES ($1, $2, $3, $4, $5) ON CONFLICT DO NOTHING", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Int8", - "Bpchar", - "Text", - "Text", - "Bpchar" - ] - }, - "nullable": [] - }, - "hash": "5c72e6e4102039c4426e8eb47d86ec152d4ee52b58f208f2fa1639eaa448c6ad" -} diff --git a/backend/.sqlx/query-5f5bdd667f699a5a1c05e07d805a97afb06252541d06b4785063819c3893b674.json b/backend/.sqlx/query-5f5bdd667f699a5a1c05e07d805a97afb06252541d06b4785063819c3893b674.json deleted file mode 100644 index 812fed8f23..0000000000 --- a/backend/.sqlx/query-5f5bdd667f699a5a1c05e07d805a97afb06252541d06b4785063819c3893b674.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n INSERT INTO group_ (workspace_id, name, summary, extra_perms)\n VALUES ('test-workspace', 'error_handler', 'The group the error handler acts on behalf of', '{\"u/test-user\": true}')\n ON CONFLICT DO NOTHING\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [] - }, - "nullable": [] - }, - "hash": "5f5bdd667f699a5a1c05e07d805a97afb06252541d06b4785063819c3893b674" -} diff --git a/backend/.sqlx/query-65016ea993fb40d4ab6b0a6f15c2082e8dfbaada01243bae07065c089bc42fa9.json b/backend/.sqlx/query-65016ea993fb40d4ab6b0a6f15c2082e8dfbaada01243bae07065c089bc42fa9.json deleted file mode 100644 index c0e9198953..0000000000 --- a/backend/.sqlx/query-65016ea993fb40d4ab6b0a6f15c2082e8dfbaada01243bae07065c089bc42fa9.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n UPDATE workspace_settings\n SET success_handler = '{\"path\": \"script/f/test/success_handler\"}'::jsonb\n WHERE workspace_id = 'test-workspace'\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [] - }, - "nullable": [] - }, - "hash": "65016ea993fb40d4ab6b0a6f15c2082e8dfbaada01243bae07065c089bc42fa9" -} diff --git a/backend/.sqlx/query-711927611ecf0144b6241b8f39f94b79f4ff03bdae60ab746f930f8758fe46bc.json b/backend/.sqlx/query-711927611ecf0144b6241b8f39f94b79f4ff03bdae60ab746f930f8758fe46bc.json new file mode 100644 index 0000000000..4735c589ac --- /dev/null +++ b/backend/.sqlx/query-711927611ecf0144b6241b8f39f94b79f4ff03bdae60ab746f930f8758fe46bc.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE job_perms SET viewer_data_access = true WHERE job_id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [] + }, + "hash": "711927611ecf0144b6241b8f39f94b79f4ff03bdae60ab746f930f8758fe46bc" +} diff --git a/backend/.sqlx/query-71c9e0c0f1d9eba0f24c8e410ca2f2a64dc559e3228d3b763f68b1ad3491ae6e.json b/backend/.sqlx/query-71c9e0c0f1d9eba0f24c8e410ca2f2a64dc559e3228d3b763f68b1ad3491ae6e.json new file mode 100644 index 0000000000..ba1cc13fac --- /dev/null +++ b/backend/.sqlx/query-71c9e0c0f1d9eba0f24c8e410ca2f2a64dc559e3228d3b763f68b1ad3491ae6e.json @@ -0,0 +1,45 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH deleted AS (\n DELETE FROM v2_job_queue WHERE id = $1\n RETURNING id, workspace_id, started_at, worker, canceled_by, canceled_reason,\n (extras->>'wac_first_started_at')::timestamptz AS first_started_at,\n COALESCE($9::bigint, (EXTRACT('epoch' FROM (now())) - EXTRACT('epoch' FROM (COALESCE(started_at, now()))))*1000)::bigint AS run_ms\n ), completed AS (\n INSERT INTO v2_job_completed AS cj\n ( workspace_id\n , id\n , started_at\n , duration_ms\n , extras\n , result\n , result_columns\n , canceled_by\n , canceled_reason\n , flow_status\n , workflow_as_code_status\n , memory_peak\n , status\n , worker\n )\n SELECT d.workspace_id, d.id, COALESCE(d.first_started_at, d.started_at),\n CASE WHEN d.first_started_at IS NULL THEN d.run_ms\n ELSE EXTRACT('epoch' FROM (now() - d.first_started_at))*1000 END,\n CASE WHEN d.first_started_at IS NOT NULL\n THEN jsonb_build_object('wac_last_segment_ms', d.run_ms) END,\n $3::text::jsonb, $10,\n CASE WHEN $4::BOOL THEN $5 ELSE d.canceled_by END,\n CASE WHEN $4::BOOL THEN $6 WHEN d.canceled_by IS NOT NULL THEN d.canceled_reason END,\n s.flow_status, s.workflow_as_code_status, $8,\n CASE WHEN $4::BOOL OR d.canceled_by IS NOT NULL THEN 'canceled'::job_status\n WHEN $7::BOOL THEN 'skipped'::job_status\n WHEN $2::BOOL THEN 'success'::job_status\n ELSE 'failure'::job_status END,\n d.worker\n FROM deleted d LEFT JOIN v2_job_status s ON s.id = d.id\n ON CONFLICT (id) DO UPDATE SET status = EXCLUDED.status, result = $3::text::jsonb,\n canceled_by = CASE WHEN NOT $4::BOOL AND EXCLUDED.canceled_by IS NOT NULL\n THEN EXCLUDED.canceled_by ELSE cj.canceled_by END,\n canceled_reason = CASE WHEN NOT $4::BOOL AND EXCLUDED.canceled_by IS NOT NULL\n THEN EXCLUDED.canceled_reason ELSE cj.canceled_reason END\n RETURNING cj.started_at, cj.duration_ms,\n COALESCE((cj.extras->>'wac_last_segment_ms')::bigint, cj.duration_ms) AS last_run_ms\n ), parent_ping AS (\n UPDATE v2_job_runtime r SET ping = now()\n FROM v2_job_queue q\n WHERE r.id = $11 AND q.id = r.id AND q.workspace_id = $12\n AND EXISTS (SELECT 1 FROM completed)\n )\n SELECT started_at AS \"started_at?\", duration_ms AS \"duration_ms!\",\n last_run_ms AS \"last_run_ms!\" FROM completed", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "started_at?", + "type_info": "Timestamptz" + }, + { + "ordinal": 1, + "name": "duration_ms!", + "type_info": "Int8" + }, + { + "ordinal": 2, + "name": "last_run_ms!", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [ + "Uuid", + "Bool", + "Text", + "Bool", + "Varchar", + "Text", + "Bool", + "Int4", + "Int8", + "TextArray", + "Uuid", + "Text" + ] + }, + "nullable": [ + true, + false, + null + ] + }, + "hash": "71c9e0c0f1d9eba0f24c8e410ca2f2a64dc559e3228d3b763f68b1ad3491ae6e" +} diff --git a/backend/.sqlx/query-71de038f332593e2177f33284854b6c0bfe9bb4999f2c4e9082a4c5f3b341496.json b/backend/.sqlx/query-71de038f332593e2177f33284854b6c0bfe9bb4999f2c4e9082a4c5f3b341496.json deleted file mode 100644 index b647ec29fa..0000000000 --- a/backend/.sqlx/query-71de038f332593e2177f33284854b6c0bfe9bb4999f2c4e9082a4c5f3b341496.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n SELECT\n id,\n runnable_path,\n permissioned_as_email,\n parent_job\n FROM v2_job\n WHERE workspace_id = 'test-workspace'\n AND permissioned_as_email = 'success_handler@windmill.dev'\n ORDER BY created_at DESC\n LIMIT 1\n ", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "id", - "type_info": "Uuid" - }, - { - "ordinal": 1, - "name": "runnable_path", - "type_info": "Varchar" - }, - { - "ordinal": 2, - "name": "permissioned_as_email", - "type_info": "Varchar" - }, - { - "ordinal": 3, - "name": "parent_job", - "type_info": "Uuid" - } - ], - "parameters": { - "Left": [] - }, - "nullable": [ - false, - true, - false, - true - ] - }, - "hash": "71de038f332593e2177f33284854b6c0bfe9bb4999f2c4e9082a4c5f3b341496" -} diff --git a/backend/.sqlx/query-73a22a814ae983ae6b0188ee2b9f110dadb3db328f0589f7de27bcb418e70371.json b/backend/.sqlx/query-73a22a814ae983ae6b0188ee2b9f110dadb3db328f0589f7de27bcb418e70371.json new file mode 100644 index 0000000000..f4092042dd --- /dev/null +++ b/backend/.sqlx/query-73a22a814ae983ae6b0188ee2b9f110dadb3db328f0589f7de27bcb418e70371.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT id, value AS \"value!: serde_json::Value\" FROM app_version_lite WHERE id = ANY($1)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Int8" + }, + { + "ordinal": 1, + "name": "value!: serde_json::Value", + "type_info": "Jsonb" + } + ], + "parameters": { + "Left": [ + "Int8Array" + ] + }, + "nullable": [ + false, + true + ] + }, + "hash": "73a22a814ae983ae6b0188ee2b9f110dadb3db328f0589f7de27bcb418e70371" +} diff --git a/backend/.sqlx/query-748b63f877498d6d279fdf23894611e11c7a05d69b4b7907f8909aec82fb1eb2.json b/backend/.sqlx/query-748b63f877498d6d279fdf23894611e11c7a05d69b4b7907f8909aec82fb1eb2.json deleted file mode 100644 index d710d59055..0000000000 --- a/backend/.sqlx/query-748b63f877498d6d279fdf23894611e11c7a05d69b4b7907f8909aec82fb1eb2.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "INSERT INTO resource (workspace_id, path, value, description, resource_type, extra_perms, edited_at, created_by)\n SELECT $2, path, value, description, resource_type, extra_perms, edited_at, created_by\n FROM resource\n WHERE workspace_id = $1", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Text", - "Varchar" - ] - }, - "nullable": [] - }, - "hash": "748b63f877498d6d279fdf23894611e11c7a05d69b4b7907f8909aec82fb1eb2" -} diff --git a/backend/.sqlx/query-ffa86babfcab107caffb8dda31a66b142fa628b8983b966357deb3d5e0a1df3c.json b/backend/.sqlx/query-7796f40e349bf0771cceff037fa2224ab49659213638230be7f9acbf82d8e1b0.json similarity index 53% rename from backend/.sqlx/query-ffa86babfcab107caffb8dda31a66b142fa628b8983b966357deb3d5e0a1df3c.json rename to backend/.sqlx/query-7796f40e349bf0771cceff037fa2224ab49659213638230be7f9acbf82d8e1b0.json index 49fe5cf6b8..cf9dc458c2 100644 --- a/backend/.sqlx/query-ffa86babfcab107caffb8dda31a66b142fa628b8983b966357deb3d5e0a1df3c.json +++ b/backend/.sqlx/query-7796f40e349bf0771cceff037fa2224ab49659213638230be7f9acbf82d8e1b0.json @@ -1,28 +1,28 @@ { "db_name": "PostgreSQL", - "query": "SELECT lock, code FROM app_script WHERE id = $1 LIMIT 1", + "query": "SELECT storage, storage_ref FROM fork_storage_namespace WHERE workspace_id = $1", "describe": { "columns": [ { "ordinal": 0, - "name": "lock", + "name": "storage", "type_info": "Text" }, { "ordinal": 1, - "name": "code", + "name": "storage_ref", "type_info": "Text" } ], "parameters": { "Left": [ - "Int8" + "Text" ] }, "nullable": [ - true, + false, false ] }, - "hash": "ffa86babfcab107caffb8dda31a66b142fa628b8983b966357deb3d5e0a1df3c" + "hash": "7796f40e349bf0771cceff037fa2224ab49659213638230be7f9acbf82d8e1b0" } diff --git a/backend/.sqlx/query-782c259ccdf71c5e2fa8dcb27515e7c5ff83009774dc15095ed0dbcb0ecdbdde.json b/backend/.sqlx/query-782c259ccdf71c5e2fa8dcb27515e7c5ff83009774dc15095ed0dbcb0ecdbdde.json deleted file mode 100644 index f3449712c9..0000000000 --- a/backend/.sqlx/query-782c259ccdf71c5e2fa8dcb27515e7c5ff83009774dc15095ed0dbcb0ecdbdde.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock, ws_error_handler_muted)\n VALUES ('test-workspace', $1, 'f/test/muted_failing_script', 'export function main() { throw new Error(\"fail\"); }', 'deno', 'script', 'test-user', '{}', '', '', '', true)\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Int8" - ] - }, - "nullable": [] - }, - "hash": "782c259ccdf71c5e2fa8dcb27515e7c5ff83009774dc15095ed0dbcb0ecdbdde" -} diff --git a/backend/.sqlx/query-7963eff5f7109874b94c0940eaef7d4b418a9e82be56dfe7dd65d160e0dcfd13.json b/backend/.sqlx/query-7963eff5f7109874b94c0940eaef7d4b418a9e82be56dfe7dd65d160e0dcfd13.json new file mode 100644 index 0000000000..1c8dfcfa57 --- /dev/null +++ b/backend/.sqlx/query-7963eff5f7109874b94c0940eaef7d4b418a9e82be56dfe7dd65d160e0dcfd13.json @@ -0,0 +1,24 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT wp.draining FROM v2_job j\n JOIN v2_job_queue q ON q.id = j.id\n JOIN worker_ping wp ON wp.worker = q.worker\n WHERE j.id = $1 AND j.workspace_id = $2 AND q.running AND q.started_at IS NOT NULL\n AND ($3::text[] IS NULL OR j.tag = ANY($3))", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "draining", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Uuid", + "Text", + "TextArray" + ] + }, + "nullable": [ + false + ] + }, + "hash": "7963eff5f7109874b94c0940eaef7d4b418a9e82be56dfe7dd65d160e0dcfd13" +} diff --git a/backend/.sqlx/query-79648f03eb50385183c34d57bda1ac984cf6502609df9ee51b7d684b585b8447.json b/backend/.sqlx/query-79648f03eb50385183c34d57bda1ac984cf6502609df9ee51b7d684b585b8447.json deleted file mode 100644 index fbf0c98de4..0000000000 --- a/backend/.sqlx/query-79648f03eb50385183c34d57bda1ac984cf6502609df9ee51b7d684b585b8447.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n UPDATE workspace_settings\n SET error_handler = NULL\n WHERE workspace_id = 'test-workspace'\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [] - }, - "nullable": [] - }, - "hash": "79648f03eb50385183c34d57bda1ac984cf6502609df9ee51b7d684b585b8447" -} diff --git a/backend/.sqlx/query-7b1d7a1404c3a17e1852e1fe7d32d04d8c95e1e87e75b9a07b01c03f3e3d4373.json b/backend/.sqlx/query-7b1d7a1404c3a17e1852e1fe7d32d04d8c95e1e87e75b9a07b01c03f3e3d4373.json new file mode 100644 index 0000000000..e5ee2e27e8 --- /dev/null +++ b/backend/.sqlx/query-7b1d7a1404c3a17e1852e1fe7d32d04d8c95e1e87e75b9a07b01c03f3e3d4373.json @@ -0,0 +1,34 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT lock, code, modules AS \"modules: serde_json::Value\"\n FROM app_script WHERE id = $1 LIMIT 1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "lock", + "type_info": "Text" + }, + { + "ordinal": 1, + "name": "code", + "type_info": "Text" + }, + { + "ordinal": 2, + "name": "modules: serde_json::Value", + "type_info": "Jsonb" + } + ], + "parameters": { + "Left": [ + "Int8" + ] + }, + "nullable": [ + true, + false, + true + ] + }, + "hash": "7b1d7a1404c3a17e1852e1fe7d32d04d8c95e1e87e75b9a07b01c03f3e3d4373" +} diff --git a/backend/.sqlx/query-7cc9d80bc4c77c996521a7c82ca42162e96499987b17a34bde7bc32d54e6260e.json b/backend/.sqlx/query-7cc9d80bc4c77c996521a7c82ca42162e96499987b17a34bde7bc32d54e6260e.json new file mode 100644 index 0000000000..6af78adde7 --- /dev/null +++ b/backend/.sqlx/query-7cc9d80bc4c77c996521a7c82ca42162e96499987b17a34bde7bc32d54e6260e.json @@ -0,0 +1,55 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE ai_shared_session SET is_public = $4\n WHERE workspace_id = $1 AND id = $2 AND email = $3\n RETURNING id, name, is_public, message_count, created_by, shared_at", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "name", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "is_public", + "type_info": "Bool" + }, + { + "ordinal": 3, + "name": "message_count", + "type_info": "Int4" + }, + { + "ordinal": 4, + "name": "created_by", + "type_info": "Varchar" + }, + { + "ordinal": 5, + "name": "shared_at", + "type_info": "Timestamptz" + } + ], + "parameters": { + "Left": [ + "Text", + "Uuid", + "Text", + "Bool" + ] + }, + "nullable": [ + false, + false, + false, + false, + false, + false + ] + }, + "hash": "7cc9d80bc4c77c996521a7c82ca42162e96499987b17a34bde7bc32d54e6260e" +} diff --git a/backend/.sqlx/query-7ec099041134ee34057b57e86b35c67fad4532904ed633b85c3bbc627367ef0c.json b/backend/.sqlx/query-7ec099041134ee34057b57e86b35c67fad4532904ed633b85c3bbc627367ef0c.json new file mode 100644 index 0000000000..bb026c9b31 --- /dev/null +++ b/backend/.sqlx/query-7ec099041134ee34057b57e86b35c67fad4532904ed633b85c3bbc627367ef0c.json @@ -0,0 +1,34 @@ +{ + "db_name": "PostgreSQL", + "query": "\n WITH RECURSIVE chain AS (\n SELECT id, parent_workspace_id, is_dev_workspace, deleted, 0 AS depth\n FROM workspace WHERE id = $1\n UNION ALL\n SELECT w.id, w.parent_workspace_id, w.is_dev_workspace, w.deleted, chain.depth + 1\n FROM workspace w\n JOIN chain ON w.id = chain.parent_workspace_id\n WHERE chain.depth < 20\n )\n SELECT\n (SELECT id FROM chain\n WHERE parent_workspace_id IS NULL\n OR (is_dev_workspace AND id NOT LIKE 'wm-fork-%')\n ORDER BY depth LIMIT 1) AS id,\n (SELECT parent_workspace_id IS NOT NULL FROM chain WHERE depth = 0) AS has_parent,\n (SELECT bool_or(is_dev_workspace\n OR (parent_workspace_id IS NULL AND id LIKE 'wm-fork-%')\n OR (deleted AND parent_workspace_id IS NOT NULL))\n FROM chain) AS in_dev_lineage\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "has_parent", + "type_info": "Bool" + }, + { + "ordinal": 2, + "name": "in_dev_lineage", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + null, + null, + null + ] + }, + "hash": "7ec099041134ee34057b57e86b35c67fad4532904ed633b85c3bbc627367ef0c" +} diff --git a/backend/.sqlx/query-7f98c013682aca6d269ef6ef754a7247b6e2dd4958d0968a3f2eb49cc320e877.json b/backend/.sqlx/query-7f98c013682aca6d269ef6ef754a7247b6e2dd4958d0968a3f2eb49cc320e877.json deleted file mode 100644 index 90b559a9b6..0000000000 --- a/backend/.sqlx/query-7f98c013682aca6d269ef6ef754a7247b6e2dd4958d0968a3f2eb49cc320e877.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock)\n VALUES ('test-workspace', 3333333333, 'f/test/error_handler', 'export function main() { return \"handled\"; }', 'deno', 'script', 'test-user', '{}', '', '', '')\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [] - }, - "nullable": [] - }, - "hash": "7f98c013682aca6d269ef6ef754a7247b6e2dd4958d0968a3f2eb49cc320e877" -} diff --git a/backend/.sqlx/query-8645e610aa35088376d0919132459bce3ad17df617855e5fcf838f6349e68c97.json b/backend/.sqlx/query-8645e610aa35088376d0919132459bce3ad17df617855e5fcf838f6349e68c97.json new file mode 100644 index 0000000000..446e9da6df --- /dev/null +++ b/backend/.sqlx/query-8645e610aa35088376d0919132459bce3ad17df617855e5fcf838f6349e68c97.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO global_settings (name, value) VALUES ($1, 'true'::jsonb) ON CONFLICT (name) DO NOTHING", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar" + ] + }, + "nullable": [] + }, + "hash": "8645e610aa35088376d0919132459bce3ad17df617855e5fcf838f6349e68c97" +} diff --git a/backend/.sqlx/query-87044e1466cd114cbef336620e96dc29f3f930149fedc240d44c614dfc794ff7.json b/backend/.sqlx/query-87044e1466cd114cbef336620e96dc29f3f930149fedc240d44c614dfc794ff7.json deleted file mode 100644 index 9915fbf6c8..0000000000 --- a/backend/.sqlx/query-87044e1466cd114cbef336620e96dc29f3f930149fedc240d44c614dfc794ff7.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT success_handler->'extra_args' FROM workspace_settings WHERE workspace_id = 'test-workspace'", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "?column?", - "type_info": "Jsonb" - } - ], - "parameters": { - "Left": [] - }, - "nullable": [ - null - ] - }, - "hash": "87044e1466cd114cbef336620e96dc29f3f930149fedc240d44c614dfc794ff7" -} diff --git a/backend/.sqlx/query-7904ac35748b1de2c7ff764f22787436d0fe74f99f298e5c399233f0d247f2ec.json b/backend/.sqlx/query-8aef4f9d27ec6df07cd671bcf90bf378e9fac4986cd29f69c1f2b8a83ba515c3.json similarity index 54% rename from backend/.sqlx/query-7904ac35748b1de2c7ff764f22787436d0fe74f99f298e5c399233f0d247f2ec.json rename to backend/.sqlx/query-8aef4f9d27ec6df07cd671bcf90bf378e9fac4986cd29f69c1f2b8a83ba515c3.json index e103a91c1e..53a9daaf9a 100644 --- a/backend/.sqlx/query-7904ac35748b1de2c7ff764f22787436d0fe74f99f298e5c399233f0d247f2ec.json +++ b/backend/.sqlx/query-8aef4f9d27ec6df07cd671bcf90bf378e9fac4986cd29f69c1f2b8a83ba515c3.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "WITH RECURSIVE chain(id, parent_job) AS (\n SELECT id, parent_job FROM v2_job WHERE id = $1 AND workspace_id = $2\n UNION ALL\n SELECT j.id, j.parent_job FROM v2_job j\n JOIN chain c ON j.id = c.parent_job AND j.workspace_id = $2\n )\n SELECT\n CASE WHEN a.agent THEN regexp_replace(j.runnable_path, '\\.chat$', '')\n ELSE j.runnable_path END AS runnable_path,\n CASE\n WHEN a.agent THEN 'agents'\n WHEN j.kind IN ('script', 'script_hub', 'unassigned_script') THEN 'scripts'\n WHEN j.kind IN ('flow', 'unassigned_flow') THEN 'flows'\n WHEN j.kind IN ('singlestepflow', 'unassigned_singlestepflow') THEN\n CASE WHEN COALESCE(\n (SELECT m->'value'->>'type'\n FROM jsonb_array_elements(j.raw_flow->'modules') m\n WHERE m->>'id' IN ('a', 'main')\n LIMIT 1),\n 'script'\n ) = 'flow' THEN 'flows' ELSE 'scripts' END\n END AS scope_kind,\n CASE WHEN j.trigger_kind = 'app' THEN j.trigger END AS launched_by_app\n FROM v2_job j JOIN chain c ON c.id = j.id,\n LATERAL (SELECT j.kind = 'flowpreview'\n AND j.raw_flow->'modules'->1 IS NULL\n AND j.raw_flow->'modules'->0->>'id' = '__wm_agent_root' AS agent) a\n WHERE j.workspace_id = $2", + "query": "WITH RECURSIVE chain(id, parent_job) AS (\n SELECT id, parent_job FROM v2_job WHERE id = $1 AND workspace_id = $2\n UNION ALL\n SELECT j.id, j.parent_job FROM v2_job j\n JOIN chain c ON j.id = c.parent_job AND j.workspace_id = $2\n )\n SELECT\n CASE WHEN a.agent THEN regexp_replace(j.runnable_path, '\\.chat$', '')\n ELSE j.runnable_path END AS runnable_path,\n CASE\n WHEN a.agent THEN 'agents'\n WHEN j.kind IN ('script', 'script_hub', 'unassigned_script') THEN 'scripts'\n WHEN j.kind IN ('flow', 'unassigned_flow') THEN 'flows'\n WHEN j.kind IN ('dependencies', 'flowdependencies') THEN 'dependencies'\n WHEN j.kind IN ('singlestepflow', 'unassigned_singlestepflow') THEN\n CASE WHEN COALESCE(\n (SELECT m->'value'->>'type'\n FROM jsonb_array_elements(j.raw_flow->'modules') m\n WHERE m->>'id' IN ('a', 'main')\n LIMIT 1),\n 'script'\n ) = 'flow' THEN 'flows' ELSE 'scripts' END\n END AS scope_kind,\n CASE WHEN j.trigger_kind = 'app' THEN j.trigger END AS launched_by_app\n FROM v2_job j JOIN chain c ON c.id = j.id,\n LATERAL (SELECT j.kind = 'flowpreview'\n AND j.raw_flow->'modules'->1 IS NULL\n AND j.raw_flow->'modules'->0->>'id' = '__wm_agent_root' AS agent) a\n WHERE j.workspace_id = $2", "describe": { "columns": [ { @@ -31,5 +31,5 @@ null ] }, - "hash": "7904ac35748b1de2c7ff764f22787436d0fe74f99f298e5c399233f0d247f2ec" + "hash": "8aef4f9d27ec6df07cd671bcf90bf378e9fac4986cd29f69c1f2b8a83ba515c3" } diff --git a/backend/.sqlx/query-8c35d87481de9eb1496d47e78660a57fd10fc5b32f4e68ab7a217d85264623b6.json b/backend/.sqlx/query-8c35d87481de9eb1496d47e78660a57fd10fc5b32f4e68ab7a217d85264623b6.json new file mode 100644 index 0000000000..7e4de24f7e --- /dev/null +++ b/backend/.sqlx/query-8c35d87481de9eb1496d47e78660a57fd10fc5b32f4e68ab7a217d85264623b6.json @@ -0,0 +1,47 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO ai_shared_session\n (workspace_id, session_id, email, created_by, name, is_public, message_count, snapshot)\n VALUES ($1, $2, $3, $4, $5, COALESCE($6, false), $7, $8)\n ON CONFLICT (workspace_id, email, session_id) DO UPDATE\n SET created_by = EXCLUDED.created_by,\n name = EXCLUDED.name,\n is_public = COALESCE($6, ai_shared_session.is_public),\n message_count = EXCLUDED.message_count,\n snapshot = EXCLUDED.snapshot,\n shared_at = now()\n RETURNING id, is_public, shared_at, (xmax = 0) AS \"inserted!\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "is_public", + "type_info": "Bool" + }, + { + "ordinal": 2, + "name": "shared_at", + "type_info": "Timestamptz" + }, + { + "ordinal": 3, + "name": "inserted!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Varchar", + "Varchar", + "Varchar", + "Varchar", + "Varchar", + "Bool", + "Int4", + "Text" + ] + }, + "nullable": [ + false, + false, + false, + null + ] + }, + "hash": "8c35d87481de9eb1496d47e78660a57fd10fc5b32f4e68ab7a217d85264623b6" +} diff --git a/backend/.sqlx/query-8c56f79cb3f940b29a35f31a48f23ea068d451cf4bfd0c3c9b2f957df82173d1.json b/backend/.sqlx/query-8c56f79cb3f940b29a35f31a48f23ea068d451cf4bfd0c3c9b2f957df82173d1.json new file mode 100644 index 0000000000..5c9eca6f51 --- /dev/null +++ b/backend/.sqlx/query-8c56f79cb3f940b29a35f31a48f23ea068d451cf4bfd0c3c9b2f957df82173d1.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT ws.teams_team_id FROM v2_job j\n JOIN workspace_settings ws ON ws.workspace_id = j.workspace_id\n WHERE j.id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "teams_team_id", + "type_info": "Text" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + true + ] + }, + "hash": "8c56f79cb3f940b29a35f31a48f23ea068d451cf4bfd0c3c9b2f957df82173d1" +} diff --git a/backend/.sqlx/query-9212902d4eb2834ab3b429968a7a85c53c49e4ef0f42c146324d5c71fbd1e21d.json b/backend/.sqlx/query-9212902d4eb2834ab3b429968a7a85c53c49e4ef0f42c146324d5c71fbd1e21d.json deleted file mode 100644 index f105dd7825..0000000000 --- a/backend/.sqlx/query-9212902d4eb2834ab3b429968a7a85c53c49e4ef0f42c146324d5c71fbd1e21d.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "WITH deleted AS (\n DELETE FROM v2_job_queue WHERE id = $1\n RETURNING id, workspace_id, started_at, worker, canceled_by, canceled_reason\n ), completed AS (\n INSERT INTO v2_job_completed AS cj\n ( workspace_id\n , id\n , started_at\n , duration_ms\n , result\n , result_columns\n , canceled_by\n , canceled_reason\n , flow_status\n , workflow_as_code_status\n , memory_peak\n , status\n , worker\n )\n SELECT d.workspace_id, d.id, d.started_at,\n COALESCE($9::bigint, (EXTRACT('epoch' FROM (now())) - EXTRACT('epoch' FROM (COALESCE(d.started_at, now()))))*1000),\n $3::text::jsonb, $10,\n CASE WHEN $4::BOOL THEN $5 ELSE d.canceled_by END,\n CASE WHEN $4::BOOL THEN $6 WHEN d.canceled_by IS NOT NULL THEN d.canceled_reason END,\n s.flow_status, s.workflow_as_code_status, $8,\n CASE WHEN $4::BOOL OR d.canceled_by IS NOT NULL THEN 'canceled'::job_status\n WHEN $7::BOOL THEN 'skipped'::job_status\n WHEN $2::BOOL THEN 'success'::job_status\n ELSE 'failure'::job_status END,\n d.worker\n FROM deleted d LEFT JOIN v2_job_status s ON s.id = d.id\n ON CONFLICT (id) DO UPDATE SET status = EXCLUDED.status, result = $3::text::jsonb,\n canceled_by = CASE WHEN NOT $4::BOOL AND EXCLUDED.canceled_by IS NOT NULL\n THEN EXCLUDED.canceled_by ELSE cj.canceled_by END,\n canceled_reason = CASE WHEN NOT $4::BOOL AND EXCLUDED.canceled_by IS NOT NULL\n THEN EXCLUDED.canceled_reason ELSE cj.canceled_reason END\n RETURNING duration_ms\n )\n SELECT duration_ms AS \"duration_ms!\" FROM completed", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "duration_ms!", - "type_info": "Int8" - } - ], - "parameters": { - "Left": [ - "Uuid", - "Bool", - "Text", - "Bool", - "Varchar", - "Text", - "Bool", - "Int4", - "Int8", - "TextArray" - ] - }, - "nullable": [ - false - ] - }, - "hash": "9212902d4eb2834ab3b429968a7a85c53c49e4ef0f42c146324d5c71fbd1e21d" -} diff --git a/backend/.sqlx/query-92b011eda2a652af714b08137b447753bc03ec35f6daa8ca245b1c8ed34c405f.json b/backend/.sqlx/query-92b011eda2a652af714b08137b447753bc03ec35f6daa8ca245b1c8ed34c405f.json deleted file mode 100644 index 794f62e49d..0000000000 --- a/backend/.sqlx/query-92b011eda2a652af714b08137b447753bc03ec35f6daa8ca245b1c8ed34c405f.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "DELETE FROM zombie_job_counter WHERE job_id IN (SELECT id FROM v2_job WHERE workspace_id = $1 AND id = ANY($2))", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Text", - "UuidArray" - ] - }, - "nullable": [] - }, - "hash": "92b011eda2a652af714b08137b447753bc03ec35f6daa8ca245b1c8ed34c405f" -} diff --git a/backend/.sqlx/query-966b065bd6bbbff9e0ca15bee504f9cfe5e3a75427767de41e5b85c797f7d58a.json b/backend/.sqlx/query-966b065bd6bbbff9e0ca15bee504f9cfe5e3a75427767de41e5b85c797f7d58a.json new file mode 100644 index 0000000000..b3a2ea6a05 --- /dev/null +++ b/backend/.sqlx/query-966b065bd6bbbff9e0ca15bee504f9cfe5e3a75427767de41e5b85c797f7d58a.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS (SELECT 1 FROM global_settings WHERE name = $1)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "exists", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "966b065bd6bbbff9e0ca15bee504f9cfe5e3a75427767de41e5b85c797f7d58a" +} diff --git a/backend/.sqlx/query-975158ae72ec12f3f933fba1d9623bf1c925feebe746299cd1f0eda3f8b949d5.json b/backend/.sqlx/query-975158ae72ec12f3f933fba1d9623bf1c925feebe746299cd1f0eda3f8b949d5.json deleted file mode 100644 index 0b166b32a4..0000000000 --- a/backend/.sqlx/query-975158ae72ec12f3f933fba1d9623bf1c925feebe746299cd1f0eda3f8b949d5.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "WITH deleted AS (\n DELETE FROM v2_job_queue WHERE id = $1\n RETURNING id, workspace_id, started_at, worker, canceled_by, canceled_reason\n ), completed AS (\n INSERT INTO v2_job_completed AS cj\n ( workspace_id\n , id\n , started_at\n , duration_ms\n , result\n , result_columns\n , canceled_by\n , canceled_reason\n , flow_status\n , workflow_as_code_status\n , memory_peak\n , status\n , worker\n )\n SELECT d.workspace_id, d.id, d.started_at,\n COALESCE($9::bigint, (EXTRACT('epoch' FROM (now())) - EXTRACT('epoch' FROM (COALESCE(d.started_at, now()))))*1000),\n $3::text::jsonb, $10,\n CASE WHEN $4::BOOL THEN $5 ELSE d.canceled_by END,\n CASE WHEN $4::BOOL THEN $6 WHEN d.canceled_by IS NOT NULL THEN d.canceled_reason END,\n s.flow_status, s.workflow_as_code_status, $8,\n CASE WHEN $4::BOOL OR d.canceled_by IS NOT NULL THEN 'canceled'::job_status\n WHEN $7::BOOL THEN 'skipped'::job_status\n WHEN $2::BOOL THEN 'success'::job_status\n ELSE 'failure'::job_status END,\n d.worker\n FROM deleted d LEFT JOIN v2_job_status s ON s.id = d.id\n ON CONFLICT (id) DO UPDATE SET status = EXCLUDED.status, result = $3::text::jsonb,\n canceled_by = CASE WHEN NOT $4::BOOL AND EXCLUDED.canceled_by IS NOT NULL\n THEN EXCLUDED.canceled_by ELSE cj.canceled_by END,\n canceled_reason = CASE WHEN NOT $4::BOOL AND EXCLUDED.canceled_by IS NOT NULL\n THEN EXCLUDED.canceled_reason ELSE cj.canceled_reason END\n RETURNING duration_ms\n ), parent_ping AS (\n UPDATE v2_job_runtime r SET ping = now()\n FROM v2_job_queue q\n WHERE r.id = $11 AND q.id = r.id AND q.workspace_id = $12\n AND EXISTS (SELECT 1 FROM completed)\n )\n SELECT duration_ms AS \"duration_ms!\" FROM completed", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "duration_ms!", - "type_info": "Int8" - } - ], - "parameters": { - "Left": [ - "Uuid", - "Bool", - "Text", - "Bool", - "Varchar", - "Text", - "Bool", - "Int4", - "Int8", - "TextArray", - "Uuid", - "Text" - ] - }, - "nullable": [ - false - ] - }, - "hash": "975158ae72ec12f3f933fba1d9623bf1c925feebe746299cd1f0eda3f8b949d5" -} diff --git a/backend/.sqlx/query-97d8a9835344b8c72d59afc99d76b681c5120ef29eb09b8626a3fbc43a32cc0e.json b/backend/.sqlx/query-97d8a9835344b8c72d59afc99d76b681c5120ef29eb09b8626a3fbc43a32cc0e.json new file mode 100644 index 0000000000..abf8b56d79 --- /dev/null +++ b/backend/.sqlx/query-97d8a9835344b8c72d59afc99d76b681c5120ef29eb09b8626a3fbc43a32cc0e.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM runnable_job_stats WHERE hour < $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Int8" + ] + }, + "nullable": [] + }, + "hash": "97d8a9835344b8c72d59afc99d76b681c5120ef29eb09b8626a3fbc43a32cc0e" +} diff --git a/backend/.sqlx/query-98aebe8ead7d3f6e84ad88e6d006309b24b658cac3c99d8d0bdb84cdd00c413a.json b/backend/.sqlx/query-98aebe8ead7d3f6e84ad88e6d006309b24b658cac3c99d8d0bdb84cdd00c413a.json new file mode 100644 index 0000000000..f81b66ccb0 --- /dev/null +++ b/backend/.sqlx/query-98aebe8ead7d3f6e84ad88e6d006309b24b658cac3c99d8d0bdb84cdd00c413a.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT large_file_storage, ducklake FROM workspace_settings WHERE workspace_id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "large_file_storage", + "type_info": "Jsonb" + }, + { + "ordinal": 1, + "name": "ducklake", + "type_info": "Jsonb" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + true, + true + ] + }, + "hash": "98aebe8ead7d3f6e84ad88e6d006309b24b658cac3c99d8d0bdb84cdd00c413a" +} diff --git a/backend/.sqlx/query-99e11c04bcc436ec7a75f46365423c85a6e6490c2d9e1dc6ac39112d763f0f75.json b/backend/.sqlx/query-99e11c04bcc436ec7a75f46365423c85a6e6490c2d9e1dc6ac39112d763f0f75.json deleted file mode 100644 index 6fb4205e32..0000000000 --- a/backend/.sqlx/query-99e11c04bcc436ec7a75f46365423c85a6e6490c2d9e1dc6ac39112d763f0f75.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT id FROM app_version WHERE app_id = (SELECT id FROM app WHERE path = $1 AND workspace_id = $2) ORDER BY created_at DESC LIMIT 1", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "id", - "type_info": "Int8" - } - ], - "parameters": { - "Left": [ - "Text", - "Text" - ] - }, - "nullable": [ - false - ] - }, - "hash": "99e11c04bcc436ec7a75f46365423c85a6e6490c2d9e1dc6ac39112d763f0f75" -} diff --git a/backend/.sqlx/query-9e7a5e1ebba42217092971dd340cd9182a4812b14735e502958eaafeb4c6b33d.json b/backend/.sqlx/query-9e7a5e1ebba42217092971dd340cd9182a4812b14735e502958eaafeb4c6b33d.json new file mode 100644 index 0000000000..59ed0e1767 --- /dev/null +++ b/backend/.sqlx/query-9e7a5e1ebba42217092971dd340cd9182a4812b14735e502958eaafeb4c6b33d.json @@ -0,0 +1,17 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE v2_job_queue\n SET suspend = $3, suspend_until = now() + make_interval(secs => $4), started_at = null,\n extras = CASE WHEN started_at IS NULL OR extras ? 'wac_first_started_at' THEN extras\n ELSE jsonb_set(COALESCE(extras, '{}'::jsonb), '{wac_first_started_at}', to_jsonb(started_at))\n END\n WHERE id = $1 AND workspace_id = $2", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Text", + "Int4", + "Float8" + ] + }, + "nullable": [] + }, + "hash": "9e7a5e1ebba42217092971dd340cd9182a4812b14735e502958eaafeb4c6b33d" +} diff --git a/backend/.sqlx/query-9ec675bd675c9915ed56f6cb91ca848b094b61475409156489319cb9d36ef096.json b/backend/.sqlx/query-9ec675bd675c9915ed56f6cb91ca848b094b61475409156489319cb9d36ef096.json new file mode 100644 index 0000000000..bd3f00aa7d --- /dev/null +++ b/backend/.sqlx/query-9ec675bd675c9915ed56f6cb91ca848b094b61475409156489319cb9d36ef096.json @@ -0,0 +1,330 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT\n v2_job_queue.workspace_id,\n v2_job_queue.id,\n v2_job.args as \"args: sqlx::types::Json>>\",\n v2_job.parent_job,\n v2_job.created_by,\n v2_job_queue.started_at,\n v2_job_queue.runnable_settings_handle,\n scheduled_for,\n runnable_path,\n kind as \"kind: JobKind\",\n runnable_id as \"runnable_id: ScriptHash\",\n canceled_reason,\n canceled_by,\n permissioned_as,\n permissioned_as_email,\n flow_status as \"flow_status: sqlx::types::Json>\",\n v2_job.tag,\n script_lang as \"script_lang: ScriptLang\",\n same_worker,\n pre_run_error,\n concurrent_limit,\n concurrency_time_window_s,\n flow_innermost_root_job,\n root_job,\n timeout,\n flow_step_id,\n cache_ttl,\n cache_ignore_s3_path,\n v2_job_queue.priority,\n preprocessed,\n script_entrypoint_override,\n trigger,\n trigger_kind as \"trigger_kind: TriggerKindLabel\",\n visible_to_owner,\n NULL as permissioned_as_end_user_email,\n NULL::boolean as viewer_data_access,\n job_perms.job_token_scopes\n FROM v2_job_queue INNER JOIN v2_job ON v2_job.id = v2_job_queue.id LEFT JOIN v2_job_status ON v2_job_status.id = v2_job_queue.id\n LEFT JOIN job_perms ON job_perms.job_id = v2_job_queue.id WHERE v2_job_queue.id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "workspace_id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 2, + "name": "args: sqlx::types::Json>>", + "type_info": "Jsonb" + }, + { + "ordinal": 3, + "name": "parent_job", + "type_info": "Uuid" + }, + { + "ordinal": 4, + "name": "created_by", + "type_info": "Varchar" + }, + { + "ordinal": 5, + "name": "started_at", + "type_info": "Timestamptz" + }, + { + "ordinal": 6, + "name": "runnable_settings_handle", + "type_info": "Int8" + }, + { + "ordinal": 7, + "name": "scheduled_for", + "type_info": "Timestamptz" + }, + { + "ordinal": 8, + "name": "runnable_path", + "type_info": "Varchar" + }, + { + "ordinal": 9, + "name": "kind: JobKind", + "type_info": { + "Custom": { + "name": "job_kind", + "kind": { + "Enum": [ + "script", + "preview", + "flow", + "dependencies", + "flowpreview", + "script_hub", + "identity", + "flowdependencies", + "http", + "graphql", + "postgresql", + "noop", + "appdependencies", + "deploymentcallback", + "singlestepflow", + "flowscript", + "flownode", + "appscript", + "aiagent", + "unassigned_script", + "unassigned_flow", + "unassigned_singlestepflow" + ] + } + } + } + }, + { + "ordinal": 10, + "name": "runnable_id: ScriptHash", + "type_info": "Int8" + }, + { + "ordinal": 11, + "name": "canceled_reason", + "type_info": "Text" + }, + { + "ordinal": 12, + "name": "canceled_by", + "type_info": "Varchar" + }, + { + "ordinal": 13, + "name": "permissioned_as", + "type_info": "Varchar" + }, + { + "ordinal": 14, + "name": "permissioned_as_email", + "type_info": "Varchar" + }, + { + "ordinal": 15, + "name": "flow_status: sqlx::types::Json>", + "type_info": "Jsonb" + }, + { + "ordinal": 16, + "name": "tag", + "type_info": "Varchar" + }, + { + "ordinal": 17, + "name": "script_lang: ScriptLang", + "type_info": { + "Custom": { + "name": "script_lang", + "kind": { + "Enum": [ + "python3", + "deno", + "go", + "bash", + "postgresql", + "nativets", + "bun", + "mysql", + "bigquery", + "snowflake", + "graphql", + "powershell", + "mssql", + "php", + "bunnative", + "rust", + "ansible", + "csharp", + "oracledb", + "nu", + "java", + "duckdb", + "ruby", + "rlang", + "dbt" + ] + } + } + } + }, + { + "ordinal": 18, + "name": "same_worker", + "type_info": "Bool" + }, + { + "ordinal": 19, + "name": "pre_run_error", + "type_info": "Text" + }, + { + "ordinal": 20, + "name": "concurrent_limit", + "type_info": "Int4" + }, + { + "ordinal": 21, + "name": "concurrency_time_window_s", + "type_info": "Int4" + }, + { + "ordinal": 22, + "name": "flow_innermost_root_job", + "type_info": "Uuid" + }, + { + "ordinal": 23, + "name": "root_job", + "type_info": "Uuid" + }, + { + "ordinal": 24, + "name": "timeout", + "type_info": "Int4" + }, + { + "ordinal": 25, + "name": "flow_step_id", + "type_info": "Varchar" + }, + { + "ordinal": 26, + "name": "cache_ttl", + "type_info": "Int4" + }, + { + "ordinal": 27, + "name": "cache_ignore_s3_path", + "type_info": "Bool" + }, + { + "ordinal": 28, + "name": "priority", + "type_info": "Int2" + }, + { + "ordinal": 29, + "name": "preprocessed", + "type_info": "Bool" + }, + { + "ordinal": 30, + "name": "script_entrypoint_override", + "type_info": "Varchar" + }, + { + "ordinal": 31, + "name": "trigger", + "type_info": "Varchar" + }, + { + "ordinal": 32, + "name": "trigger_kind: TriggerKindLabel", + "type_info": { + "Custom": { + "name": "job_trigger_kind", + "kind": { + "Enum": [ + "webhook", + "http", + "websocket", + "kafka", + "email", + "nats", + "schedule", + "app", + "ui", + "postgres", + "sqs", + "gcp", + "mqtt", + "nextcloud", + "google", + "ci_test", + "github", + "azure", + "asset", + "freshness", + "amqp" + ] + } + } + } + }, + { + "ordinal": 33, + "name": "visible_to_owner", + "type_info": "Bool" + }, + { + "ordinal": 34, + "name": "permissioned_as_end_user_email", + "type_info": "Text" + }, + { + "ordinal": 35, + "name": "viewer_data_access", + "type_info": "Bool" + }, + { + "ordinal": 36, + "name": "job_token_scopes", + "type_info": "TextArray" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + false, + false, + true, + true, + false, + true, + true, + false, + true, + false, + true, + true, + true, + false, + false, + true, + false, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + null, + null, + true + ] + }, + "hash": "9ec675bd675c9915ed56f6cb91ca848b094b61475409156489319cb9d36ef096" +} diff --git a/backend/.sqlx/query-9f6bb810ebe383c848d8256f594fe701ee064dd9c880ad4df89ec47279aff7de.json b/backend/.sqlx/query-9f6bb810ebe383c848d8256f594fe701ee064dd9c880ad4df89ec47279aff7de.json new file mode 100644 index 0000000000..6caeda5fc2 --- /dev/null +++ b/backend/.sqlx/query-9f6bb810ebe383c848d8256f594fe701ee064dd9c880ad4df89ec47279aff7de.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO app_version_lite (id, value)\n SELECT * FROM UNNEST($1::bigint[], $2::jsonb[])\n ON CONFLICT (id) DO NOTHING", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Int8Array", + "JsonbArray" + ] + }, + "nullable": [] + }, + "hash": "9f6bb810ebe383c848d8256f594fe701ee064dd9c880ad4df89ec47279aff7de" +} diff --git a/backend/.sqlx/query-a2f6ca89faaa8d8739f67cd1aae571de793b377dd6058065f51b12c974e5b665.json b/backend/.sqlx/query-a2f6ca89faaa8d8739f67cd1aae571de793b377dd6058065f51b12c974e5b665.json deleted file mode 100644 index 2358af807f..0000000000 --- a/backend/.sqlx/query-a2f6ca89faaa8d8739f67cd1aae571de793b377dd6058065f51b12c974e5b665.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n SELECT usr.email, usage.executions\n FROM usr, LATERAL (\n SELECT COALESCE(SUM(c.duration_ms + 1000)/1000 , 0)::BIGINT executions\n FROM v2_job_completed c JOIN v2_job j USING (id)\n WHERE j.workspace_id = $1\n AND j.kind NOT IN ('flow', 'flowpreview', 'flownode', 'singlestepflow')\n AND j.permissioned_as_email = usr.email\n AND now() - '1 week'::interval < j.created_at\n ) usage\n WHERE workspace_id = $1\n ", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "email", - "type_info": "Varchar" - }, - { - "ordinal": 1, - "name": "executions", - "type_info": "Int8" - } - ], - "parameters": { - "Left": [ - "Text" - ] - }, - "nullable": [ - false, - null - ] - }, - "hash": "a2f6ca89faaa8d8739f67cd1aae571de793b377dd6058065f51b12c974e5b665" -} diff --git a/backend/.sqlx/query-a352fd2f8a2d57e499b975115ba14afc75b7794b2a172b6bee519597b0e2cf69.json b/backend/.sqlx/query-a352fd2f8a2d57e499b975115ba14afc75b7794b2a172b6bee519597b0e2cf69.json new file mode 100644 index 0000000000..88026d0fed --- /dev/null +++ b/backend/.sqlx/query-a352fd2f8a2d57e499b975115ba14afc75b7794b2a172b6bee519597b0e2cf69.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT versions[array_upper(versions, 1)] FROM app WHERE path = $1 AND workspace_id = $2 FOR NO KEY UPDATE", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "versions", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "a352fd2f8a2d57e499b975115ba14afc75b7794b2a172b6bee519597b0e2cf69" +} diff --git a/backend/.sqlx/query-34979901e417b6eef8bda80f6213db46e3e68ee3d756c2540d924831879ce9e9.json b/backend/.sqlx/query-a3582b2b9089d85d8fa273aed5348394cb91064948c1c3fbb21f9461b9869af0.json similarity index 59% rename from backend/.sqlx/query-34979901e417b6eef8bda80f6213db46e3e68ee3d756c2540d924831879ce9e9.json rename to backend/.sqlx/query-a3582b2b9089d85d8fa273aed5348394cb91064948c1c3fbb21f9461b9869af0.json index 07fa5c2adf..2abbc1a8a3 100644 --- a/backend/.sqlx/query-34979901e417b6eef8bda80f6213db46e3e68ee3d756c2540d924831879ce9e9.json +++ b/backend/.sqlx/query-a3582b2b9089d85d8fa273aed5348394cb91064948c1c3fbb21f9461b9869af0.json @@ -1,32 +1,42 @@ { "db_name": "PostgreSQL", - "query": "SELECT app, hash, lock, code, code_sha256\n FROM app_script\n WHERE app = ANY(SELECT id FROM app WHERE workspace_id = $1)", + "query": "SELECT id, app, hash, lock, code, code_sha256, modules\n FROM app_script\n WHERE app = ANY(SELECT id FROM app WHERE workspace_id = $1)", "describe": { "columns": [ { "ordinal": 0, - "name": "app", + "name": "id", "type_info": "Int8" }, { "ordinal": 1, + "name": "app", + "type_info": "Int8" + }, + { + "ordinal": 2, "name": "hash", "type_info": "Bpchar" }, { - "ordinal": 2, + "ordinal": 3, "name": "lock", "type_info": "Text" }, { - "ordinal": 3, + "ordinal": 4, "name": "code", "type_info": "Text" }, { - "ordinal": 4, + "ordinal": 5, "name": "code_sha256", "type_info": "Bpchar" + }, + { + "ordinal": 6, + "name": "modules", + "type_info": "Jsonb" } ], "parameters": { @@ -35,12 +45,14 @@ ] }, "nullable": [ + false, false, false, true, false, - false + false, + true ] }, - "hash": "34979901e417b6eef8bda80f6213db46e3e68ee3d756c2540d924831879ce9e9" + "hash": "a3582b2b9089d85d8fa273aed5348394cb91064948c1c3fbb21f9461b9869af0" } diff --git a/backend/.sqlx/query-a37dec4e86f537880d45da01ce872ae5b7858a087cb4eb5869573fff69c1c6b9.json b/backend/.sqlx/query-a37dec4e86f537880d45da01ce872ae5b7858a087cb4eb5869573fff69c1c6b9.json new file mode 100644 index 0000000000..7733ad9fa5 --- /dev/null +++ b/backend/.sqlx/query-a37dec4e86f537880d45da01ce872ae5b7858a087cb4eb5869573fff69c1c6b9.json @@ -0,0 +1,35 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT c.id AS \"id!\", ws.large_file_storage,\n EXISTS (SELECT 1 FROM fork_storage_namespace f\n WHERE f.workspace_id = c.id AND f.storage = $2) AS \"isolated!\"\n FROM unnest($1::text[]) WITH ORDINALITY AS c(id, ord)\n LEFT JOIN workspace_settings ws ON ws.workspace_id = c.id\n ORDER BY c.ord", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id!", + "type_info": "Text" + }, + { + "ordinal": 1, + "name": "large_file_storage", + "type_info": "Jsonb" + }, + { + "ordinal": 2, + "name": "isolated!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "TextArray", + "Text" + ] + }, + "nullable": [ + null, + true, + null + ] + }, + "hash": "a37dec4e86f537880d45da01ce872ae5b7858a087cb4eb5869573fff69c1c6b9" +} diff --git a/backend/.sqlx/query-a93bc7945ec8344a9eb6dc8c1bbb8ef161a9b7342c6699df8263df404153346a.json b/backend/.sqlx/query-a93bc7945ec8344a9eb6dc8c1bbb8ef161a9b7342c6699df8263df404153346a.json new file mode 100644 index 0000000000..883805160b --- /dev/null +++ b/backend/.sqlx/query-a93bc7945ec8344a9eb6dc8c1bbb8ef161a9b7342c6699df8263df404153346a.json @@ -0,0 +1,58 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT\n flow_step_id,\n flow_innermost_root_job as flow_scope,\n (flow_status->'step')::integer as step,\n jsonb_array_length(flow_status->'modules') as len,\n runnable_path ~ '/branchone-\\d+$' as is_branch_one,\n runnable_path ~ '/branch(one|all)-\\d+$' as is_branch,\n parent_job as next_parent\n FROM v2_job\n LEFT JOIN v2_job_status USING (id)\n WHERE v2_job.id = $1", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "flow_step_id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "flow_scope", + "type_info": "Uuid" + }, + { + "ordinal": 2, + "name": "step", + "type_info": "Int4" + }, + { + "ordinal": 3, + "name": "len", + "type_info": "Int4" + }, + { + "ordinal": 4, + "name": "is_branch_one", + "type_info": "Bool" + }, + { + "ordinal": 5, + "name": "is_branch", + "type_info": "Bool" + }, + { + "ordinal": 6, + "name": "next_parent", + "type_info": "Uuid" + } + ], + "parameters": { + "Left": [ + "Uuid" + ] + }, + "nullable": [ + true, + true, + null, + null, + null, + null, + true + ] + }, + "hash": "a93bc7945ec8344a9eb6dc8c1bbb8ef161a9b7342c6699df8263df404153346a" +} diff --git a/backend/.sqlx/query-2e589e039986e7a2c75e328868874669b32cbe0dae6822b2d2fad0635c5f6087.json b/backend/.sqlx/query-ae695dce1a5740aa2b0283bc80dea6f924cc4246bce4ac13e8256a96085bcce1.json similarity index 68% rename from backend/.sqlx/query-2e589e039986e7a2c75e328868874669b32cbe0dae6822b2d2fad0635c5f6087.json rename to backend/.sqlx/query-ae695dce1a5740aa2b0283bc80dea6f924cc4246bce4ac13e8256a96085bcce1.json index 6ba559e644..8edb183166 100644 --- a/backend/.sqlx/query-2e589e039986e7a2c75e328868874669b32cbe0dae6822b2d2fad0635c5f6087.json +++ b/backend/.sqlx/query-ae695dce1a5740aa2b0283bc80dea6f924cc4246bce4ac13e8256a96085bcce1.json @@ -1,15 +1,16 @@ { "db_name": "PostgreSQL", - "query": "\n UPDATE v2_job_status\n SET flow_status = jsonb_set(flow_status, array['stream_job'], to_jsonb($1::UUID::TEXT))\n WHERE id = $2", + "query": "\n UPDATE v2_job_status\n SET flow_status = jsonb_set(flow_status, array['stream_job'], to_jsonb($1::UUID::TEXT))\n WHERE id = $2 AND NOT COALESCE(flow_leaf_jobs ? $3, false)", "describe": { "columns": [], "parameters": { "Left": [ "Uuid", - "Uuid" + "Uuid", + "Text" ] }, "nullable": [] }, - "hash": "2e589e039986e7a2c75e328868874669b32cbe0dae6822b2d2fad0635c5f6087" + "hash": "ae695dce1a5740aa2b0283bc80dea6f924cc4246bce4ac13e8256a96085bcce1" } diff --git a/backend/.sqlx/query-afb0762c88d9232b79090f2e5966e78437a5e4d3b5e2341ec5f7725a28870270.json b/backend/.sqlx/query-afb0762c88d9232b79090f2e5966e78437a5e4d3b5e2341ec5f7725a28870270.json deleted file mode 100644 index b492b38f49..0000000000 --- a/backend/.sqlx/query-afb0762c88d9232b79090f2e5966e78437a5e4d3b5e2341ec5f7725a28870270.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "UPDATE app SET versions = array_append(versions, $1::bigint) WHERE path = $2 AND workspace_id = $3 AND versions[array_upper(versions, 1)] = $1::bigint", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Int8", - "Text", - "Text" - ] - }, - "nullable": [] - }, - "hash": "afb0762c88d9232b79090f2e5966e78437a5e4d3b5e2341ec5f7725a28870270" -} diff --git a/backend/.sqlx/query-b159cc3ab6fddcfb561c90d20bee2ff605a1c3721a4cbcc080f98fbb87277c37.json b/backend/.sqlx/query-b159cc3ab6fddcfb561c90d20bee2ff605a1c3721a4cbcc080f98fbb87277c37.json new file mode 100644 index 0000000000..d65f75636d --- /dev/null +++ b/backend/.sqlx/query-b159cc3ab6fddcfb561c90d20bee2ff605a1c3721a4cbcc080f98fbb87277c37.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS(SELECT 1 FROM script WHERE workspace_id = $1 AND hash = $2)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "exists", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Int8" + ] + }, + "nullable": [ + null + ] + }, + "hash": "b159cc3ab6fddcfb561c90d20bee2ff605a1c3721a4cbcc080f98fbb87277c37" +} diff --git a/backend/.sqlx/query-ba0c3dad5d2a77922821c9c6d58e06a65e6666e197f3e59b880470df35c27bec.json b/backend/.sqlx/query-ba0c3dad5d2a77922821c9c6d58e06a65e6666e197f3e59b880470df35c27bec.json deleted file mode 100644 index 7c4fe34428..0000000000 --- a/backend/.sqlx/query-ba0c3dad5d2a77922821c9c6d58e06a65e6666e197f3e59b880470df35c27bec.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n INSERT INTO group_ (workspace_id, name, summary, extra_perms)\n VALUES ('test-workspace', 'error_handler', 'Error handler group', '{\"u/test-user\": true}')\n ON CONFLICT DO NOTHING\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [] - }, - "nullable": [] - }, - "hash": "ba0c3dad5d2a77922821c9c6d58e06a65e6666e197f3e59b880470df35c27bec" -} diff --git a/backend/.sqlx/query-bb4cde84157126f29680cb36075848e7cde2ab7c6b7f0861becd4c0b8c330a8d.json b/backend/.sqlx/query-bb4cde84157126f29680cb36075848e7cde2ab7c6b7f0861becd4c0b8c330a8d.json deleted file mode 100644 index 4c4e0b71a4..0000000000 --- a/backend/.sqlx/query-bb4cde84157126f29680cb36075848e7cde2ab7c6b7f0861becd4c0b8c330a8d.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n UPDATE workspace_settings\n SET error_handler = '{\"path\": \"script/f/test/error_handler\"}'::jsonb\n WHERE workspace_id = 'test-workspace'\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [] - }, - "nullable": [] - }, - "hash": "bb4cde84157126f29680cb36075848e7cde2ab7c6b7f0861becd4c0b8c330a8d" -} diff --git a/backend/.sqlx/query-bdc39bdd63c38217834a0c0d858f6db33d63ff7bf55329452dc84dae2560c23e.json b/backend/.sqlx/query-bdc39bdd63c38217834a0c0d858f6db33d63ff7bf55329452dc84dae2560c23e.json new file mode 100644 index 0000000000..cb595ad5b3 --- /dev/null +++ b/backend/.sqlx/query-bdc39bdd63c38217834a0c0d858f6db33d63ff7bf55329452dc84dae2560c23e.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT EXISTS (SELECT 1 FROM workspace WHERE id = $1)", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "exists", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "bdc39bdd63c38217834a0c0d858f6db33d63ff7bf55329452dc84dae2560c23e" +} diff --git a/backend/.sqlx/query-bf763c3ae4951537033d18ce48d3eb83d5c19e32aef199bf161e8ba8d1adf176.json b/backend/.sqlx/query-bf763c3ae4951537033d18ce48d3eb83d5c19e32aef199bf161e8ba8d1adf176.json new file mode 100644 index 0000000000..d6b261b56c --- /dev/null +++ b/backend/.sqlx/query-bf763c3ae4951537033d18ce48d3eb83d5c19e32aef199bf161e8ba8d1adf176.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO resource (workspace_id, path, value, description, resource_type, extra_perms, edited_at, created_by)\n SELECT $2, path,\n CASE WHEN $3::text IS NOT NULL AND resource_type = 'ai_agent'\n AND jsonb_typeof(value) = 'object' AND value ? 'on_behalf_of'\n THEN jsonb_set(value, '{on_behalf_of}', to_jsonb($3::text))\n ELSE value END,\n description, resource_type, extra_perms, edited_at, created_by\n FROM resource\n WHERE workspace_id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Varchar", + "Text" + ] + }, + "nullable": [] + }, + "hash": "bf763c3ae4951537033d18ce48d3eb83d5c19e32aef199bf161e8ba8d1adf176" +} diff --git a/backend/.sqlx/query-c2f271bcea1f11b2979152cc743559236fd875192b7b7f4824c63675fdc6a551.json b/backend/.sqlx/query-c2f271bcea1f11b2979152cc743559236fd875192b7b7f4824c63675fdc6a551.json deleted file mode 100644 index c621e4b903..0000000000 --- a/backend/.sqlx/query-c2f271bcea1f11b2979152cc743559236fd875192b7b7f4824c63675fdc6a551.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n UPDATE workspace_settings\n SET success_handler = '{\"path\": \"flow/f/test/success_flow\"}'::jsonb\n WHERE workspace_id = 'test-workspace'\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [] - }, - "nullable": [] - }, - "hash": "c2f271bcea1f11b2979152cc743559236fd875192b7b7f4824c63675fdc6a551" -} diff --git a/backend/.sqlx/query-c37f34ea3603af1496825ec54a3415fe710c5fbbc7380c5088c7069fa2caf990.json b/backend/.sqlx/query-c37f34ea3603af1496825ec54a3415fe710c5fbbc7380c5088c7069fa2caf990.json new file mode 100644 index 0000000000..bb82fbf97e --- /dev/null +++ b/backend/.sqlx/query-c37f34ea3603af1496825ec54a3415fe710c5fbbc7380c5088c7069fa2caf990.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM fork_storage_namespace WHERE workspace_id = $1 AND storage = $2", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [] + }, + "hash": "c37f34ea3603af1496825ec54a3415fe710c5fbbc7380c5088c7069fa2caf990" +} diff --git a/backend/.sqlx/query-c3bfc89762258b83bf7494ea40e097cb3bd140e3986780d35706584a368ea215.json b/backend/.sqlx/query-c3bfc89762258b83bf7494ea40e097cb3bd140e3986780d35706584a368ea215.json new file mode 100644 index 0000000000..52dffb5a4c --- /dev/null +++ b/backend/.sqlx/query-c3bfc89762258b83bf7494ea40e097cb3bd140e3986780d35706584a368ea215.json @@ -0,0 +1,22 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT value FROM app_version WHERE id = $1 FOR NO KEY UPDATE", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "value", + "type_info": "Json" + } + ], + "parameters": { + "Left": [ + "Int8" + ] + }, + "nullable": [ + false + ] + }, + "hash": "c3bfc89762258b83bf7494ea40e097cb3bd140e3986780d35706584a368ea215" +} diff --git a/backend/.sqlx/query-c3c51c3536eaa6a5e702d306344db63d19f1c9ab0366e01c0092aa653ab51877.json b/backend/.sqlx/query-c3c51c3536eaa6a5e702d306344db63d19f1c9ab0366e01c0092aa653ab51877.json new file mode 100644 index 0000000000..be4fbb73c9 --- /dev/null +++ b/backend/.sqlx/query-c3c51c3536eaa6a5e702d306344db63d19f1c9ab0366e01c0092aa653ab51877.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM token WHERE email = $1 AND label = 'session' AND token_hash != $2", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [] + }, + "hash": "c3c51c3536eaa6a5e702d306344db63d19f1c9ab0366e01c0092aa653ab51877" +} diff --git a/backend/.sqlx/query-c5971326bdbfaa7dff74689d1365db4f26c41fa56b326dbd02e604c793a13477.json b/backend/.sqlx/query-c5971326bdbfaa7dff74689d1365db4f26c41fa56b326dbd02e604c793a13477.json new file mode 100644 index 0000000000..d84578d37c --- /dev/null +++ b/backend/.sqlx/query-c5971326bdbfaa7dff74689d1365db4f26c41fa56b326dbd02e604c793a13477.json @@ -0,0 +1,74 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT workspace_id, runnable_path, worker_group,\n SUM(job_count)::bigint AS \"job_count!\",\n SUM(total_duration_ms)::bigint AS \"total_duration_ms!\",\n MAX(max_memory_peak) AS \"max_memory_peak!\",\n SUM(sum_memory_peak)::bigint AS \"sum_memory_peak!\",\n SUM(memory_sample_count)::bigint AS \"memory_sample_count!\",\n SUM(total_cpu_ms)::bigint AS \"total_cpu_ms!\"\n FROM runnable_job_stats\n WHERE hour >= $1\n AND ($2::text IS NULL OR worker_group = $2)\n AND ($3::text IS NULL OR workspace_id = $3)\n GROUP BY workspace_id, runnable_path, worker_group\n ORDER BY CASE $4::text\n WHEN 'max_memory' THEN MAX(max_memory_peak)::numeric\n WHEN 'cpu' THEN SUM(total_cpu_ms)\n ELSE SUM(total_duration_ms)\n END DESC, workspace_id, runnable_path, worker_group\n LIMIT $5\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "workspace_id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "runnable_path", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "worker_group", + "type_info": "Text" + }, + { + "ordinal": 3, + "name": "job_count!", + "type_info": "Int8" + }, + { + "ordinal": 4, + "name": "total_duration_ms!", + "type_info": "Int8" + }, + { + "ordinal": 5, + "name": "max_memory_peak!", + "type_info": "Int4" + }, + { + "ordinal": 6, + "name": "sum_memory_peak!", + "type_info": "Int8" + }, + { + "ordinal": 7, + "name": "memory_sample_count!", + "type_info": "Int8" + }, + { + "ordinal": 8, + "name": "total_cpu_ms!", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [ + "Int8", + "Text", + "Text", + "Text", + "Int8" + ] + }, + "nullable": [ + false, + false, + false, + null, + null, + null, + null, + null, + null + ] + }, + "hash": "c5971326bdbfaa7dff74689d1365db4f26c41fa56b326dbd02e604c793a13477" +} diff --git a/backend/.sqlx/query-c748617e060bc41b5922df4b433f20b6971b993e0671b6ccb45db5ef028550bc.json b/backend/.sqlx/query-c748617e060bc41b5922df4b433f20b6971b993e0671b6ccb45db5ef028550bc.json deleted file mode 100644 index 7f6fe7a81c..0000000000 --- a/backend/.sqlx/query-c748617e060bc41b5922df4b433f20b6971b993e0671b6ccb45db5ef028550bc.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "INSERT INTO worker_ping (worker_instance, worker, ip, custom_tags, worker_group, dedicated_worker, dedicated_workers, wm_version, vcpus, memory, job_isolation, native_mode) VALUES ($1, $2, COALESCE($3, 'NO IP'), $4, $5, $6, $7, $8, $9, $10, $11, $12) ON CONFLICT (worker)\n DO UPDATE set ping_at = now(), worker_instance = EXCLUDED.worker_instance, ip = COALESCE($3, worker_ping.ip), custom_tags = EXCLUDED.custom_tags, worker_group = EXCLUDED.worker_group, dedicated_worker = EXCLUDED.dedicated_worker, dedicated_workers = EXCLUDED.dedicated_workers, wm_version = EXCLUDED.wm_version, vcpus = COALESCE(EXCLUDED.vcpus, worker_ping.vcpus), memory = COALESCE(EXCLUDED.memory, worker_ping.memory), job_isolation = EXCLUDED.job_isolation, native_mode = EXCLUDED.native_mode, current_job_id = NULL, current_job_workspace_id = NULL\n RETURNING jobs_executed", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "jobs_executed", - "type_info": "Int4" - } - ], - "parameters": { - "Left": [ - "Varchar", - "Varchar", - "Text", - "TextArray", - "Varchar", - "Varchar", - "TextArray", - "Varchar", - "Int8", - "Int8", - "Text", - "Bool" - ] - }, - "nullable": [ - false - ] - }, - "hash": "c748617e060bc41b5922df4b433f20b6971b993e0671b6ccb45db5ef028550bc" -} diff --git a/backend/.sqlx/query-0c6c80746733be8f561ab0b631854799f5e8122adaf35465cb16c3dc795bdc3b.json b/backend/.sqlx/query-c798432108de19ed28dcf1810c68c838beaa5dfa5e3bcfcfeddee252ffe1334e.json similarity index 55% rename from backend/.sqlx/query-0c6c80746733be8f561ab0b631854799f5e8122adaf35465cb16c3dc795bdc3b.json rename to backend/.sqlx/query-c798432108de19ed28dcf1810c68c838beaa5dfa5e3bcfcfeddee252ffe1334e.json index efe58b7a16..9779b00977 100644 --- a/backend/.sqlx/query-0c6c80746733be8f561ab0b631854799f5e8122adaf35465cb16c3dc795bdc3b.json +++ b/backend/.sqlx/query-c798432108de19ed28dcf1810c68c838beaa5dfa5e3bcfcfeddee252ffe1334e.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "\n INSERT INTO app_script (app, hash, lock, code, code_sha256)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT (hash) DO UPDATE SET app = EXCLUDED.app -- trivial update to return the id\n RETURNING id\n ", + "query": "\n INSERT INTO app_script (app, hash, lock, code, code_sha256, modules)\n VALUES ($1, $2, $3, $4, $5, $6)\n ON CONFLICT (hash) DO UPDATE SET app = EXCLUDED.app -- trivial update to return the id\n RETURNING id\n ", "describe": { "columns": [ { @@ -15,12 +15,13 @@ "Bpchar", "Text", "Text", - "Bpchar" + "Bpchar", + "Jsonb" ] }, "nullable": [ false ] }, - "hash": "0c6c80746733be8f561ab0b631854799f5e8122adaf35465cb16c3dc795bdc3b" + "hash": "c798432108de19ed28dcf1810c68c838beaa5dfa5e3bcfcfeddee252ffe1334e" } diff --git a/backend/.sqlx/query-c8e3e103645e0428d4b784f200595309a55635083a541745552c397a36ac08c4.json b/backend/.sqlx/query-c8e3e103645e0428d4b784f200595309a55635083a541745552c397a36ac08c4.json new file mode 100644 index 0000000000..e66cfa2881 --- /dev/null +++ b/backend/.sqlx/query-c8e3e103645e0428d4b784f200595309a55635083a541745552c397a36ac08c4.json @@ -0,0 +1,54 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT id, name, is_public, message_count, created_by, shared_at FROM ai_shared_session\n WHERE workspace_id = $1 AND email = $2 AND session_id = $3", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "name", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "is_public", + "type_info": "Bool" + }, + { + "ordinal": 3, + "name": "message_count", + "type_info": "Int4" + }, + { + "ordinal": 4, + "name": "created_by", + "type_info": "Varchar" + }, + { + "ordinal": 5, + "name": "shared_at", + "type_info": "Timestamptz" + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "Text" + ] + }, + "nullable": [ + false, + false, + false, + false, + false, + false + ] + }, + "hash": "c8e3e103645e0428d4b784f200595309a55635083a541745552c397a36ac08c4" +} diff --git a/backend/.sqlx/query-ca15fe5d43f0e94f50408efe5c9e359770b759e8661687b4503c4b692ecd245e.json b/backend/.sqlx/query-ca15fe5d43f0e94f50408efe5c9e359770b759e8661687b4503c4b692ecd245e.json new file mode 100644 index 0000000000..6812bfdfc7 --- /dev/null +++ b/backend/.sqlx/query-ca15fe5d43f0e94f50408efe5c9e359770b759e8661687b4503c4b692ecd245e.json @@ -0,0 +1,23 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT versions[array_upper(versions, 1)] FROM app WHERE path = $1 AND workspace_id = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "versions", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [ + "Text", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "ca15fe5d43f0e94f50408efe5c9e359770b759e8661687b4503c4b692ecd245e" +} diff --git a/backend/.sqlx/query-cb421ceb68ab798bde4192a8da9a133ea859f243f518197cde803ef0c86eab33.json b/backend/.sqlx/query-cb421ceb68ab798bde4192a8da9a133ea859f243f518197cde803ef0c86eab33.json new file mode 100644 index 0000000000..73fbc88289 --- /dev/null +++ b/backend/.sqlx/query-cb421ceb68ab798bde4192a8da9a133ea859f243f518197cde803ef0c86eab33.json @@ -0,0 +1,25 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM ai_shared_session\n WHERE workspace_id = $1 AND id = $2 AND (email = $3 OR $4::bool)\n RETURNING name", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "name", + "type_info": "Varchar" + } + ], + "parameters": { + "Left": [ + "Text", + "Uuid", + "Text", + "Bool" + ] + }, + "nullable": [ + false + ] + }, + "hash": "cb421ceb68ab798bde4192a8da9a133ea859f243f518197cde803ef0c86eab33" +} diff --git a/backend/.sqlx/query-cdc594b30855e9384481f561b2c16200d4e6dacb1eb274513c8f1795235dfe20.json b/backend/.sqlx/query-cdc594b30855e9384481f561b2c16200d4e6dacb1eb274513c8f1795235dfe20.json deleted file mode 100644 index a68e5f1253..0000000000 --- a/backend/.sqlx/query-cdc594b30855e9384481f561b2c16200d4e6dacb1eb274513c8f1795235dfe20.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock)\n VALUES ('test-workspace', 5555555555, 'f/test/error_handler', 'export function main() { return \"handled\"; }', 'deno', 'script', 'test-user', '{}', '', '', '')\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [] - }, - "nullable": [] - }, - "hash": "cdc594b30855e9384481f561b2c16200d4e6dacb1eb274513c8f1795235dfe20" -} diff --git a/backend/.sqlx/query-ce39fd9650500b16f7247c8173a40c7e5d2d8a51aea2d36f2bc8c6f86d53a9b8.json b/backend/.sqlx/query-ce39fd9650500b16f7247c8173a40c7e5d2d8a51aea2d36f2bc8c6f86d53a9b8.json new file mode 100644 index 0000000000..ba7a89ef73 --- /dev/null +++ b/backend/.sqlx/query-ce39fd9650500b16f7247c8173a40c7e5d2d8a51aea2d36f2bc8c6f86d53a9b8.json @@ -0,0 +1,43 @@ +{ + "db_name": "PostgreSQL", + "query": "WITH deleted AS (\n DELETE FROM v2_job_queue WHERE id = $1\n RETURNING id, workspace_id, started_at, worker, canceled_by, canceled_reason,\n (extras->>'wac_first_started_at')::timestamptz AS first_started_at,\n COALESCE($9::bigint, (EXTRACT('epoch' FROM (now())) - EXTRACT('epoch' FROM (COALESCE(started_at, now()))))*1000)::bigint AS run_ms\n ), completed AS (\n INSERT INTO v2_job_completed AS cj\n ( workspace_id\n , id\n , started_at\n , duration_ms\n , extras\n , result\n , result_columns\n , canceled_by\n , canceled_reason\n , flow_status\n , workflow_as_code_status\n , memory_peak\n , status\n , worker\n )\n SELECT d.workspace_id, d.id, COALESCE(d.first_started_at, d.started_at),\n CASE WHEN d.first_started_at IS NULL THEN d.run_ms\n ELSE EXTRACT('epoch' FROM (now() - d.first_started_at))*1000 END,\n CASE WHEN d.first_started_at IS NOT NULL\n THEN jsonb_build_object('wac_last_segment_ms', d.run_ms) END,\n $3::text::jsonb, $10,\n CASE WHEN $4::BOOL THEN $5 ELSE d.canceled_by END,\n CASE WHEN $4::BOOL THEN $6 WHEN d.canceled_by IS NOT NULL THEN d.canceled_reason END,\n s.flow_status, s.workflow_as_code_status, $8,\n CASE WHEN $4::BOOL OR d.canceled_by IS NOT NULL THEN 'canceled'::job_status\n WHEN $7::BOOL THEN 'skipped'::job_status\n WHEN $2::BOOL THEN 'success'::job_status\n ELSE 'failure'::job_status END,\n d.worker\n FROM deleted d LEFT JOIN v2_job_status s ON s.id = d.id\n ON CONFLICT (id) DO UPDATE SET status = EXCLUDED.status, result = $3::text::jsonb,\n canceled_by = CASE WHEN NOT $4::BOOL AND EXCLUDED.canceled_by IS NOT NULL\n THEN EXCLUDED.canceled_by ELSE cj.canceled_by END,\n canceled_reason = CASE WHEN NOT $4::BOOL AND EXCLUDED.canceled_by IS NOT NULL\n THEN EXCLUDED.canceled_reason ELSE cj.canceled_reason END\n RETURNING cj.started_at, cj.duration_ms,\n COALESCE((cj.extras->>'wac_last_segment_ms')::bigint, cj.duration_ms) AS last_run_ms\n )\n SELECT started_at AS \"started_at?\", duration_ms AS \"duration_ms!\",\n last_run_ms AS \"last_run_ms!\" FROM completed", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "started_at?", + "type_info": "Timestamptz" + }, + { + "ordinal": 1, + "name": "duration_ms!", + "type_info": "Int8" + }, + { + "ordinal": 2, + "name": "last_run_ms!", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [ + "Uuid", + "Bool", + "Text", + "Bool", + "Varchar", + "Text", + "Bool", + "Int4", + "Int8", + "TextArray" + ] + }, + "nullable": [ + true, + false, + null + ] + }, + "hash": "ce39fd9650500b16f7247c8173a40c7e5d2d8a51aea2d36f2bc8c6f86d53a9b8" +} diff --git a/backend/.sqlx/query-d2a9a9af4d00c1c05276c14e6f32044437800a4b0c60aa364ab2f362a4fd9a2c.json b/backend/.sqlx/query-d2a9a9af4d00c1c05276c14e6f32044437800a4b0c60aa364ab2f362a4fd9a2c.json deleted file mode 100644 index ec3ae54f17..0000000000 --- a/backend/.sqlx/query-d2a9a9af4d00c1c05276c14e6f32044437800a4b0c60aa364ab2f362a4fd9a2c.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock)\n VALUES ('test-workspace', $1, 'f/test/failing_script', $2, 'deno', 'script', 'test-user', '{}', 'Failing test script', 'A script that always fails', '')\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Int8", - "Text" - ] - }, - "nullable": [] - }, - "hash": "d2a9a9af4d00c1c05276c14e6f32044437800a4b0c60aa364ab2f362a4fd9a2c" -} diff --git a/backend/.sqlx/query-d2fbaaaea6c542342862d8b535673d19dc4ca721ab656a39330bad5ea48999d8.json b/backend/.sqlx/query-d2fbaaaea6c542342862d8b535673d19dc4ca721ab656a39330bad5ea48999d8.json new file mode 100644 index 0000000000..55b335fba0 --- /dev/null +++ b/backend/.sqlx/query-d2fbaaaea6c542342862d8b535673d19dc4ca721ab656a39330bad5ea48999d8.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM runnable_job_stats WHERE workspace_id = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [] + }, + "hash": "d2fbaaaea6c542342862d8b535673d19dc4ca721ab656a39330bad5ea48999d8" +} diff --git a/backend/.sqlx/query-d5f1a2bfbac206a33b991d58f9ff4b8e8e4a3840ea1c65d409576379dede41ed.json b/backend/.sqlx/query-d5f1a2bfbac206a33b991d58f9ff4b8e8e4a3840ea1c65d409576379dede41ed.json deleted file mode 100644 index c6eb9e16a3..0000000000 --- a/backend/.sqlx/query-d5f1a2bfbac206a33b991d58f9ff4b8e8e4a3840ea1c65d409576379dede41ed.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT error_handler->'extra_args' FROM workspace_settings WHERE workspace_id = 'test-workspace'", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "?column?", - "type_info": "Jsonb" - } - ], - "parameters": { - "Left": [] - }, - "nullable": [ - null - ] - }, - "hash": "d5f1a2bfbac206a33b991d58f9ff4b8e8e4a3840ea1c65d409576379dede41ed" -} diff --git a/backend/.sqlx/query-dbc05cbf6720cc85e01118bcdcbb478724ac0ea8f3e043da2de9d932216cc730.json b/backend/.sqlx/query-dbc05cbf6720cc85e01118bcdcbb478724ac0ea8f3e043da2de9d932216cc730.json deleted file mode 100644 index 6e5f8645bf..0000000000 --- a/backend/.sqlx/query-dbc05cbf6720cc85e01118bcdcbb478724ac0ea8f3e043da2de9d932216cc730.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock)\n VALUES ('test-workspace', $1, 'f/test/simple_script', $2, 'deno', 'script', 'test-user', '{}', 'Simple test script', 'A simple test script', '')\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Int8", - "Text" - ] - }, - "nullable": [] - }, - "hash": "dbc05cbf6720cc85e01118bcdcbb478724ac0ea8f3e043da2de9d932216cc730" -} diff --git a/backend/.sqlx/query-dbd821d6d58aff9ed34cf3f14982ffe92d3cd13915be8a07f9364a14a01e549f.json b/backend/.sqlx/query-dbd821d6d58aff9ed34cf3f14982ffe92d3cd13915be8a07f9364a14a01e549f.json new file mode 100644 index 0000000000..224e1f62e7 --- /dev/null +++ b/backend/.sqlx/query-dbd821d6d58aff9ed34cf3f14982ffe92d3cd13915be8a07f9364a14a01e549f.json @@ -0,0 +1,26 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO job_resolution (job_id, workspace_id, resolved_by, note, automatic)\n SELECT c.id, c.workspace_id, $4, $5, false\n FROM v2_job_completed c\n JOIN v2_job j ON j.id = c.id\n WHERE c.id = $1\n AND c.workspace_id = $2\n AND ($3::TEXT[] IS NULL OR j.tag = ANY($3))\n AND c.status IN ('failure', 'canceled')\n AND j.flow_step_id IS NULL\n ON CONFLICT (job_id) DO NOTHING\n RETURNING job_id", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "job_id", + "type_info": "Uuid" + } + ], + "parameters": { + "Left": [ + "Uuid", + "Text", + "TextArray", + "Varchar", + "Text" + ] + }, + "nullable": [ + false + ] + }, + "hash": "dbd821d6d58aff9ed34cf3f14982ffe92d3cd13915be8a07f9364a14a01e549f" +} diff --git a/backend/.sqlx/query-e12f852fa196d16862151ab490b05e6f5c25e23b7c41ce1c0e5a83bf7b118bfd.json b/backend/.sqlx/query-e12f852fa196d16862151ab490b05e6f5c25e23b7c41ce1c0e5a83bf7b118bfd.json deleted file mode 100644 index ae893b6791..0000000000 --- a/backend/.sqlx/query-e12f852fa196d16862151ab490b05e6f5c25e23b7c41ce1c0e5a83bf7b118bfd.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "WITH prev AS (SELECT started_at FROM v2_job_queue WHERE id = $1)\n UPDATE v2_job_queue q SET running = false, started_at = null\n FROM prev WHERE q.id = $1\n RETURNING (extract(epoch FROM now() - prev.started_at) * 1000)::bigint", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "int8", - "type_info": "Int8" - } - ], - "parameters": { - "Left": [ - "Uuid" - ] - }, - "nullable": [ - null - ] - }, - "hash": "e12f852fa196d16862151ab490b05e6f5c25e23b7c41ce1c0e5a83bf7b118bfd" -} diff --git a/backend/.sqlx/query-e4b9c0e8a46dbfe29bace8d8b12123a98ec175f9d3dc72e40a1cb40e14dec919.json b/backend/.sqlx/query-e4b9c0e8a46dbfe29bace8d8b12123a98ec175f9d3dc72e40a1cb40e14dec919.json new file mode 100644 index 0000000000..9ebf9289c2 --- /dev/null +++ b/backend/.sqlx/query-e4b9c0e8a46dbfe29bace8d8b12123a98ec175f9d3dc72e40a1cb40e14dec919.json @@ -0,0 +1,14 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE worker_ping SET draining = true WHERE worker = $1", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [] + }, + "hash": "e4b9c0e8a46dbfe29bace8d8b12123a98ec175f9d3dc72e40a1cb40e14dec919" +} diff --git a/backend/.sqlx/query-e4bb7af19003baca7f4d88e954b603843edce422c522c035b81b88cb169b88b1.json b/backend/.sqlx/query-e4bb7af19003baca7f4d88e954b603843edce422c522c035b81b88cb169b88b1.json new file mode 100644 index 0000000000..c1ea457a72 --- /dev/null +++ b/backend/.sqlx/query-e4bb7af19003baca7f4d88e954b603843edce422c522c035b81b88cb169b88b1.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO job_resolution (job_id, workspace_id, resolved_by, note, automatic)\n SELECT c.id, c.workspace_id, $4, COALESCE($5, $7), false\n FROM v2_job_completed c\n JOIN v2_job j ON j.id = c.id\n WHERE c.id = ANY($1)\n AND c.workspace_id = $2\n AND ($3::TEXT[] IS NULL OR j.tag = ANY($3))\n AND c.status IN ('failure', 'canceled')\n -- Resolution is a top-level triage state: a step resolved on its own\n -- would render orange inside a flow whose status is still red.\n AND j.flow_step_id IS NULL\n -- A supersession claim has to be proven, not trusted: a later success of the\n -- same identified runnable, itself visible to the caller. An unproven claim\n -- resolves nothing, so the caller learns it was rejected instead of having\n -- the fiction recorded as provenance.\n AND ($6::UUID IS NULL OR EXISTS (\n SELECT 1 FROM v2_job_completed sc\n JOIN v2_job sj ON sj.id = sc.id\n WHERE sc.id = $6\n AND sc.workspace_id = $2\n -- Tag scope is a read restriction enforced outside RLS, so it has\n -- to bind the evidence as well: otherwise the result reveals\n -- whether an out-of-scope run succeeded.\n AND ($3::TEXT[] IS NULL OR sj.tag = ANY($3))\n AND sc.status = 'success'\n AND sc.completed_at >= c.completed_at\n AND (j.runnable_id IS NOT NULL OR j.runnable_path IS NOT NULL)\n AND sj.runnable_id IS NOT DISTINCT FROM j.runnable_id\n AND sj.runnable_path IS NOT DISTINCT FROM j.runnable_path\n ))\n ON CONFLICT (job_id) DO UPDATE SET\n resolved_at = now(),\n -- Both COALESCEd: `resolution_attribution` returns NULLs outside EE and once the\n -- licence lapses, and bulk selections routinely include already-resolved rows,\n -- so overwriting would erase metadata recorded while it was valid. Clear either\n -- by unresolving first.\n resolved_by = COALESCE($4, job_resolution.resolved_by),\n -- A person's explanation replaces what was there; machine provenance only fills\n -- a blank, so re-running an already-explained failure never erases their words.\n note = COALESCE($5, job_resolution.note, $7),\n -- A human taking over an automatic resolution makes it no longer automatic.\n automatic = false\n RETURNING job_id", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "job_id", + "type_info": "Uuid" + } + ], + "parameters": { + "Left": [ + "UuidArray", + "Text", + "TextArray", + "Varchar", + "Text", + "Uuid", + "Text" + ] + }, + "nullable": [ + false + ] + }, + "hash": "e4bb7af19003baca7f4d88e954b603843edce422c522c035b81b88cb169b88b1" +} diff --git a/backend/.sqlx/query-e4c9f3bca6bd636c3ee31fc643182ed5ca48a45da895fb992d820682f5169f7c.json b/backend/.sqlx/query-e4c9f3bca6bd636c3ee31fc643182ed5ca48a45da895fb992d820682f5169f7c.json deleted file mode 100644 index 63ce99a139..0000000000 --- a/backend/.sqlx/query-e4c9f3bca6bd636c3ee31fc643182ed5ca48a45da895fb992d820682f5169f7c.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n SELECT id\n FROM v2_job\n WHERE workspace_id = 'test-workspace'\n AND permissioned_as_email = 'error_handler@windmill.dev'\n ", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "id", - "type_info": "Uuid" - } - ], - "parameters": { - "Left": [] - }, - "nullable": [ - false - ] - }, - "hash": "e4c9f3bca6bd636c3ee31fc643182ed5ca48a45da895fb992d820682f5169f7c" -} diff --git a/backend/.sqlx/query-e7a8c0ee68b8626eb45a7eacdd364360a5d5c783d6ca0a3c4123ea126ed0e60b.json b/backend/.sqlx/query-e7a8c0ee68b8626eb45a7eacdd364360a5d5c783d6ca0a3c4123ea126ed0e60b.json new file mode 100644 index 0000000000..9f51c69616 --- /dev/null +++ b/backend/.sqlx/query-e7a8c0ee68b8626eb45a7eacdd364360a5d5c783d6ca0a3c4123ea126ed0e60b.json @@ -0,0 +1,34 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO worker_ping (worker_instance, worker, ip, custom_tags, worker_group, dedicated_worker, dedicated_workers, wm_version, vcpus, memory, job_isolation, native_mode, draining) VALUES ($1, $2, COALESCE($3, 'NO IP'), $4, $5, $6, $7, $8, $9, $10, $11, $12, COALESCE($13, false)) ON CONFLICT (worker)\n DO UPDATE set ping_at = now(), worker_instance = EXCLUDED.worker_instance, ip = COALESCE($3, worker_ping.ip), custom_tags = EXCLUDED.custom_tags, worker_group = EXCLUDED.worker_group, dedicated_worker = EXCLUDED.dedicated_worker, dedicated_workers = EXCLUDED.dedicated_workers, wm_version = EXCLUDED.wm_version, vcpus = COALESCE(EXCLUDED.vcpus, worker_ping.vcpus), memory = COALESCE(EXCLUDED.memory, worker_ping.memory), job_isolation = EXCLUDED.job_isolation, native_mode = EXCLUDED.native_mode, current_job_id = NULL, current_job_workspace_id = NULL, draining = COALESCE($13, worker_ping.draining)\n RETURNING jobs_executed", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "jobs_executed", + "type_info": "Int4" + } + ], + "parameters": { + "Left": [ + "Varchar", + "Varchar", + "Text", + "TextArray", + "Varchar", + "Varchar", + "TextArray", + "Varchar", + "Int8", + "Int8", + "Text", + "Bool", + "Bool" + ] + }, + "nullable": [ + false + ] + }, + "hash": "e7a8c0ee68b8626eb45a7eacdd364360a5d5c783d6ca0a3c4123ea126ed0e60b" +} diff --git a/backend/.sqlx/query-e8779f1cddc475554dbbd2e3122db8a21a2eaacf971bf046cef1ee14cf04e323.json b/backend/.sqlx/query-e8779f1cddc475554dbbd2e3122db8a21a2eaacf971bf046cef1ee14cf04e323.json new file mode 100644 index 0000000000..e22953610d --- /dev/null +++ b/backend/.sqlx/query-e8779f1cddc475554dbbd2e3122db8a21a2eaacf971bf046cef1ee14cf04e323.json @@ -0,0 +1,28 @@ +{ + "db_name": "PostgreSQL", + "query": "\n SELECT usr.email, usage.executions\n FROM usr, LATERAL (\n SELECT COALESCE(SUM(COALESCE((c.extras->>'wac_last_segment_ms')::bigint, c.duration_ms) + 1000)/1000 , 0)::BIGINT executions\n FROM v2_job_completed c JOIN v2_job j USING (id)\n WHERE j.workspace_id = $1\n AND j.kind NOT IN ('flow', 'flowpreview', 'flownode', 'singlestepflow')\n AND j.permissioned_as_email = usr.email\n AND now() - '1 week'::interval < j.created_at\n ) usage\n WHERE workspace_id = $1\n ", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "email", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "executions", + "type_info": "Int8" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false, + null + ] + }, + "hash": "e8779f1cddc475554dbbd2e3122db8a21a2eaacf971bf046cef1ee14cf04e323" +} diff --git a/backend/.sqlx/query-e9808cc152e1ce4717260ebb42f203ca16321a4550073258734a6208b83c00c2.json b/backend/.sqlx/query-e9808cc152e1ce4717260ebb42f203ca16321a4550073258734a6208b83c00c2.json deleted file mode 100644 index 91479f0583..0000000000 --- a/backend/.sqlx/query-e9808cc152e1ce4717260ebb42f203ca16321a4550073258734a6208b83c00c2.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "SELECT success_handler->>'path' FROM workspace_settings WHERE workspace_id = 'test-workspace'", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "?column?", - "type_info": "Text" - } - ], - "parameters": { - "Left": [] - }, - "nullable": [ - null - ] - }, - "hash": "e9808cc152e1ce4717260ebb42f203ca16321a4550073258734a6208b83c00c2" -} diff --git a/backend/.sqlx/query-eafb6d792370bf4d42cb79d0264e2eaf32f8f756920bd9fe9b302cba8e7d8814.json b/backend/.sqlx/query-eafb6d792370bf4d42cb79d0264e2eaf32f8f756920bd9fe9b302cba8e7d8814.json new file mode 100644 index 0000000000..b7cfa590d5 --- /dev/null +++ b/backend/.sqlx/query-eafb6d792370bf4d42cb79d0264e2eaf32f8f756920bd9fe9b302cba8e7d8814.json @@ -0,0 +1,31 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT l.id IS NOT NULL as \"has_lite!\",\n CASE WHEN $3::bigint IS NULL THEN NOT EXISTS (\n SELECT 1 FROM app_script s\n WHERE s.app = a.id AND s.code_sha256 = $4::text\n AND jsonb_path_exists(l.value, '$.**.inlineScript.id ? (@ == $id)',\n jsonb_build_object('id', s.id)))\n ELSE coalesce(jsonb_path_exists(l.value, '$.**.inlineScript.id ? (@ == $id)',\n jsonb_build_object('id', $3::bigint)), false)\n END as \"may_run!\"\n FROM app a\n LEFT JOIN app_version_lite l ON l.id = a.versions[array_upper(a.versions, 1)]\n WHERE a.path = $1 AND a.workspace_id = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "has_lite!", + "type_info": "Bool" + }, + { + "ordinal": 1, + "name": "may_run!", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + "Int8", + "Text" + ] + }, + "nullable": [ + null, + null + ] + }, + "hash": "eafb6d792370bf4d42cb79d0264e2eaf32f8f756920bd9fe9b302cba8e7d8814" +} diff --git a/backend/.sqlx/query-eb6dc43ac53a853eab20ef804a092249e32b1184a146463094289c604bbd0332.json b/backend/.sqlx/query-eb6dc43ac53a853eab20ef804a092249e32b1184a146463094289c604bbd0332.json new file mode 100644 index 0000000000..b69c453bef --- /dev/null +++ b/backend/.sqlx/query-eb6dc43ac53a853eab20ef804a092249e32b1184a146463094289c604bbd0332.json @@ -0,0 +1,16 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO fork_storage_namespace (workspace_id, storage, storage_ref)\n VALUES ($1, $2, $3)", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Text", + "Text" + ] + }, + "nullable": [] + }, + "hash": "eb6dc43ac53a853eab20ef804a092249e32b1184a146463094289c604bbd0332" +} diff --git a/backend/.sqlx/query-edce6243bcdfbb6380ae2b6d8a63a863c3f265ea043cc653f9732bb87860b8d9.json b/backend/.sqlx/query-edce6243bcdfbb6380ae2b6d8a63a863c3f265ea043cc653f9732bb87860b8d9.json new file mode 100644 index 0000000000..94b5ba8f10 --- /dev/null +++ b/backend/.sqlx/query-edce6243bcdfbb6380ae2b6d8a63a863c3f265ea043cc653f9732bb87860b8d9.json @@ -0,0 +1,65 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT id, email, name, is_public, message_count, created_by, snapshot, shared_at\n FROM ai_shared_session\n WHERE workspace_id = $1 AND id = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "email", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "name", + "type_info": "Varchar" + }, + { + "ordinal": 3, + "name": "is_public", + "type_info": "Bool" + }, + { + "ordinal": 4, + "name": "message_count", + "type_info": "Int4" + }, + { + "ordinal": 5, + "name": "created_by", + "type_info": "Varchar" + }, + { + "ordinal": 6, + "name": "snapshot", + "type_info": "Text" + }, + { + "ordinal": 7, + "name": "shared_at", + "type_info": "Timestamptz" + } + ], + "parameters": { + "Left": [ + "Text", + "Uuid" + ] + }, + "nullable": [ + false, + false, + false, + false, + false, + false, + false, + false + ] + }, + "hash": "edce6243bcdfbb6380ae2b6d8a63a863c3f265ea043cc653f9732bb87860b8d9" +} diff --git a/backend/.sqlx/query-cbc521b505c3953dc624ae6cefe6999e6d0c732da83ebc74ef7678cacd22ad6b.json b/backend/.sqlx/query-efc7aab19d729ea419c1fcaef47122096921dce2dac3979a8b788bf76f32646b.json similarity index 58% rename from backend/.sqlx/query-cbc521b505c3953dc624ae6cefe6999e6d0c732da83ebc74ef7678cacd22ad6b.json rename to backend/.sqlx/query-efc7aab19d729ea419c1fcaef47122096921dce2dac3979a8b788bf76f32646b.json index a2a87b680d..81505d64a3 100644 --- a/backend/.sqlx/query-cbc521b505c3953dc624ae6cefe6999e6d0c732da83ebc74ef7678cacd22ad6b.json +++ b/backend/.sqlx/query-efc7aab19d729ea419c1fcaef47122096921dce2dac3979a8b788bf76f32646b.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "WITH active_users as (SELECT distinct username as email FROM audit_partitioned WHERE timestamp > NOW() - INTERVAL '1 month' AND (operation = 'users.login' OR operation = 'oauth.login' OR operation = 'users.token.refresh') AND username NOT IN (SELECT email FROM usr WHERE is_service_account)),\n active_authors as (SELECT distinct t.email FROM usr t LEFT JOIN workspace_settings ws ON ws.workspace_id = t.workspace_id WHERE NOT (t.operator AND NOT COALESCE((ws.operator_settings->>'builder_flows')::boolean, false)) AND t.email IN (SELECT email FROM active_users)),\n active_authors_agg as (SELECT array_agg(email) as authors FROM active_authors),\n active_ops_agg as (SELECT array_agg(email) as operators from active_users WHERE email NOT IN (SELECT email FROM active_authors))\n SELECT active_authors_agg.authors, active_ops_agg.operators, array_length(active_authors_agg.authors, 1) as author_count, array_length(active_ops_agg.operators, 1) as operator_count FROM active_authors_agg, active_ops_agg", + "query": "WITH active_users as (SELECT distinct username as email FROM audit_partitioned WHERE timestamp > NOW() - INTERVAL '1 month' AND (operation = 'users.login' OR operation = 'oauth.login' OR operation = 'users.token.refresh') AND username NOT IN (SELECT email FROM usr WHERE is_service_account)),\n active_authors as (SELECT distinct t.email FROM usr t LEFT JOIN workspace_settings ws ON ws.workspace_id = t.workspace_id WHERE NOT (t.operator AND NOT (COALESCE((ws.operator_settings->>'builder_flows')::boolean, false) OR COALESCE((ws.operator_settings->>'builder_apps')::boolean, false))) AND t.email IN (SELECT email FROM active_users)),\n active_authors_agg as (SELECT array_agg(email) as authors FROM active_authors),\n active_ops_agg as (SELECT array_agg(email) as operators from active_users WHERE email NOT IN (SELECT email FROM active_authors))\n SELECT active_authors_agg.authors, active_ops_agg.operators, array_length(active_authors_agg.authors, 1) as author_count, array_length(active_ops_agg.operators, 1) as operator_count FROM active_authors_agg, active_ops_agg", "describe": { "columns": [ { @@ -34,5 +34,5 @@ null ] }, - "hash": "cbc521b505c3953dc624ae6cefe6999e6d0c732da83ebc74ef7678cacd22ad6b" + "hash": "efc7aab19d729ea419c1fcaef47122096921dce2dac3979a8b788bf76f32646b" } diff --git a/backend/.sqlx/query-f0498c9bddc0d4d8948167f3ed849bf8b3523d8dde1ef6b8f1950423830cc6ed.json b/backend/.sqlx/query-f0498c9bddc0d4d8948167f3ed849bf8b3523d8dde1ef6b8f1950423830cc6ed.json deleted file mode 100644 index 5f86fb97d8..0000000000 --- a/backend/.sqlx/query-f0498c9bddc0d4d8948167f3ed849bf8b3523d8dde1ef6b8f1950423830cc6ed.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "UPDATE v2_job_queue\n SET suspend = $3, suspend_until = now() + make_interval(secs => $4), started_at = null\n WHERE id = $1 AND workspace_id = $2", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Uuid", - "Text", - "Int4", - "Float8" - ] - }, - "nullable": [] - }, - "hash": "f0498c9bddc0d4d8948167f3ed849bf8b3523d8dde1ef6b8f1950423830cc6ed" -} diff --git a/backend/.sqlx/query-f338741f0866dc717ccfcf6b7d46b4e55ca07e472610b29fad24b64f45f98e18.json b/backend/.sqlx/query-f338741f0866dc717ccfcf6b7d46b4e55ca07e472610b29fad24b64f45f98e18.json new file mode 100644 index 0000000000..0f57f5d951 --- /dev/null +++ b/backend/.sqlx/query-f338741f0866dc717ccfcf6b7d46b4e55ca07e472610b29fad24b64f45f98e18.json @@ -0,0 +1,59 @@ +{ + "db_name": "PostgreSQL", + "query": "DELETE FROM draft\n WHERE workspace_id = $1 AND path = $2 AND typ = $3\n AND ($4::text IS NULL OR email = $4)\n RETURNING 1 as \"one!\"", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "one!", + "type_info": "Int4" + } + ], + "parameters": { + "Left": [ + "Text", + "Text", + { + "Custom": { + "name": "draft_kind", + "kind": { + "Enum": [ + "script", + "flow", + "app", + "raw_app", + "resource", + "variable", + "trigger_schedule", + "trigger_webhook", + "trigger_default_email", + "trigger_email", + "trigger_http", + "trigger_websocket", + "trigger_postgres", + "trigger_kafka", + "trigger_nats", + "trigger_mqtt", + "trigger_sqs", + "trigger_gcp", + "trigger_azure", + "trigger_poll", + "trigger_cli", + "trigger_nextcloud", + "trigger_google", + "trigger_github", + "data_pipeline", + "trigger_amqp" + ] + } + } + }, + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "f338741f0866dc717ccfcf6b7d46b4e55ca07e472610b29fad24b64f45f98e18" +} diff --git a/backend/.sqlx/query-f434d29f5617e1a97f9cc556ffaf47751aa5bff0741e98c00b3294d29dc36718.json b/backend/.sqlx/query-f434d29f5617e1a97f9cc556ffaf47751aa5bff0741e98c00b3294d29dc36718.json new file mode 100644 index 0000000000..79b8e613ac --- /dev/null +++ b/backend/.sqlx/query-f434d29f5617e1a97f9cc556ffaf47751aa5bff0741e98c00b3294d29dc36718.json @@ -0,0 +1,24 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT format('rawscript/%s', s.code_sha256) as \"path!: String\"\n FROM app_script s JOIN app a ON a.id = s.app\n WHERE s.id = $1 AND a.path = $2 AND a.workspace_id = $3", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "path!: String", + "type_info": "Text" + } + ], + "parameters": { + "Left": [ + "Int8", + "Text", + "Text" + ] + }, + "nullable": [ + null + ] + }, + "hash": "f434d29f5617e1a97f9cc556ffaf47751aa5bff0741e98c00b3294d29dc36718" +} diff --git a/backend/.sqlx/query-f633095ebe2fdabd116d687c7f8cfb8cb76159d8db20a42e0fce71146f9b8aaa.json b/backend/.sqlx/query-f633095ebe2fdabd116d687c7f8cfb8cb76159d8db20a42e0fce71146f9b8aaa.json new file mode 100644 index 0000000000..c8134447e6 --- /dev/null +++ b/backend/.sqlx/query-f633095ebe2fdabd116d687c7f8cfb8cb76159d8db20a42e0fce71146f9b8aaa.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "INSERT INTO global_settings (name, value) VALUES ($1, $2) ON CONFLICT (name) DO UPDATE SET value = EXCLUDED.value, updated_at = now() WHERE global_settings.value IS DISTINCT FROM EXCLUDED.value", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Varchar", + "Jsonb" + ] + }, + "nullable": [] + }, + "hash": "f633095ebe2fdabd116d687c7f8cfb8cb76159d8db20a42e0fce71146f9b8aaa" +} diff --git a/backend/.sqlx/query-fa62a55dd0a635995390ad4189b847b91388b6699f16afb57d8147d7e9712220.json b/backend/.sqlx/query-fa62a55dd0a635995390ad4189b847b91388b6699f16afb57d8147d7e9712220.json new file mode 100644 index 0000000000..bfda06948d --- /dev/null +++ b/backend/.sqlx/query-fa62a55dd0a635995390ad4189b847b91388b6699f16afb57d8147d7e9712220.json @@ -0,0 +1,337 @@ +{ + "db_name": "PostgreSQL", + "query": "UPDATE v2_job_status SET\n flow_status = JSONB_SET(\n JSONB_SET(v2_job_status.flow_status, $2::TEXT[], $3),\n $4::TEXT[], $5\n ) - $6::TEXT[],\n flow_leaf_jobs = CASE\n WHEN $7::TEXT IS NULL\n OR COALESCE(v2_job.flow_innermost_root_job, v2_job_status.id) <> v2_job_status.id\n THEN v2_job_status.flow_leaf_jobs\n ELSE JSONB_SET(COALESCE(v2_job_status.flow_leaf_jobs, '{}'::JSONB), ARRAY[$7::TEXT], $8) END\n FROM v2_job_queue INNER JOIN v2_job ON v2_job.id = v2_job_queue.id\n LEFT JOIN job_perms ON job_perms.job_id = v2_job_queue.id\n WHERE v2_job_status.id = $1 AND v2_job_queue.id = $1\n RETURNING\n v2_job_queue.workspace_id,\n v2_job_queue.id,\n v2_job.args as \"args: sqlx::types::Json>>\",\n v2_job.parent_job,\n v2_job.created_by,\n v2_job_queue.started_at,\n v2_job_queue.runnable_settings_handle,\n v2_job_queue.scheduled_for,\n v2_job.runnable_path,\n v2_job.kind as \"kind: JobKind\",\n v2_job.runnable_id as \"runnable_id: ScriptHash\",\n v2_job_queue.canceled_reason,\n v2_job_queue.canceled_by,\n v2_job.permissioned_as,\n v2_job.permissioned_as_email,\n v2_job_status.flow_status as \"flow_status: sqlx::types::Json>\",\n v2_job.tag,\n v2_job.script_lang as \"script_lang: ScriptLang\",\n v2_job.same_worker,\n v2_job.pre_run_error,\n v2_job.concurrent_limit,\n v2_job.concurrency_time_window_s,\n v2_job.flow_innermost_root_job,\n v2_job.root_job,\n v2_job.timeout,\n v2_job.flow_step_id,\n v2_job.cache_ttl,\n v2_job_queue.cache_ignore_s3_path,\n v2_job_queue.priority,\n v2_job.preprocessed,\n v2_job.script_entrypoint_override,\n v2_job.trigger,\n v2_job.trigger_kind as \"trigger_kind: TriggerKindLabel\",\n v2_job.visible_to_owner,\n NULL as permissioned_as_end_user_email,\n NULL::boolean as viewer_data_access,\n job_perms.job_token_scopes", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "workspace_id", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "id", + "type_info": "Uuid" + }, + { + "ordinal": 2, + "name": "args: sqlx::types::Json>>", + "type_info": "Jsonb" + }, + { + "ordinal": 3, + "name": "parent_job", + "type_info": "Uuid" + }, + { + "ordinal": 4, + "name": "created_by", + "type_info": "Varchar" + }, + { + "ordinal": 5, + "name": "started_at", + "type_info": "Timestamptz" + }, + { + "ordinal": 6, + "name": "runnable_settings_handle", + "type_info": "Int8" + }, + { + "ordinal": 7, + "name": "scheduled_for", + "type_info": "Timestamptz" + }, + { + "ordinal": 8, + "name": "runnable_path", + "type_info": "Varchar" + }, + { + "ordinal": 9, + "name": "kind: JobKind", + "type_info": { + "Custom": { + "name": "job_kind", + "kind": { + "Enum": [ + "script", + "preview", + "flow", + "dependencies", + "flowpreview", + "script_hub", + "identity", + "flowdependencies", + "http", + "graphql", + "postgresql", + "noop", + "appdependencies", + "deploymentcallback", + "singlestepflow", + "flowscript", + "flownode", + "appscript", + "aiagent", + "unassigned_script", + "unassigned_flow", + "unassigned_singlestepflow" + ] + } + } + } + }, + { + "ordinal": 10, + "name": "runnable_id: ScriptHash", + "type_info": "Int8" + }, + { + "ordinal": 11, + "name": "canceled_reason", + "type_info": "Text" + }, + { + "ordinal": 12, + "name": "canceled_by", + "type_info": "Varchar" + }, + { + "ordinal": 13, + "name": "permissioned_as", + "type_info": "Varchar" + }, + { + "ordinal": 14, + "name": "permissioned_as_email", + "type_info": "Varchar" + }, + { + "ordinal": 15, + "name": "flow_status: sqlx::types::Json>", + "type_info": "Jsonb" + }, + { + "ordinal": 16, + "name": "tag", + "type_info": "Varchar" + }, + { + "ordinal": 17, + "name": "script_lang: ScriptLang", + "type_info": { + "Custom": { + "name": "script_lang", + "kind": { + "Enum": [ + "python3", + "deno", + "go", + "bash", + "postgresql", + "nativets", + "bun", + "mysql", + "bigquery", + "snowflake", + "graphql", + "powershell", + "mssql", + "php", + "bunnative", + "rust", + "ansible", + "csharp", + "oracledb", + "nu", + "java", + "duckdb", + "ruby", + "rlang", + "dbt" + ] + } + } + } + }, + { + "ordinal": 18, + "name": "same_worker", + "type_info": "Bool" + }, + { + "ordinal": 19, + "name": "pre_run_error", + "type_info": "Text" + }, + { + "ordinal": 20, + "name": "concurrent_limit", + "type_info": "Int4" + }, + { + "ordinal": 21, + "name": "concurrency_time_window_s", + "type_info": "Int4" + }, + { + "ordinal": 22, + "name": "flow_innermost_root_job", + "type_info": "Uuid" + }, + { + "ordinal": 23, + "name": "root_job", + "type_info": "Uuid" + }, + { + "ordinal": 24, + "name": "timeout", + "type_info": "Int4" + }, + { + "ordinal": 25, + "name": "flow_step_id", + "type_info": "Varchar" + }, + { + "ordinal": 26, + "name": "cache_ttl", + "type_info": "Int4" + }, + { + "ordinal": 27, + "name": "cache_ignore_s3_path", + "type_info": "Bool" + }, + { + "ordinal": 28, + "name": "priority", + "type_info": "Int2" + }, + { + "ordinal": 29, + "name": "preprocessed", + "type_info": "Bool" + }, + { + "ordinal": 30, + "name": "script_entrypoint_override", + "type_info": "Varchar" + }, + { + "ordinal": 31, + "name": "trigger", + "type_info": "Varchar" + }, + { + "ordinal": 32, + "name": "trigger_kind: TriggerKindLabel", + "type_info": { + "Custom": { + "name": "job_trigger_kind", + "kind": { + "Enum": [ + "webhook", + "http", + "websocket", + "kafka", + "email", + "nats", + "schedule", + "app", + "ui", + "postgres", + "sqs", + "gcp", + "mqtt", + "nextcloud", + "google", + "ci_test", + "github", + "azure", + "asset", + "freshness", + "amqp" + ] + } + } + } + }, + { + "ordinal": 33, + "name": "visible_to_owner", + "type_info": "Bool" + }, + { + "ordinal": 34, + "name": "permissioned_as_end_user_email", + "type_info": "Text" + }, + { + "ordinal": 35, + "name": "viewer_data_access", + "type_info": "Bool" + }, + { + "ordinal": 36, + "name": "job_token_scopes", + "type_info": "TextArray" + } + ], + "parameters": { + "Left": [ + "Uuid", + "TextArray", + "Jsonb", + "TextArray", + "Jsonb", + "TextArray", + "Text", + "Jsonb" + ] + }, + "nullable": [ + false, + false, + true, + true, + false, + true, + true, + false, + true, + false, + true, + true, + true, + false, + false, + true, + false, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + null, + null, + true + ] + }, + "hash": "fa62a55dd0a635995390ad4189b847b91388b6699f16afb57d8147d7e9712220" +} diff --git a/backend/.sqlx/query-fd04f65015069792f23edbfce320af6e69ee32b27a8f0a020e251eb2c79e43cd.json b/backend/.sqlx/query-fd04f65015069792f23edbfce320af6e69ee32b27a8f0a020e251eb2c79e43cd.json new file mode 100644 index 0000000000..4801a9b5da --- /dev/null +++ b/backend/.sqlx/query-fd04f65015069792f23edbfce320af6e69ee32b27a8f0a020e251eb2c79e43cd.json @@ -0,0 +1,71 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT email, username, is_admin, is_operator, groups, folders, end_user_email,\n job_token_scopes, viewer_data_access\n FROM job_perms WHERE job_id = $1 AND workspace_id = $2", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "email", + "type_info": "Varchar" + }, + { + "ordinal": 1, + "name": "username", + "type_info": "Varchar" + }, + { + "ordinal": 2, + "name": "is_admin", + "type_info": "Bool" + }, + { + "ordinal": 3, + "name": "is_operator", + "type_info": "Bool" + }, + { + "ordinal": 4, + "name": "groups", + "type_info": "TextArray" + }, + { + "ordinal": 5, + "name": "folders", + "type_info": "JsonbArray" + }, + { + "ordinal": 6, + "name": "end_user_email", + "type_info": "Varchar" + }, + { + "ordinal": 7, + "name": "job_token_scopes", + "type_info": "TextArray" + }, + { + "ordinal": 8, + "name": "viewer_data_access", + "type_info": "Bool" + } + ], + "parameters": { + "Left": [ + "Uuid", + "Text" + ] + }, + "nullable": [ + false, + false, + false, + false, + false, + false, + true, + true, + false + ] + }, + "hash": "fd04f65015069792f23edbfce320af6e69ee32b27a8f0a020e251eb2c79e43cd" +} diff --git a/backend/.sqlx/query-fdf0a16a72bc2eca2025d64750e2e6a7e7ff90b5ad4b42e6aab53992b447a20e.json b/backend/.sqlx/query-fdf0a16a72bc2eca2025d64750e2e6a7e7ff90b5ad4b42e6aab53992b447a20e.json deleted file mode 100644 index 69497769d7..0000000000 --- a/backend/.sqlx/query-fdf0a16a72bc2eca2025d64750e2e6a7e7ff90b5ad4b42e6aab53992b447a20e.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n SELECT\n id,\n runnable_path,\n permissioned_as_email,\n parent_job\n FROM v2_job\n WHERE workspace_id = 'test-workspace'\n AND permissioned_as_email = 'error_handler@windmill.dev'\n ORDER BY created_at DESC\n LIMIT 1\n ", - "describe": { - "columns": [ - { - "ordinal": 0, - "name": "id", - "type_info": "Uuid" - }, - { - "ordinal": 1, - "name": "runnable_path", - "type_info": "Varchar" - }, - { - "ordinal": 2, - "name": "permissioned_as_email", - "type_info": "Varchar" - }, - { - "ordinal": 3, - "name": "parent_job", - "type_info": "Uuid" - } - ], - "parameters": { - "Left": [] - }, - "nullable": [ - false, - true, - false, - true - ] - }, - "hash": "fdf0a16a72bc2eca2025d64750e2e6a7e7ff90b5ad4b42e6aab53992b447a20e" -} diff --git a/backend/.sqlx/query-fe17aff543f28cf4d6d09ea7c4c7d18ff6a95a8402468131f5a5f33df91c59e4.json b/backend/.sqlx/query-fe17aff543f28cf4d6d09ea7c4c7d18ff6a95a8402468131f5a5f33df91c59e4.json deleted file mode 100644 index c747e99795..0000000000 --- a/backend/.sqlx/query-fe17aff543f28cf4d6d09ea7c4c7d18ff6a95a8402468131f5a5f33df91c59e4.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "db_name": "PostgreSQL", - "query": "\n INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock)\n VALUES ('test-workspace', 1111111111, 'f/test/error_handler', $1, 'deno', 'script', 'test-user', '{}', 'Error handler script', 'Handles failed job completions', '')\n ", - "describe": { - "columns": [], - "parameters": { - "Left": [ - "Text" - ] - }, - "nullable": [] - }, - "hash": "fe17aff543f28cf4d6d09ea7c4c7d18ff6a95a8402468131f5a5f33df91c59e4" -} diff --git a/backend/.sqlx/query-68bca8f839e47705b11d312ee874eceaa3d1d24d9053ad4aea94b9f8465585ca.json b/backend/.sqlx/query-fe22c4609d8b2472c0f83fedb92eceec2b6f1ae1a32fcf375161d04419404d9c.json similarity index 86% rename from backend/.sqlx/query-68bca8f839e47705b11d312ee874eceaa3d1d24d9053ad4aea94b9f8465585ca.json rename to backend/.sqlx/query-fe22c4609d8b2472c0f83fedb92eceec2b6f1ae1a32fcf375161d04419404d9c.json index 583d2bcc6b..5ee5c7571d 100644 --- a/backend/.sqlx/query-68bca8f839e47705b11d312ee874eceaa3d1d24d9053ad4aea94b9f8465585ca.json +++ b/backend/.sqlx/query-fe22c4609d8b2472c0f83fedb92eceec2b6f1ae1a32fcf375161d04419404d9c.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "SELECT worker, worker_instance, EXTRACT(EPOCH FROM (now() - ping_at))::integer as last_ping, started_at, ip, jobs_executed,\n CASE WHEN $4 IS TRUE THEN current_job_id ELSE NULL END as last_job_id, CASE WHEN $4 IS TRUE THEN current_job_workspace_id ELSE NULL END as last_job_workspace_id,\n custom_tags, worker_group, wm_version, occupancy_rate, occupancy_rate_15s, occupancy_rate_5m, occupancy_rate_30m, memory, vcpus, memory_usage, wm_memory_usage, job_isolation, native_mode\n FROM worker_ping\n WHERE ($1::integer IS NULL AND ping_at > now() - interval '5 minute') OR (ping_at > now() - ($1 || ' seconds')::interval)\n ORDER BY ping_at desc LIMIT $2 OFFSET $3", + "query": "SELECT worker, worker_instance, EXTRACT(EPOCH FROM (now() - ping_at))::integer as last_ping, started_at, ip, jobs_executed,\n CASE WHEN $4 IS TRUE THEN current_job_id ELSE NULL END as last_job_id, CASE WHEN $4 IS TRUE THEN current_job_workspace_id ELSE NULL END as last_job_workspace_id,\n custom_tags, worker_group, wm_version, occupancy_rate, occupancy_rate_15s, occupancy_rate_5m, occupancy_rate_30m, memory, vcpus, memory_usage, wm_memory_usage, job_isolation, native_mode, draining\n FROM worker_ping\n WHERE ($1::integer IS NULL AND ping_at > now() - interval '5 minute') OR (ping_at > now() - ($1 || ' seconds')::interval)\n ORDER BY ping_at desc LIMIT $2 OFFSET $3", "describe": { "columns": [ { @@ -107,6 +107,11 @@ "ordinal": 20, "name": "native_mode", "type_info": "Bool" + }, + { + "ordinal": 21, + "name": "draining", + "type_info": "Bool" } ], "parameters": { @@ -138,8 +143,9 @@ true, true, true, + false, false ] }, - "hash": "68bca8f839e47705b11d312ee874eceaa3d1d24d9053ad4aea94b9f8465585ca" + "hash": "fe22c4609d8b2472c0f83fedb92eceec2b6f1ae1a32fcf375161d04419404d9c" } diff --git a/backend/AGENTS.md b/backend/AGENTS.md index 750e0594e1..290890009a 100644 --- a/backend/AGENTS.md +++ b/backend/AGENTS.md @@ -6,17 +6,17 @@ - **DB schema**: `backend/summarized_schema.txt` - **API routes entry point**: `windmill-api/src/lib.rs` - **OpenAPI spec**: `windmill-api/openapi.yaml` -- **DuckDB local jobs**: build the dynamic FFI library before running DuckDB scripts locally: +- **DuckDB local jobs**: build the DuckDB runner before running DuckDB scripts locally: ```bash cd backend/windmill-duckdb-ffi-internal && ./build_dev.sh ``` - Re-run after clean builds or when `target/debug/libwindmill_duckdb_ffi_internal.*` is missing. + Re-run after clean builds or when `target/debug/windmill_duckdb_runner` is missing. The bundled DuckDB compile (~2min) is cached in a per-user dir shared across worktrees (keyed by the crate's `Cargo.lock`), so a fresh worktree reuses it and the build is near-instant — you don't pay the full compile per worktree. Editing - the FFI crate's own source falls back to an isolated per-worktree `./target`. - The engine is a **patched fork** of duckdb-rs, not the crates.io crate — read - `docs/duckdb-isolation.md` before bumping it or touching the isolation transform. + the crate's own source falls back to an isolated per-worktree `./target`. + Jobs run in that binary, out of the worker's process, under the worker's job isolation — + read `docs/duckdb-execution.md` before changing how it is spawned or what crosses to it. - **Running data pipelines (DuckLake) from source**: see the section below — a plain build advertises the `duckdb` tag but cannot execute DuckDB scripts and has no working S3 proxy. @@ -120,7 +120,7 @@ only what you need — build time scales with the set. | `enterprise` | EE business logic (autoscaling, SAML hooks, advanced S3 rule **enforcement**, WAP, forks, …). Pulls in `license`. | Running EE features. Advanced S3 permission rules only take effect with this. | | `license` | License-key/plan plumbing (`LICENSE_KEY`). Pulled in by `enterprise`. Having the feature compiled does **not** require a license *key* at runtime — CE defaults to a free plan and most EE paths still run keyless. | License-gated behavior. | | `parquet` | S3/object-storage support: the `job_helpers/*` and `apps_u/*` S3 endpoints, parquet/CSV preview, workspace large-file storage. Without it those routes return `"requires parquet"`. | Anything touching S3/object storage or datasets. | -| `duckdb` | DuckDB script executor (also needs the FFI dylib — see above). | DuckDB scripts, DuckLake. | +| `duckdb` | DuckDB script executor (also needs the runner binary — see above). | DuckDB scripts, DuckLake. | | `python` `rust` `php` `java` `ruby` `csharp` `nu` `deno_core` `mysql` `mssql` `bigquery` `snowflake` `oracledb` `rlang` | Each enables that language/DB runtime for job execution. | Running jobs in that language. | | `mcp` | MCP gateway routes (baseline `quickjs` does NOT include it → MCP routes 404). | MCP work. | | `websocket` `http_trigger` `kafka` `nats` `mqtt_trigger` `sqs_trigger` `gcp_trigger` `azure_trigger` `postgres_trigger` `native_trigger` | Each native trigger kind; none on by default (creating one 404s without its feature). | Working on / exercising that trigger. | @@ -136,7 +136,7 @@ minimal explicit set for dev. | Plain dev baseline (JS eval only) | `quickjs` | | S3 / object storage / datasets (CE) | `quickjs,private,parquet` | | S3 + EE (advanced S3 rules, on-behalf app reads, WAP, forks) | `quickjs,enterprise,private,parquet` | -| DuckLake / DuckDB (CE) | `quickjs,duckdb,parquet,private` (+ build the FFI) | +| DuckLake / DuckDB (CE) | `quickjs,duckdb,parquet,private` (+ build the runner) | | + Python jobs | append `,python` | ## Workspace object storage in dev — use the local filesystem @@ -163,7 +163,7 @@ in DuckDB"`) — DuckLake/datatable go through the S3 proxy instead, which works ## Running data pipelines (DuckLake) from source -DuckLake pipelines need **both** the right cargo features **and** the prebuilt DuckDB FFI. A +DuckLake pipelines need **both** the right cargo features **and** the DuckDB runner binary. A plain `cargo run` (or `cargo run --features quickjs`) does **not** suffice, and the failure modes are silent-ish, so agents lose time. Verify feature names against `backend/Cargo.toml` `[features]`. @@ -178,7 +178,7 @@ are silent-ish, so agents lose time. Verify feature names against `backend/Cargo `enterprise` already pulls in `license`, but list both when you want the license-gated paths. `quickjs` is for JS eval, not DuckLake per se — keep it if your baseline build had it. -**Before running any DuckDB script**, build the FFI (see the bullet above): +**Before running any DuckDB script**, build the runner (see the bullet above): `cd backend/windmill-duckdb-ffi-internal && ./build_dev.sh`. **Two gotchas that a wrong feature set produces:** @@ -214,7 +214,7 @@ Whole classes of defect compile and unit-test clean: - **Stack overflow from a large buffer in an async block.** An array declared across an `.await` is baked into the future's state; once that future is boxed a few layers deep by the job poller, two 16 KB arrays abort the worker *process* (`thread - 'tokio-runtime-worker' has overflowed its stack`). Heap-allocate read buffers + 'tokio-rt-worker' has overflowed its stack`). Heap-allocate read buffers (`vec![0u8; N]`, not `[0u8; N]`). - Deadlocks from draining only one of a child's pipes, missed cancellation or timeout propagation, and anything depending on the real engine's output format. diff --git a/backend/Cargo.lock b/backend/Cargo.lock index aeb7670d17..3f2dfbffec 100644 --- a/backend/Cargo.lock +++ b/backend/Cargo.lock @@ -2,15 +2,6 @@ # It is not intended for manual editing. version = 4 -[[package]] -name = "addr2line" -version = "0.25.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b5d307320b3181d6d7954e663bd7c774a838b8220fe0593c86d9fb09f498b4b" -dependencies = [ - "gimli", -] - [[package]] name = "adler2" version = "2.0.1" @@ -247,14 +238,14 @@ version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "73cd58deff2140a0a8eae87e417bd01db68a33e148aa93d1e8cd837e55e312b6" dependencies = [ - "object 0.39.1", + "object", ] [[package]] name = "arc-swap" -version = "1.9.2" +version = "1.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c049c0be4daef0b145cb3555416b3b8ef5b7888a38aea1a3a155801fe7b0810b" +checksum = "380962b3d93b99642e50b9febf72c071e97e8b32d86eae9cf4ef582bb960ae6e" dependencies = [ "rustversion", ] @@ -508,6 +499,22 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16" +[[package]] +name = "asn1-rs" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f6fd5ddaf0351dff5b8da21b2fb4ff8e08ddd02857f0bf69c47639106c0fff0" +dependencies = [ + "asn1-rs-derive 0.4.0", + "asn1-rs-impl 0.1.0", + "displaydoc", + "nom", + "num-traits", + "rusticata-macros", + "thiserror 1.0.69", + "time", +] + [[package]] name = "asn1-rs" version = "0.6.2" @@ -515,7 +522,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5493c3bedbacf7fd7382c6346bbd66687d12bbaad3a89a2d2c303ee6cf20b048" dependencies = [ "asn1-rs-derive 0.5.1", - "asn1-rs-impl", + "asn1-rs-impl 0.2.0", "displaydoc", "nom", "num-traits", @@ -531,7 +538,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8" dependencies = [ "asn1-rs-derive 0.6.0", - "asn1-rs-impl", + "asn1-rs-impl 0.2.0", "displaydoc", "nom", "num-traits", @@ -540,6 +547,18 @@ dependencies = [ "time", ] +[[package]] +name = "asn1-rs-derive" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "726535892e8eae7e70657b4c8ea93d26b8553afb1ce617caee529ef96d7dee6c" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", + "synstructure 0.12.6", +] + [[package]] name = "asn1-rs-derive" version = "0.5.1" @@ -564,6 +583,17 @@ dependencies = [ "synstructure 0.13.2", ] +[[package]] +name = "asn1-rs-impl" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2777730b2039ac0f95f093556e61b6d26cebed5393ca6f152717777cec3a42ed" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + [[package]] name = "asn1-rs-impl" version = "0.2.0" @@ -834,7 +864,7 @@ checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -873,7 +903,7 @@ checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -920,6 +950,35 @@ version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" +[[package]] +name = "attribute-derive" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f9ef7a68684657ce9da341c934c73b63df7a3585a61e366d84c84ed5d3d167" +dependencies = [ + "attribute-derive-macro", + "manyhow 0.14.1", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "attribute-derive-macro" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300d426e5e73549125bb8e4649bdd5508f82c94ddf898fb0517246e71dfb8e98" +dependencies = [ + "collection_literals", + "interpolator", + "manyhow 0.14.1", + "proc-macro-utils", + "proc-macro2", + "quote", + "quote-use", + "syn 3.0.9", +] + [[package]] name = "autocfg" version = "1.5.1" @@ -970,20 +1029,32 @@ dependencies = [ [[package]] name = "aws-lc-rs" -version = "1.18.1" +version = "1.18.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b281d307588d634de920874890732659e2e7672f72b5e10e81badc1a8a83621e" +checksum = "faac5829c2b74c28f830747e7818ccfb684261b5f48a1118b1e2a13d36dfab13" dependencies = [ - "aws-lc-sys", + "aws-lc-sys 0.46.0", "untrusted 0.7.1", "zeroize", ] [[package]] name = "aws-lc-sys" -version = "0.45.0" +version = "0.40.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bff6c3b54fad79a2e60b8102caf565819711497c1f5f092f49508e2f5c31b27" +checksum = "f50037ee5e1e41e7b8f9d161680a725bd1626cb6f8c7e901f91f942850852fe7" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", +] + +[[package]] +name = "aws-lc-sys" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1622d8446a2d4b2ce0c7eefc73dd43a99779028d5ee5c2dd8073a658ba8a2bc" dependencies = [ "cc", "cmake", @@ -1265,9 +1336,9 @@ dependencies = [ [[package]] name = "aws-smithy-async" -version = "1.2.12" +version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3cba48474f1d6807384d06fec085b909f5807e16653c5af5c45dfe89539f0b70" +checksum = "f02e407fb3b54891734224b9ffac8a71fdd35f542500fa1af95754a6b2beb316" dependencies = [ "futures-util", "pin-project-lite", @@ -1349,8 +1420,8 @@ dependencies = [ "hyper-util", "pin-project-lite", "rustls 0.21.12", - "rustls 0.23.35", - "rustls-native-certs 0.8.4", + "rustls 0.23.40", + "rustls-native-certs 0.8.5", "rustls-pki-types", "tokio", "tokio-rustls 0.26.6", @@ -1492,44 +1563,17 @@ dependencies = [ "aws-smithy-async", "aws-smithy-runtime-api", "aws-smithy-types", - "rustc_version 0.4.1", + "rustc_version", "tracing", ] -[[package]] -name = "axum" -version = "0.7.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edca88bc138befd0323b20752846e6587272d3b03b0343c8ea28a6f819e6e71f" -dependencies = [ - "async-trait", - "axum-core 0.4.5", - "bytes", - "futures-util", - "http 1.5.0", - "http-body 1.1.0", - "http-body-util", - "itoa", - "matchit 0.7.3", - "memchr", - "mime", - "percent-encoding", - "pin-project-lite", - "rustversion", - "serde", - "sync_wrapper", - "tower 0.5.3", - "tower-layer", - "tower-service", -] - [[package]] name = "axum" version = "0.8.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" dependencies = [ - "axum-core 0.5.6", + "axum-core", "axum-macros", "bytes", "form_urlencoded", @@ -1558,26 +1602,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "axum-core" -version = "0.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "09f2bd6146b97ae3359fa0cc6d6b376d9539582c7b4220f041a33ec24c226199" -dependencies = [ - "async-trait", - "bytes", - "futures-util", - "http 1.5.0", - "http-body 1.1.0", - "http-body-util", - "mime", - "pin-project-lite", - "rustversion", - "sync_wrapper", - "tower-layer", - "tower-service", -] - [[package]] name = "axum-core" version = "0.5.6" @@ -1608,12 +1632,6 @@ dependencies = [ "syn 2.0.119", ] -[[package]] -name = "az" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "be5eb007b7cacc6c660343e96f650fedf4b5a77512399eb952ca6642cf8d13f7" - [[package]] name = "backon" version = "1.6.0" @@ -1625,27 +1643,18 @@ dependencies = [ "tokio", ] -[[package]] -name = "backtrace" -version = "0.3.76" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb531853791a215d7c62a30daf0dde835f381ab5de4589cfe7c649d2cbe92bd6" -dependencies = [ - "addr2line", - "cfg-if", - "libc", - "miniz_oxide 0.8.9", - "object 0.37.3", - "rustc-demangle", - "windows-link 0.2.1", -] - [[package]] name = "base16ct" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" +[[package]] +name = "base16ct" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6" + [[package]] name = "base32" version = "0.5.1" @@ -1723,6 +1732,26 @@ dependencies = [ "serde", ] +[[package]] +name = "bindgen" +version = "0.70.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f49d8fed880d473ea71efb9bf597651e77201bdd4893efe54c9e5d65ae04ce6f" +dependencies = [ + "bitflags 2.13.2", + "cexpr", + "clang-sys", + "itertools 0.13.0", + "log", + "prettyplease 0.2.37", + "proc-macro2", + "quote", + "regex", + "rustc-hash 1.1.0", + "shlex 1.3.0", + "syn 2.0.119", +] + [[package]] name = "bindgen" version = "0.71.1" @@ -1981,7 +2010,7 @@ dependencies = [ "prettyplease 0.3.0", "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -2005,7 +2034,7 @@ dependencies = [ "proc-macro-crate", "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -2018,6 +2047,17 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "brotli" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74f7971dbd9326d58187408ab83117d8ac1bb9c17b085fdacd1cf2f598719b6b" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor 4.0.3", +] + [[package]] name = "brotli" version = "7.0.0" @@ -2105,7 +2145,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c719d56f7e96194cfc53460976d3ba51c85719747c9c62ed99981847b551152b" dependencies = [ "rust_decimal", - "schemars 1.2.2", + "schemars 1.2.3", "serde", "utf8-width", ] @@ -2149,7 +2189,7 @@ checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -2212,6 +2252,16 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "calendrical_calculations" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5abbd6eeda6885048d357edc66748eea6e0268e3dd11f326fff5bd248d779c26" +dependencies = [ + "core_maths", + "displaydoc", +] + [[package]] name = "candle-core" version = "0.9.2" @@ -2316,9 +2366,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.6.0" +version = "1.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f74872d07caf508b30a21f6836e7d7016a2eaf7d9ff4f48deaa58cd8a0407630" +checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838" dependencies = [ "find-msvc-tools", "jobserver", @@ -2364,6 +2414,18 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "char_str" +version = "0.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cba78a5abb515610e10af297615434b019755b5d7be14e559ff5340dff50c4" +dependencies = [ + "castaway", + "get-size2", + "itoa", + "ryu", +] + [[package]] name = "chrono" version = "0.4.45" @@ -2459,7 +2521,7 @@ dependencies = [ "heck", "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -2490,11 +2552,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b77c319abfd5219629c45c34c89ba945ed3c5e49fcde9d16b6c3885f118a730" dependencies = [ "const-oid 0.9.6", - "der", - "spki", + "der 0.7.10", + "spki 0.7.3", "x509-cert", ] +[[package]] +name = "collection_literals" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2550f75b8cfac212855f6b1885455df8eaee8fe8e246b647d69146142e016084" + [[package]] name = "colorchoice" version = "1.0.5" @@ -2503,9 +2571,9 @@ checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" [[package]] name = "combine" -version = "4.6.8" +version = "4.6.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" dependencies = [ "bytes", "memchr", @@ -2534,6 +2602,19 @@ dependencies = [ "static_assertions", ] +[[package]] +name = "compact_str" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79fcda08c33bb58b97008b2cdada6622500e949e060f5913361763121abd2416" +dependencies = [ + "castaway", + "cfg-if", + "itoa", + "static_assertions", + "zmij", +] + [[package]] name = "concurrent-queue" version = "2.5.0" @@ -2562,6 +2643,18 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "const-hex" +version = "1.19.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e59eef12462b0f9b0a3620219be5d639afd79fe39dff0a42c3997061f9298b4" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "proptest", + "serde_core", +] + [[package]] name = "const-oid" version = "0.9.6" @@ -2700,6 +2793,27 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "core_maths" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77745e017f5edba1a9c1d854f6f3a52dac8a12dd5af5d2f54aecf61e43d80d30" +dependencies = [ + "libm", +] + +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -2751,6 +2865,12 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "critical-section" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" + [[package]] name = "cron" version = "0.17.0" @@ -2842,6 +2962,22 @@ dependencies = [ "zeroize", ] +[[package]] +name = "crypto-bigint" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a52aa3fcda4e6302a9f48734f234d35d4721b96f8fe07d073f07ce9df4f0271" +dependencies = [ + "cpubits", + "ctutils", + "getrandom 0.4.3", + "hybrid-array", + "num-traits", + "rand_core 0.10.1", + "subtle", + "zeroize", +] + [[package]] name = "crypto-common" version = "0.1.7" @@ -2859,7 +2995,32 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" dependencies = [ + "getrandom 0.4.3", "hybrid-array", + "rand_core 0.10.1", +] + +[[package]] +name = "cssparser" +version = "0.36.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dae61cf9c0abb83bd659dab65b7e4e38d8236824c85f0f804f173567bda257d2" +dependencies = [ + "cssparser-macros", + "dtoa-short", + "itoa", + "phf 0.13.1", + "smallvec", +] + +[[package]] +name = "cssparser-macros" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13b588ba4ac1a99f7f2964d24b3d896ddc6bf847ee3855dbd4366f058cfcd331" +dependencies = [ + "quote", + "syn 2.0.119", ] [[package]] @@ -2899,13 +3060,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "03bb0e1cc970d482d121d9a1744999169b69a07470b3d644a7894e53fcaf4574" dependencies = [ "cmov", + "subtle", ] [[package]] name = "curl-sys" -version = "0.4.90+curl-8.21.0" +version = "0.4.91+curl-8.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97799a0d220bfb3361e0fe4936966ff8c4b24d65c3f06dfc70d7b680b44e7897" +checksum = "cd39579123e45bf762716bb893d43886ed1cabe6289455be29a4f1d4e37afb06" dependencies = [ "cc", "libc", @@ -2926,8 +3088,8 @@ dependencies = [ "cpufeatures 0.2.17", "curve25519-dalek-derive", "digest 0.10.7", - "fiat-crypto 0.2.9", - "rustc_version 0.4.1", + "fiat-crypto", + "rustc_version", "subtle", "zeroize", ] @@ -3058,7 +3220,7 @@ dependencies = [ "proc-macro2", "quote", "strsim 0.11.1", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -3113,7 +3275,7 @@ checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" dependencies = [ "darling_core 0.24.1", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -3764,9 +3926,9 @@ dependencies = [ [[package]] name = "defmt" -version = "1.1.1" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1" +checksum = "e4a0795ac740cb54d7b3775c9c17345f6aaecf884c01733b39d6017738e0e3e1" dependencies = [ "bitflags 1.3.2", "defmt-macros", @@ -3774,21 +3936,21 @@ dependencies = [ [[package]] name = "defmt-macros" -version = "1.1.1" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8" +checksum = "840bb056bd99c495c9188198a258ab787c79f306d864db3e6e8451442d6d8366" dependencies = [ "defmt-parser", "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.9", ] [[package]] name = "defmt-parser" -version = "1.0.0" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e" +checksum = "71958f69fb2de856c5dd51ac9377e986ca1aa5919f931bf5395a807277f889a0" dependencies = [ "thiserror 2.0.21", ] @@ -3801,7 +3963,7 @@ checksum = "c72e0409b3dbd60a5bf296cbc273a8e36bb3a3aab6abac389f1891e187d5ce14" dependencies = [ "base64 0.22.1", "capacity_builder", - "deno_error 0.7.3", + "deno_error", "deno_media_type", "deno_terminal", "dprint-swc-ext", @@ -3835,37 +3997,29 @@ dependencies = [ "url", ] -[[package]] -name = "deno_console" -version = "0.209.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66c0b8a65dcb7b38c22e5969c6454b3cb0839b7dcfb7a4f0d904de871a4c4416" -dependencies = [ - "deno_core", -] - [[package]] name = "deno_core" -version = "0.352.1" +version = "0.412.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf78f3f72ac8e09b18a588bc26a1b3c5ab853e7fb489889b2f5000654d34db5d" +checksum = "580cb2e0d797d75ff3dfc4a8f2b14aa7470f0fa31654a09a83d4cbb42b5eb9b4" dependencies = [ "anyhow", - "az", - "bincode", + "base64 0.22.1", "bit-set", "bit-vec 0.8.0", + "boxed_error", "bytes", - "capacity_builder", "cooked-waker", - "deno_core_icudata", - "deno_error 0.6.1", + "deno_error", "deno_ops", "deno_path_util", "deno_unsync", + "deno_v8", "futures", "indexmap 2.14.2", + "inventory", "libc", + "num-bigint", "parking_lot", "percent-encoding", "pin-project", @@ -3875,28 +4029,25 @@ dependencies = [ "smallvec", "sourcemap", "static_assertions", + "sys_traits", "thiserror 2.0.21", "tokio", "url", - "v8", + "uuid", "wasm_dep_analyzer", + "windows-sys 0.59.0", ] -[[package]] -name = "deno_core_icudata" -version = "0.74.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fe4dccb6147bb3f3ba0c7a48e993bfeb999d2c2e47a81badee80e2b370c8d695" - [[package]] name = "deno_crypto" -version = "0.223.0" +version = "0.273.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "beb2568806b930b96fb6440ff16463befa73a36de3378986644e7134c9d52e8f" +checksum = "d9931d22328961b9a9c8d3b666a27312c1f3ddcc7ea78d8610ddfbc934ac61a0" dependencies = [ "aes 0.8.3", "aes-gcm", "aes-kw", + "argon2", "aws-lc-rs", "base64 0.22.1", "cbc", @@ -3904,12 +4055,15 @@ dependencies = [ "ctr", "curve25519-dalek", "deno_core", - "deno_error 0.6.1", - "deno_web", + "deno_crypto_provider", + "deno_error", "ecdsa", - "ed448-goldilocks", - "elliptic-curve", + "elliptic-curve 0.13.8", + "fips203", + "fips205", + "hmac 0.12.1", "num-traits", + "ocb3", "once_cell", "p256", "p384", @@ -3920,21 +4074,34 @@ dependencies = [ "serde_bytes", "sha1", "sha2 0.10.9", - "signature", - "spki", + "sha3", + "signature 2.2.0", + "spki 0.7.3", + "subtle", "thiserror 2.0.21", + "tiny-keccak", "tokio", "uuid", "x25519-dalek", ] [[package]] -name = "deno_error" -version = "0.6.1" +name = "deno_crypto_provider" +version = "0.53.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "612ec3fc481fea759141b0c57810889b0a4fb6fee8f10748677bfe492fd30486" +checksum = "fafd673e5a4eefd6d65db358b00ff60488cfa1be6515406b4371935c2e2e6baa" dependencies = [ - "deno_error_macro 0.6.1", + "aws-lc-sys 0.40.0", + "ed448-goldilocks", +] + +[[package]] +name = "deno_error" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfafd2219b29886a71aecbb3449e462deed1b2c474dc5b12f855f0e58c478931" +dependencies = [ + "deno_error_macro", "libc", "serde", "serde_json", @@ -3942,32 +4109,11 @@ dependencies = [ "url", ] -[[package]] -name = "deno_error" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3007d3f1ea92ea503324ae15883aac0c2de2b8cf6fead62203ff6a67161007ab" -dependencies = [ - "deno_error_macro 0.7.3", - "libc", -] - [[package]] name = "deno_error_macro" -version = "0.6.1" +version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8380a4224d5d2c3f84da4d764c4326cac62e9a1e3d4960442d29136fc07be863" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "deno_error_macro" -version = "0.7.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b565e60a9685cdf312c888665b5f8647ac692a7da7e058a5e2268a466da8eaf" +checksum = "1c28ede88783f14cd8aae46ca89f230c226b40e4a81ab06fa52ed72af84beb2f" dependencies = [ "proc-macro2", "quote", @@ -3976,31 +4122,30 @@ dependencies = [ [[package]] name = "deno_features" -version = "0.6.0" +version = "0.56.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "487773bb24b92f3b88d1c9ef0d4d15888641a2e2ea4d4cdfd6fda12cae26317c" +checksum = "2fef16a40daeb19acfc5345aa5bb367a36ecffef18b7ad1a594f0f01fe7c20c5" dependencies = [ "deno_core", - "serde", - "serde_json", ] [[package]] name = "deno_fetch" -version = "0.233.0" +version = "0.283.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5cbe158bec955790105ded69978b1245b97c65092f7bf184add344c0e78efffa" +checksum = "20e792f76d45e20cf6f1ad46157bbe1a0a895a6f09ec4d99b0911112be8e05e3" dependencies = [ + "async-compression", "base64 0.22.1", "bytes", "data-url", "deno_core", - "deno_error 0.6.1", + "deno_error", "deno_fs", + "deno_io", "deno_path_util", "deno_permissions", "deno_tls", - "dyn-clone", "error_reporter", "h2 0.4.20", "hickory-resolver", @@ -4011,8 +4156,7 @@ dependencies = [ "hyper-util", "ipnet", "percent-encoding", - "rustls-webpki 0.102.8", - "serde", + "rustls-webpki 0.103.15", "serde_json", "thiserror 2.0.21", "tokio", @@ -4021,62 +4165,69 @@ dependencies = [ "tokio-util", "tokio-vsock", "tower 0.5.3", - "tower-http", "tower-service", ] [[package]] name = "deno_fs" -version = "0.119.0" +version = "0.169.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ca83a95cea7bcdf19dac1888ef6f04aff69d251640a4d085bc6089c06b4b181" +checksum = "a0b0ae3c55f4af9d33113ba4935828a2e9a7bfcbf4d3058533403b9ef332a966" dependencies = [ "async-trait", - "base32", "boxed_error", "deno_core", - "deno_error 0.6.1", + "deno_error", "deno_io", + "deno_maybe_sync", "deno_path_util", "deno_permissions", "filetime", "junction", "libc", - "nix 0.27.1", + "nix 0.30.1", "rand 0.8.5", "rayon", + "same-file", "serde", "thiserror 2.0.21", - "winapi", + "tokio", "windows-sys 0.59.0", ] [[package]] name = "deno_io" -version = "0.119.0" +version = "0.169.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "597aac25be261a1bd545d6f47a80439c60e600c076f9847b3718a592883b2a73" +checksum = "ba495b6c141d34e49fb2dbe7ca746d7ac068b1962470776eb341c59059b758f6" dependencies = [ "async-trait", "deno_core", - "deno_error 0.6.1", + "deno_error", + "deno_permissions", "deno_subprocess_windows", "filetime", - "fs3", "libc", "log", - "nix 0.27.1", - "once_cell", + "nix 0.30.1", "os_pipe", "parking_lot", "pin-project", "rand 0.8.5", "tokio", "uuid", - "winapi", "windows-sys 0.59.0", ] +[[package]] +name = "deno_maybe_sync" +version = "0.46.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57e5e72b38015b5e478b8d739dfa818d563329e03a72d6ce5cfb2ecbcd7f8d41" +dependencies = [ + "rustc-hash 2.1.3", +] + [[package]] name = "deno_media_type" version = "0.3.3" @@ -4103,17 +4254,21 @@ dependencies = [ [[package]] name = "deno_net" -version = "0.201.0" +version = "0.251.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb88f1ea2762065d6cc0316372acc22696ab6004943aa029f80546f9faf1b491" +checksum = "19ba02152d978f30e2eb5f8d074b343363f53cb1364b5c304b3176da916a06c0" dependencies = [ "deno_core", - "deno_error 0.6.1", + "deno_error", "deno_features", "deno_permissions", + "deno_signals", "deno_tls", + "deno_tunnel", "hickory-proto", "hickory-resolver", + "libc", + "log", "pin-project", "quinn", "rustls-tokio-stream", @@ -4125,32 +4280,33 @@ dependencies = [ "tokio-vsock", "url", "web-transport-proto", + "x509-parser 0.15.1", ] [[package]] name = "deno_ops" -version = "0.228.1" +version = "0.288.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8bf8dbe5abf37d270bb853c5dfe45fbe3b1b6c453877cc11d7fe84e9862a6dbc" +checksum = "977748624aad80164dbe385c8c907bc0041c2e6849f92528e362e03132c64c52" dependencies = [ "indexmap 2.14.2", - "proc-macro-rules", "proc-macro2", "quote", "stringcase", "strum", "strum_macros", "syn 2.0.119", + "syn-match", "thiserror 2.0.21", ] [[package]] name = "deno_path_util" -version = "0.4.0" +version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "516f813389095889776b81cc9108ff6f336fd9409b4b12fc0138aea23d2708e1" +checksum = "78c7e98943f0d068928906db0c7bde89de684fa32c6a8018caacc4cee2cdd72b" dependencies = [ - "deno_error 0.6.1", + "deno_error", "percent-encoding", "sys_traits", "thiserror 2.0.21", @@ -4159,77 +4315,100 @@ dependencies = [ [[package]] name = "deno_permissions" -version = "0.68.0" +version = "0.118.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baa14d9c3fbba59836ffbaac7f736a2f48d4a5fc209a2103d1e1b898915232a5" +checksum = "f8e9d37215f52e29b5ad9d9065c476168ffb888cd2ad93b0ae153f22304851a0" dependencies = [ "capacity_builder", - "deno_error 0.6.1", + "chrono", + "deno_error", "deno_path_util", "deno_terminal", "deno_unsync", + "dunce", "fqdn", - "ipnetwork", + "ipnet", "libc", "log", - "nix 0.27.1", + "nix 0.30.1", "once_cell", "parking_lot", - "percent-encoding", "serde", "serde_json", "sys_traits", - "temp_deno_which", "thiserror 2.0.21", + "unicode-normalization", "url", - "winapi", + "which 8.0.6", + "windows-sys 0.59.0", +] + +[[package]] +name = "deno_signals" +version = "0.50.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "038ed4b09a6d36c81ac436c4d10076e9e01cc67faf93d701c541887f8eeddf36" +dependencies = [ + "libc", + "signal-hook", + "thiserror 2.0.21", + "tokio", "windows-sys 0.59.0", ] [[package]] name = "deno_subprocess_windows" -version = "0.4.0" +version = "0.54.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7bc6b10059f0ccb14c6e0319c5275f0407fb2f9ffe405cd555700561999ea4bf" +checksum = "04d4f451b2f94d2847de4895d39ca5aa264b90af34e72fd79ddc1d0da05a5ea0" dependencies = [ - "fastrand 2.5.0", "futures-channel", "libc", + "rand 0.8.5", "windows-sys 0.59.0", ] [[package]] name = "deno_telemetry" -version = "0.31.0" +version = "0.81.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "377581966bd34e85ce230f7f4b1dee7e16c6bf7f845b4690648507ce7ba105d9" +checksum = "8831dc236ed1c66a90c8dfddab93ad44fbb28950fc476c78306b9100233ff694" dependencies = [ "async-trait", "deno_core", - "deno_error 0.6.1", + "deno_error", + "deno_net", + "deno_signals", + "deno_terminal", "deno_tls", + "flate2", "http-body-util", "hyper 1.12.0", "hyper-rustls 0.27.10", "hyper-util", "log", "once_cell", - "opentelemetry 0.27.1", - "opentelemetry-http 0.27.0", - "opentelemetry-otlp 0.27.0", - "opentelemetry-semantic-conventions 0.27.0", - "opentelemetry_sdk 0.27.1", + "opentelemetry 0.32.0", + "opentelemetry-http 0.32.0", + "opentelemetry-otlp 0.32.0", + "opentelemetry-proto 0.32.0", + "opentelemetry-semantic-conventions 0.32.1", + "opentelemetry_sdk 0.32.1", "pin-project", + "prost 0.14.4", "serde", + "sys_traits", "thiserror 2.0.21", "tokio", + "tokio-vsock", + "tower-service", ] [[package]] name = "deno_terminal" -version = "0.2.2" +version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "23f71c27009e0141dedd315f1dfa3ebb0a6ca4acce7c080fac576ea415a465f6" +checksum = "f3ba8041ae7319b3ca6a64c399df4112badcbbe0868b4517637647614bede4be" dependencies = [ "once_cell", "termcolor", @@ -4237,23 +4416,40 @@ dependencies = [ [[package]] name = "deno_tls" -version = "0.196.0" +version = "0.246.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a7835eb6a8d114703b0293573fbb8885bc2c81e8c35363b9e89391dd3c541fa6" +checksum = "6229f7a00441b2acbf7fae58dd14bded0e835f212653402083430826e640f99d" dependencies = [ "deno_core", - "deno_error 0.6.1", + "deno_error", "deno_native_certs", - "rustls 0.23.35", + "log", + "rustls 0.23.40", "rustls-pemfile 2.2.0", "rustls-tokio-stream", - "rustls-webpki 0.102.8", + "rustls-webpki 0.103.15", "serde", "thiserror 2.0.21", "tokio", "webpki-roots 0.26.11", ] +[[package]] +name = "deno_tunnel" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e432929e0c167f2a003b963ee406c714fcd947a87d4f9edc7b3255e87be9881d" +dependencies = [ + "pin-project", + "quinn", + "serde", + "serde_json", + "socket2 0.6.5", + "thiserror 2.0.21", + "tokio", + "tracing", +] + [[package]] name = "deno_unsync" version = "0.4.4" @@ -4266,42 +4462,43 @@ dependencies = [ ] [[package]] -name = "deno_url" -version = "0.209.0" +name = "deno_v8" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8cccbb10fb59f29b04161055a65f7fe83364f9e8317d4d2ce3bd7979faf63a87" +checksum = "85cdff08dedf79da6a40f97554f47d59d419ba3df8061b8b31789cd2cbe00433" dependencies = [ - "deno_core", - "deno_error 0.6.1", - "urlpattern", + "v8", + "v8x", ] [[package]] name = "deno_web" -version = "0.240.0" +version = "0.290.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d6b8a97cc90b6aaea20fe200cfa7e5b6953dd33ecda0af50d6d360387c33df4" +checksum = "7510967ba4ec695959c1a518748c3b564fd9ca7a8f3eb13bd397707a3ca232da" dependencies = [ "async-trait", - "base64-simd", + "brotli 6.0.0", "bytes", + "cssparser", "deno_core", - "deno_error 0.6.1", - "deno_permissions", + "deno_error", "encoding_rs", "flate2", "futures", "serde", "thiserror 2.0.21", "tokio", + "unicode-normalization", + "urlpattern", "uuid", ] [[package]] name = "deno_webidl" -version = "0.209.0" +version = "0.259.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a20bbfac0cf15918f7cbd0b55c366ac20ad65c825f362fa684c3104984254d3b" +checksum = "40af42313723a8d3114c4e5b007abd1cab4400a0b68929794c556b2e792409c7" dependencies = [ "deno_core", ] @@ -4319,6 +4516,30 @@ dependencies = [ "zeroize", ] +[[package]] +name = "der" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a878c850e9e421b20262e9b41f9c860e4785fa07541c266b62ff9d1ef998a80a" +dependencies = [ + "const-oid 0.10.2", + "zeroize", +] + +[[package]] +name = "der-parser" +version = "8.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbd676fbbab537128ef0278adb5576cf363cff6aa22a7b24effe97347cfab61e" +dependencies = [ + "asn1-rs 0.5.2", + "displaydoc", + "nom", + "num-bigint", + "num-traits", + "rusticata-macros", +] + [[package]] name = "der-parser" version = "9.0.0" @@ -4360,13 +4581,32 @@ dependencies = [ [[package]] name = "deranged" -version = "0.5.8" +version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" dependencies = [ "serde_core", ] +[[package]] +name = "derive-io" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58cc7f4740088458993d183a200fe56e62378736f94bf0e2dd45807407e7bb94" +dependencies = [ + "derive-io-macros", + "tokio", +] + +[[package]] +name = "derive-io-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d0a1bd7eeab72097740967d03d53db5fbaf8e3c0dd471ebdefa43ce445a20a6" +dependencies = [ + "proc-macro2", +] + [[package]] name = "derive_builder" version = "0.12.0" @@ -4456,7 +4696,6 @@ dependencies = [ "proc-macro2", "quote", "syn 2.0.119", - "unicode-xid", ] [[package]] @@ -4467,7 +4706,7 @@ checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" dependencies = [ "proc-macro2", "quote", - "rustc_version 0.4.1", + "rustc_version", "syn 2.0.119", ] @@ -4524,6 +4763,38 @@ dependencies = [ "ctutils", ] +[[package]] +name = "diplomat" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8b37a6cea72eb6df5143d3e091d4c34cb0cf4046dd1ddcc082988886fe1f809" +dependencies = [ + "diplomat_core", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "diplomat-runtime" +version = "0.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae517853d9f82b2d144393b1c32c34c46c2e361de2b6c44a8fdfce23beb211cd" + +[[package]] +name = "diplomat_core" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73b18e806f9ecb92df828d080efe47984ae1193958295d4a84fb8b32c9a1aa1b" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "smallvec", + "strck", + "syn 3.0.9", +] + [[package]] name = "dirs" version = "4.0.0" @@ -4615,7 +4886,7 @@ checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -4681,6 +4952,27 @@ dependencies = [ "text_lines", ] +[[package]] +name = "drop_bomb" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bda8e21c04aca2ae33ffc2fd8c23134f3cac46db123ba97bd9d3f3b8a4a85e1" + +[[package]] +name = "dtoa" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c3cf4824e2d5f025c7b531afcb2325364084a16806f6d47fbc1f5fbd9960590" + +[[package]] +name = "dtoa-short" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd1511a7b6a56299bd043a9c167a6d2bfb37bf84a6dfceaba651168adfb43c87" +dependencies = [ + "dtoa", +] + [[package]] name = "duct" version = "0.13.7" @@ -4727,12 +5019,12 @@ version = "0.16.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" dependencies = [ - "der", + "der 0.7.10", "digest 0.10.7", - "elliptic-curve", + "elliptic-curve 0.13.8", "rfc6979", - "signature", - "spki", + "signature 2.2.0", + "spki 0.7.3", ] [[package]] @@ -4741,8 +5033,8 @@ version = "2.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" dependencies = [ - "pkcs8", - "signature", + "pkcs8 0.10.2", + "signature 2.2.0", ] [[package]] @@ -4756,21 +5048,35 @@ dependencies = [ "rand_core 0.6.4", "serde", "sha2 0.10.9", - "signature", + "signature 2.2.0", "subtle", "zeroize", ] [[package]] -name = "ed448-goldilocks" -version = "0.8.3" +name = "ed448" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06924531e9e90130842b012e447f85bdaf9161bc8a0f8092be8cb70b01ebe092" +checksum = "ae112a25f86ae3598d4e8533ed1e65149cec6eb21918e7a6f4c06dddec370263" dependencies = [ - "fiat-crypto 0.1.20", - "hex", + "pkcs8 0.11.0", + "signature 3.0.0", +] + +[[package]] +name = "ed448-goldilocks" +version = "0.14.0-pre.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b805154de2e68f59874ec217ca36790dcffe500cd872c60fe509d28d0814a74d" +dependencies = [ + "ed448", + "elliptic-curve 0.14.1", + "hash2curve", + "rand_core 0.10.1", + "serdect 0.4.3", + "shake", + "signature 3.0.0", "subtle", - "zeroize", ] [[package]] @@ -4800,20 +5106,39 @@ version = "0.13.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" dependencies = [ - "base16ct", + "base16ct 0.2.0", "base64ct", - "crypto-bigint", + "crypto-bigint 0.5.5", "digest 0.10.7", - "ff", + "ff 0.13.1", "generic-array", - "group", + "group 0.13.0", "hkdf", "pem-rfc7468", - "pkcs8", + "pkcs8 0.10.2", "rand_core 0.6.4", - "sec1", + "sec1 0.7.3", "serde_json", - "serdect", + "serdect 0.2.0", + "subtle", + "zeroize", +] + +[[package]] +name = "elliptic-curve" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d65aa39b3a5c1c9c1b745c9a019234bb7a21b77abcb4f4d266d706e2d577d65" +dependencies = [ + "base16ct 1.0.0", + "crypto-bigint 0.7.5", + "crypto-common 0.2.2", + "ff 0.14.0", + "group 0.14.0", + "hybrid-array", + "pkcs8 0.11.0", + "rand_core 0.10.1", + "sec1 0.8.1", "subtle", "zeroize", ] @@ -4862,7 +5187,7 @@ checksum = "a65863d15a4ce2888bd2f0f543cc963d3879c3a022c8ee43f6141d479a3ac815" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -4887,9 +5212,9 @@ dependencies = [ [[package]] name = "equivalent" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" [[package]] name = "erased-serde" @@ -5012,6 +5337,18 @@ dependencies = [ "regex-syntax 0.8.11", ] +[[package]] +name = "fastbloom" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef975e30683b2d965054bb0a836f8973857c4ebf6acf274fe46617cd285060d8" +dependencies = [ + "foldhash 0.2.0", + "libm", + "portable-atomic", + "siphasher 1.0.4", +] + [[package]] name = "fastdivide" version = "0.4.2" @@ -5044,10 +5381,14 @@ dependencies = [ ] [[package]] -name = "fiat-crypto" -version = "0.1.20" +name = "ff" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e825f6987101665dea6ec934c09ec6d721de7bc1bf92248e1d5810c8cd636b77" +checksum = "a1f686ab92a9fb0eaf188f6c6c87b89490baa6fdb0db4544ba4dc47f7942489f" +dependencies = [ + "rand_core 0.10.1", + "subtle", +] [[package]] name = "fiat-crypto" @@ -5071,6 +5412,30 @@ version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" +[[package]] +name = "fips203" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8bdb6454f692ca2a2b45cd554c6828c639d7f9c968cf83a678899ec4443a280" +dependencies = [ + "rand_core 0.6.4", + "sha3", + "subtle", + "zeroize", +] + +[[package]] +name = "fips205" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f5626bf5534df4ebdbd2536465d7eaa8a9dc2cdeb7e036e0ecf291dcc80ffb6" +dependencies = [ + "rand_core 0.6.4", + "sha2 0.10.9", + "sha3", + "zeroize", +] + [[package]] name = "fixedbitset" version = "0.5.7" @@ -5090,7 +5455,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "35f6839d7b3b98adde531effaf34f0c2badc6f4735d26fe74709d8e513a96ef3" dependencies = [ "bitflags 2.13.2", - "rustc_version 0.4.1", + "rustc_version", ] [[package]] @@ -5173,9 +5538,9 @@ dependencies = [ [[package]] name = "fqdn" -version = "0.3.12" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb540cf7bc4fe6df9d8f7f0c974cfd0dce8ed4e9e8884e73433b503ee78b4e7d" +checksum = "886ac788f62d16d6b0f26b2fa762b34ef16ebfb4b624c2c15fbcadc9173c0f72" [[package]] name = "from_variant" @@ -5189,20 +5554,9 @@ dependencies = [ [[package]] name = "frostem" -version = "1.20260821.7" +version = "1.20260821.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "28c70238056ad1dbfdf035222a571d2e9baf5b6a4c308cfa87bc8cbe7f2f3840" - -[[package]] -name = "fs3" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fb17cf6ed704f72485332f6ab65257460c4f9f3083934cf402bf9f5b3b600a90" -dependencies = [ - "libc", - "rustc_version 0.2.3", - "winapi", -] +checksum = "9e2488a10218a17366ce6bd38b6d081b4387a9548d350029db9feddc9bb44d6d" [[package]] name = "fs4" @@ -5331,7 +5685,7 @@ checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -5509,9 +5863,9 @@ dependencies = [ [[package]] name = "generator" -version = "0.8.10" +version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54ade96dc9003043bce7c035c85a9df5a858bfb2039c5a2e6fdf00f324f6c551" +checksum = "1be81b31c9ce4caf7f3178eeb90662bb1864d3ad363ec6bdada3201adff19c37" dependencies = [ "cc", "cfg-if", @@ -5533,6 +5887,31 @@ dependencies = [ "zeroize", ] +[[package]] +name = "get-size-derive2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28f0daa179069133df60523e0f59d0a6bd2d3db9ccae01b630896d269c4a802e" +dependencies = [ + "attribute-derive", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "get-size2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "050a5d07359ebfac7f0b74916d94cfa30575e45fdc7e9bfbb0f76d5d4203325a" +dependencies = [ + "compact_str 0.10.0", + "get-size-derive2", + "hashbrown 0.17.1", + "ordermap", + "smallvec", + "thin-vec", +] + [[package]] name = "gethostname" version = "0.4.3" @@ -5614,12 +5993,6 @@ dependencies = [ "polyval", ] -[[package]] -name = "gimli" -version = "0.32.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7" - [[package]] name = "git-version" version = "0.3.9" @@ -5721,7 +6094,7 @@ version = "0.16.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "886aa8ec755382a1fdf4651f6e6ec01f2f3bf49f2cb0f068b9a74cafd574a715" dependencies = [ - "prost", + "prost 0.13.5", "prost-types", "tonic 0.12.3", ] @@ -5783,11 +6156,22 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" dependencies = [ - "ff", + "ff 0.13.1", "rand_core 0.6.4", "subtle", ] +[[package]] +name = "group" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fd1a1c7a5206c5b7a3f5a0d7ccd3ff85d0c8f5133d62a02680255b0004af5f4" +dependencies = [ + "ff 0.14.0", + "rand_core 0.10.1", + "subtle", +] + [[package]] name = "gzip-header" version = "1.1.0" @@ -5850,6 +6234,16 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "hash2curve" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1eaf40612d7d854743e7189228a6d528f0f6e8502cf6a0cb831d28a218b7f3f6" +dependencies = [ + "digest 0.11.3", + "elliptic-curve 0.14.1", +] + [[package]] name = "hashbrown" version = "0.12.3" @@ -5997,11 +6391,10 @@ dependencies = [ [[package]] name = "hickory-proto" -version = "0.25.0-alpha.5" +version = "0.25.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d00147af6310f4392a31680db52a3ed45a2e0f68eb18e8c3fe5537ecc96d9e2" +checksum = "f8a6fe56c0038198998a6f217ca4e7ef3a5e51f46163bd6dd60b5c71ca6c6502" dependencies = [ - "async-recursion", "async-trait", "cfg-if", "data-encoding", @@ -6013,6 +6406,7 @@ dependencies = [ "ipnet", "once_cell", "rand 0.9.5", + "ring 0.17.14", "serde", "thiserror 2.0.21", "tinyvec", @@ -6023,9 +6417,9 @@ dependencies = [ [[package]] name = "hickory-resolver" -version = "0.25.0-alpha.5" +version = "0.25.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5762f69ebdbd4ddb2e975cd24690bf21fe6b2604039189c26acddbc427f12887" +checksum = "dc62a9a99b0bfb44d2ab95a7208ac952d31060efc16241c87eaf36406fecf87a" dependencies = [ "cfg-if", "futures-util", @@ -6217,7 +6611,9 @@ version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" dependencies = [ + "subtle", "typenum", + "zeroize", ] [[package]] @@ -6344,8 +6740,8 @@ dependencies = [ "hyper 1.12.0", "hyper-util", "log", - "rustls 0.23.35", - "rustls-native-certs 0.8.4", + "rustls 0.23.40", + "rustls-native-certs 0.8.5", "tokio", "tokio-rustls 0.26.6", "tower-service", @@ -6461,6 +6857,28 @@ dependencies = [ "cc", ] +[[package]] +name = "icu_calendar" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58655df2f728e46e4eee80bddebefacf52ec3e77cdb925014b47c5a5905eb55c" +dependencies = [ + "calendrical_calculations", + "displaydoc", + "icu_calendar_data", + "icu_locale_core", + "icu_locale_fallback", + "icu_provider", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_calendar_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc00caaa3fb3201ff7a18aa458e8c3ab042b9da154cfdf948bdde3936c31c36e" + [[package]] name = "icu_collections" version = "2.3.0" @@ -6684,10 +7102,16 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8bb03732005da905c88227371639bf1ad885cc712789c011c31c5fb3ab3ccf02" [[package]] -name = "inventory" -version = "0.3.24" +name = "interpolator" +version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4f0c30c76f2f4ccee3fe55a2435f691ca00c0e4bd87abe4f4a851b1d4dac39b" +checksum = "71dd52191aae121e8611f1e8dc3e324dd0dd1dee1e6dd91d10ee07a3cfb4d9d8" + +[[package]] +name = "inventory" +version = "0.3.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6928282826c822ad91bf1c9a1cb90a30ba1c26770749929b4656cd6be829cd7c" dependencies = [ "rustversion", ] @@ -6703,17 +7127,6 @@ dependencies = [ "windows-sys 0.48.0", ] -[[package]] -name = "io-uring" -version = "0.7.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed3bd0ecfbb87805f538bb7b32e5239ca0763890c623e349860ecba69469f2bb" -dependencies = [ - "bitflags 2.13.2", - "cfg-if", - "libc", -] - [[package]] name = "ipconfig" version = "0.3.4" @@ -6733,15 +7146,6 @@ version = "2.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" -[[package]] -name = "ipnetwork" -version = "0.20.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf466541e9d546596ee94f9f69590f89473455f88372423e0008fc1a7daf100e" -dependencies = [ - "serde", -] - [[package]] name = "is-macro" version = "0.3.8" @@ -6802,12 +7206,27 @@ dependencies = [ "either", ] +[[package]] +name = "itertools" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "ixdtf" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d3667095d64c3ecffc96463a21157b04bf3e252f6e8d5750b20c02e33c194e3" + [[package]] name = "jiff" version = "0.2.38" @@ -6887,7 +7306,7 @@ checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" dependencies = [ "proc-macro2", "quote", - "rustc_version 0.4.1", + "rustc_version", "simd_cesu8", "syn 2.0.119", ] @@ -6995,7 +7414,7 @@ dependencies = [ "pem", "serde", "serde_json", - "signature", + "signature 2.2.0", "simple_asn1", "zeroize", ] @@ -7022,6 +7441,25 @@ dependencies = [ "serde_json", ] +[[package]] +name = "keccak" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb26cec98cce3a3d96cbb7bced3c4b16e3d13f27ec56dbd62cbc8f39cfb9d653" +dependencies = [ + "cpufeatures 0.2.17", +] + +[[package]] +name = "keccak" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8f198d1db720e4940b5a493201d199d9f24f568f8f746bd13706243a2f71598" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", +] + [[package]] name = "keyed_priority_queue" version = "0.4.2" @@ -7093,7 +7531,7 @@ dependencies = [ "k8s-openapi", "kube-core", "pem", - "rustls 0.23.35", + "rustls 0.23.40", "secrecy", "serde", "serde_json", @@ -7166,12 +7604,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "lalrpop-util" -version = "0.20.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "507460a910eb7b32ee961886ff48539633b788a36b65692b95f225b844c82553" - [[package]] name = "lapin" version = "2.5.5" @@ -7268,9 +7700,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.190" +version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" [[package]] name = "libffi-sys" @@ -7339,7 +7771,7 @@ dependencies = [ "bitflags 2.13.2", "libc", "plain", - "redox_syscall 0.9.4", + "redox_syscall 0.9.5", ] [[package]] @@ -7375,9 +7807,9 @@ dependencies = [ [[package]] name = "libz-sys" -version = "1.1.29" +version = "1.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85bc9657773828b90eeb625adff10eeac83cc21bbfd8e23a03eaa8a33c9e28d9" +checksum = "f710a23e6dbf193214fd46ca56a9d6864e550abe86202184532ae7275e46de19" dependencies = [ "cc", "libc", @@ -7582,7 +8014,7 @@ dependencies = [ "base64 0.22.1", "gethostname", "mail-builder", - "rustls 0.23.35", + "rustls 0.23.40", "rustls-pki-types", "smtp-proto", "tokio", @@ -7590,76 +8022,30 @@ dependencies = [ "webpki-roots 0.26.11", ] -[[package]] -name = "malachite" -version = "0.4.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2fbdf9cb251732db30a7200ebb6ae5d22fe8e11397364416617d2c2cf0c51cb5" -dependencies = [ - "malachite-base", - "malachite-nz", - "malachite-q", -] - -[[package]] -name = "malachite-base" -version = "0.4.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ea0ed76adf7defc1a92240b5c36d5368cfe9251640dcce5bd2d0b7c1fd87aeb" -dependencies = [ - "hashbrown 0.14.5", - "itertools 0.11.0", - "libm", - "ryu", -] - -[[package]] -name = "malachite-bigint" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d149aaa2965d70381709d9df4c7ee1fc0de1c614a4efc2ee356f5e43d68749f8" -dependencies = [ - "derive_more 1.0.0", - "malachite", - "num-integer", - "num-traits", - "paste", -] - -[[package]] -name = "malachite-nz" -version = "0.4.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34a79feebb2bc9aa7762047c8e5495269a367da6b5a90a99882a0aeeac1841f7" -dependencies = [ - "itertools 0.11.0", - "libm", - "malachite-base", -] - -[[package]] -name = "malachite-q" -version = "0.4.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50f235d5747b1256b47620f5640c2a17a88c7569eebdf27cd9cb130e1a619191" -dependencies = [ - "itertools 0.11.0", - "malachite-base", - "malachite-nz", -] - [[package]] name = "manyhow" version = "0.11.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b33efb3ca6d3b07393750d4030418d594ab1139cee518f0dc88db70fec873587" dependencies = [ - "manyhow-macros", + "manyhow-macros 0.11.4", "proc-macro2", "quote", "syn 2.0.119", ] +[[package]] +name = "manyhow" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1704b073316272a6785b70599f91f73b49022c2e290b065591ee6b9109ed8c7" +dependencies = [ + "manyhow-macros 0.14.1", + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "manyhow-macros" version = "0.11.4" @@ -7671,6 +8057,17 @@ dependencies = [ "quote", ] +[[package]] +name = "manyhow-macros" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31601db71f1f5fb6f831a18aa3052d13a62528ee4f2cba7e8c9a5e258d953725" +dependencies = [ + "proc-macro-utils", + "proc-macro2", + "quote", +] + [[package]] name = "mappable-rc" version = "0.1.1" @@ -7938,7 +8335,7 @@ checksum = "a4db8a44120571277accfaa3f3d91e7d3989d601d817c2fc01a9391b86135666" dependencies = [ "darling 0.23.0", "heck", - "manyhow", + "manyhow 0.11.4", "num-bigint", "proc-macro-crate", "proc-macro2", @@ -8072,6 +8469,7 @@ dependencies = [ "cfg-if", "cfg_aliases", "libc", + "memoffset", ] [[package]] @@ -8291,7 +8689,6 @@ checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" dependencies = [ "num-integer", "num-traits", - "rand 0.8.5", "serde", ] @@ -8435,15 +8832,6 @@ dependencies = [ "url", ] -[[package]] -name = "object" -version = "0.37.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff76201f031d8863c38aa7f905eca4f53abbfa15f609db4277d44cd8938f33fe" -dependencies = [ - "memchr", -] - [[package]] name = "object" version = "0.39.1" @@ -8490,6 +8878,18 @@ dependencies = [ "web-time", ] +[[package]] +name = "ocb3" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c196e0276c471c843dd5777e7543a36a298a4be942a2a688d8111cd43390dedb" +dependencies = [ + "aead", + "cipher 0.4.4", + "ctr", + "subtle", +] + [[package]] name = "odpic-sys" version = "0.1.1" @@ -8499,6 +8899,15 @@ dependencies = [ "cc", ] +[[package]] +name = "oid-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bedf36ffb6ba96c2eb7144ef6270557b52e54b20c0a8e1eb2ff99a6c6959bff" +dependencies = [ + "asn1-rs 0.5.2", +] + [[package]] name = "oid-registry" version = "0.7.1" @@ -8528,6 +8937,10 @@ name = "once_cell" version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +dependencies = [ + "critical-section", + "portable-atomic", +] [[package]] name = "once_cell_polyfill" @@ -8667,23 +9080,23 @@ dependencies = [ [[package]] name = "opentelemetry" -version = "0.27.1" +version = "0.30.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab70038c28ed37b97d8ed414b6429d343a8bbf44c9f79ec854f3a643029ba6d7" +checksum = "aaf416e4cb72756655126f7dd7bb0af49c674f4c1b9903e80c009e0c37e552e6" dependencies = [ "futures-core", "futures-sink", "js-sys", "pin-project-lite", - "thiserror 1.0.69", + "thiserror 2.0.21", "tracing", ] [[package]] name = "opentelemetry" -version = "0.30.0" +version = "0.32.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aaf416e4cb72756655126f7dd7bb0af49c674f4c1b9903e80c009e0c37e552e6" +checksum = "b0142c63252a9e054e68a4c61a5778f7b14f576274d593f8ce883d191a099682" dependencies = [ "futures-core", "futures-sink", @@ -8705,18 +9118,6 @@ dependencies = [ "tracing-subscriber", ] -[[package]] -name = "opentelemetry-http" -version = "0.27.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10a8a7f5f6ba7c1b286c2fbca0454eaba116f63bbe69ed250b642d36fbb04d80" -dependencies = [ - "async-trait", - "bytes", - "http 1.5.0", - "opentelemetry 0.27.1", -] - [[package]] name = "opentelemetry-http" version = "0.30.0" @@ -8731,24 +9132,15 @@ dependencies = [ ] [[package]] -name = "opentelemetry-otlp" -version = "0.27.0" +name = "opentelemetry-http" +version = "0.32.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91cf61a1868dacc576bf2b2a1c3e9ab150af7272909e80085c3173384fe11f76" +checksum = "5683015d09e2df236ef005b17f6f196f0d5f6313c4fa43a7b6a53b52776e4331" dependencies = [ "async-trait", - "futures-core", + "bytes", "http 1.5.0", - "opentelemetry 0.27.1", - "opentelemetry-http 0.27.0", - "opentelemetry-proto 0.27.0", - "opentelemetry_sdk 0.27.1", - "prost", - "serde_json", - "thiserror 1.0.69", - "tokio", - "tonic 0.12.3", - "tracing", + "opentelemetry 0.32.0", ] [[package]] @@ -8762,7 +9154,7 @@ dependencies = [ "opentelemetry-http 0.30.0", "opentelemetry-proto 0.30.0", "opentelemetry_sdk 0.30.0", - "prost", + "prost 0.13.5", "reqwest 0.12.28", "thiserror 2.0.21", "tokio", @@ -8771,17 +9163,19 @@ dependencies = [ ] [[package]] -name = "opentelemetry-proto" -version = "0.27.0" +name = "opentelemetry-otlp" +version = "0.32.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a6e05acbfada5ec79023c85368af14abd0b307c015e9064d249b2a950ef459a6" +checksum = "9966929966d17620d7c316c643ba62631826e10021409357772d5eea84f62c35" dependencies = [ - "hex", - "opentelemetry 0.27.1", - "opentelemetry_sdk 0.27.1", - "prost", - "serde", - "tonic 0.12.3", + "http 1.5.0", + "opentelemetry 0.32.0", + "opentelemetry-http 0.32.0", + "opentelemetry-proto 0.32.0", + "opentelemetry_sdk 0.32.1", + "prost 0.14.4", + "serde_json", + "thiserror 2.0.21", ] [[package]] @@ -8794,16 +9188,24 @@ dependencies = [ "hex", "opentelemetry 0.30.0", "opentelemetry_sdk 0.30.0", - "prost", + "prost 0.13.5", "serde", "tonic 0.13.1", ] [[package]] -name = "opentelemetry-semantic-conventions" -version = "0.27.0" +name = "opentelemetry-proto" +version = "0.32.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bc1b6902ff63b32ef6c489e8048c5e253e2e4a803ea3ea7e783914536eb15c52" +checksum = "56d658ba1faf63f7b9c492cfbe6e0ec365440a16132d3270c1065f7b33f1b638" +dependencies = [ + "base64 0.22.1", + "const-hex", + "opentelemetry 0.32.0", + "opentelemetry_sdk 0.32.1", + "prost 0.14.4", + "serde", +] [[package]] name = "opentelemetry-semantic-conventions" @@ -8812,25 +9214,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "83d059a296a47436748557a353c5e6c5705b9470ef6c95cfc52c21a8814ddac2" [[package]] -name = "opentelemetry_sdk" -version = "0.27.1" +name = "opentelemetry-semantic-conventions" +version = "0.32.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "231e9d6ceef9b0b2546ddf52335785ce41252bc7474ee8ba05bfad277be13ab8" -dependencies = [ - "async-trait", - "futures-channel", - "futures-executor", - "futures-util", - "glob", - "opentelemetry 0.27.1", - "percent-encoding", - "rand 0.8.5", - "serde_json", - "thiserror 1.0.69", - "tokio", - "tokio-stream", - "tracing", -] +checksum = "c913ac17a6c451661ee255f4625d143e51647ae78ebd969b75e41c4442f4fe47" [[package]] name = "opentelemetry_sdk" @@ -8850,6 +9237,24 @@ dependencies = [ "tokio-stream", ] +[[package]] +name = "opentelemetry_sdk" +version = "0.32.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b59f80e1ac4d5ff7a2db8fb6c80badb7f0f3f858211fba08dd9aaec750894f9" +dependencies = [ + "futures-channel", + "futures-executor", + "futures-util", + "opentelemetry 0.32.0", + "percent-encoding", + "portable-atomic", + "rand 0.9.5", + "thiserror 2.0.21", + "tokio", + "tokio-stream", +] + [[package]] name = "option-ext" version = "0.2.0" @@ -8901,6 +9306,15 @@ dependencies = [ "num-traits", ] +[[package]] +name = "ordermap" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a756ddcdeb6c0efc8927bdf0ed112885815a35ba350472a467be5104f01ca1" +dependencies = [ + "indexmap 2.14.2", +] + [[package]] name = "os_pipe" version = "1.2.1" @@ -8939,7 +9353,7 @@ checksum = "3cae83056e7cb770211494a0ecf66d9fa7eba7d00977e5bb91f0e925b40b937f" dependencies = [ "cbc", "cms", - "der", + "der 0.7.10", "des 0.8.1", "hex", "hmac 0.12.1", @@ -8960,7 +9374,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" dependencies = [ "ecdsa", - "elliptic-curve", + "elliptic-curve 0.13.8", "primeorder", "sha2 0.10.9", ] @@ -8972,7 +9386,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6" dependencies = [ "ecdsa", - "elliptic-curve", + "elliptic-curve 0.13.8", "primeorder", "sha2 0.10.9", ] @@ -8983,9 +9397,9 @@ version = "0.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fc9e2161f1f215afdfce23677034ae137bbd45016a880c2eb3ba8eb95f085b2" dependencies = [ - "base16ct", + "base16ct 0.2.0", "ecdsa", - "elliptic-curve", + "elliptic-curve 0.13.8", "primeorder", "rand_core 0.6.4", "sha2 0.10.9", @@ -9224,7 +9638,7 @@ version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" dependencies = [ - "phf_macros", + "phf_macros 0.11.3", "phf_shared 0.11.3", ] @@ -9243,6 +9657,7 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" dependencies = [ + "phf_macros 0.13.1", "phf_shared 0.13.1", "serde", ] @@ -9253,7 +9668,7 @@ version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aef8048c789fa5e851558d709946d6d79a8ff88c0440c587967f8e94bfb1216a" dependencies = [ - "phf_generator", + "phf_generator 0.11.3", "phf_shared 0.11.3", ] @@ -9267,19 +9682,42 @@ dependencies = [ "rand 0.8.5", ] +[[package]] +name = "phf_generator" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" +dependencies = [ + "fastrand 2.5.0", + "phf_shared 0.13.1", +] + [[package]] name = "phf_macros" version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f84ac04429c13a7ff43785d75ad27569f2951ce0ffd30a3321230db2fc727216" dependencies = [ - "phf_generator", + "phf_generator 0.11.3", "phf_shared 0.11.3", "proc-macro2", "quote", "syn 2.0.119", ] +[[package]] +name = "phf_macros" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" +dependencies = [ + "phf_generator 0.13.1", + "phf_shared 0.13.1", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "phf_shared" version = "0.11.3" @@ -9380,9 +9818,9 @@ version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" dependencies = [ - "der", - "pkcs8", - "spki", + "der 0.7.10", + "pkcs8 0.10.2", + "spki 0.7.3", ] [[package]] @@ -9393,9 +9831,9 @@ checksum = "695b3df3d3cc1015f12d70235e35b6b79befc5fa7a9b95b951eab1dd07c9efc2" dependencies = [ "cms", "const-oid 0.9.6", - "der", + "der 0.7.10", "digest 0.10.7", - "spki", + "spki 0.7.3", "x509-cert", "zeroize", ] @@ -9408,11 +9846,11 @@ checksum = "e847e2c91a18bfa887dd028ec33f2fe6f25db77db3619024764914affe8b69a6" dependencies = [ "aes 0.8.3", "cbc", - "der", + "der 0.7.10", "pbkdf2", "scrypt", "sha2 0.10.9", - "spki", + "spki 0.7.3", ] [[package]] @@ -9421,8 +9859,18 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" dependencies = [ - "der", - "spki", + "der 0.7.10", + "spki 0.7.3", +] + +[[package]] +name = "pkcs8" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7" +dependencies = [ + "der 0.8.2", + "spki 0.8.1", ] [[package]] @@ -9530,7 +9978,7 @@ dependencies = [ "md-5 0.11.0", "memchr", "rand 0.10.3", - "sha2 0.11.0", + "sha2 0.11.1", "stringprep", ] @@ -9599,7 +10047,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0" dependencies = [ "proc-macro2", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -9608,7 +10056,7 @@ version = "0.13.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" dependencies = [ - "elliptic-curve", + "elliptic-curve 0.13.8", ] [[package]] @@ -9617,7 +10065,7 @@ version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" dependencies = [ - "toml_edit 0.25.15+spec-1.1.0", + "toml_edit 0.25.17+spec-1.1.0", ] [[package]] @@ -9643,29 +10091,6 @@ dependencies = [ "version_check", ] -[[package]] -name = "proc-macro-rules" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07c277e4e643ef00c1233393c673f655e3672cf7eb3ba08a00bdd0ea59139b5f" -dependencies = [ - "proc-macro-rules-macros", - "proc-macro2", - "syn 2.0.119", -] - -[[package]] -name = "proc-macro-rules-macros" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "207fffb0fe655d1d47f6af98cc2793405e85929bdbc420d685554ff07be27ac7" -dependencies = [ - "once_cell", - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "proc-macro-utils" version = "0.10.0" @@ -9739,6 +10164,22 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "proptest" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0" +dependencies = [ + "bitflags 2.13.2", + "chacha20", + "core_detect", + "num-traits", + "rand 0.10.3", + "rand_xorshift", + "regex-syntax 0.8.11", + "unarray", +] + [[package]] name = "prost" version = "0.13.5" @@ -9746,7 +10187,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2796faa41db3ec313a31f7624d9286acf277b52de526150b7e69f3debf891ee5" dependencies = [ "bytes", - "prost-derive", + "prost-derive 0.13.5", +] + +[[package]] +name = "prost" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "528ac67416ff8646872a3c02cad9cc4ee5dc9f9540c9b10771855c95cb2e5ae1" +dependencies = [ + "bytes", + "prost-derive 0.14.4", ] [[package]] @@ -9762,13 +10213,26 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "prost-derive" +version = "0.14.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf" +dependencies = [ + "anyhow", + "itertools 0.14.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "prost-types" version = "0.13.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "52c2c1bf36ddb1a1c396b3601a3cec27c2462e45f07c386894ec3ccf5332bd16" dependencies = [ - "prost", + "prost 0.13.5", ] [[package]] @@ -9886,7 +10350,7 @@ dependencies = [ "quinn-proto", "quinn-udp", "rustc-hash 2.1.3", - "rustls 0.23.35", + "rustls 0.23.40", "socket2 0.6.5", "thiserror 2.0.21", "tokio", @@ -9902,13 +10366,14 @@ checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" dependencies = [ "aws-lc-rs", "bytes", + "fastbloom", "getrandom 0.4.3", "lru-slab", "rand 0.10.3", "rand_pcg", "ring 0.17.14", "rustc-hash 2.1.3", - "rustls 0.23.35", + "rustls 0.23.40", "rustls-pki-types", "slab", "thiserror 2.0.21", @@ -9940,6 +10405,28 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "quote-use" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48356e493823dc3c1d7e9fc7b3ff204ecec48afbdd718fc4134091b88eb63f3d" +dependencies = [ + "quote", + "quote-use-macros", +] + +[[package]] +name = "quote-use-macros" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cf1c5de6a7cc231c71e03c77aa4c7019097859ea7029156b54d2894a8430704" +dependencies = [ + "proc-macro-utils", + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "r-efi" version = "5.3.0" @@ -10094,6 +10581,15 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "rand_xorshift" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf" +dependencies = [ + "rand_core 0.10.1", +] + [[package]] name = "raw-cpuid" version = "11.6.0" @@ -10239,9 +10735,9 @@ dependencies = [ [[package]] name = "redox_syscall" -version = "0.9.4" +version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "737970939a87c6fa31e7acad13307bccbb017a073b695b6089a2c484f929e20e" +checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd" dependencies = [ "bitflags 2.13.2", ] @@ -10284,7 +10780,7 @@ checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -10373,8 +10869,8 @@ dependencies = [ "percent-encoding", "pin-project-lite", "quinn", - "rustls 0.23.35", - "rustls-native-certs 0.8.4", + "rustls 0.23.40", + "rustls-native-certs 0.8.5", "rustls-pki-types", "serde", "serde_json", @@ -10420,7 +10916,7 @@ dependencies = [ "percent-encoding", "pin-project-lite", "quinn", - "rustls 0.23.35", + "rustls 0.23.40", "rustls-pki-types", "rustls-platform-verifier", "serde", @@ -10476,6 +10972,16 @@ dependencies = [ "wasmtimer", ] +[[package]] +name = "resb" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22d392791f3c6802a1905a509e9d1a6039cbbcb5e9e00e5a6d3661f7c874f390" +dependencies = [ + "potential_utf", + "serde_core", +] + [[package]] name = "resolv-conf" version = "0.7.6" @@ -10579,7 +11085,7 @@ dependencies = [ "rand 0.10.3", "reqwest 0.13.5", "rmcp-macros", - "schemars 1.2.2", + "schemars 1.2.3", "serde", "serde_json", "sse-stream", @@ -10603,7 +11109,7 @@ dependencies = [ "proc-macro2", "quote", "serde_json", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -10666,14 +11172,114 @@ dependencies = [ "num-integer", "num-traits", "pkcs1", - "pkcs8", + "pkcs8 0.10.2", "rand_core 0.6.4", - "signature", - "spki", + "signature 2.2.0", + "spki 0.7.3", "subtle", "zeroize", ] +[[package]] +name = "ruff_python_ast" +version = "0.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15434b06df7d930fad2818639a4e0fec4af9c770121c45a96b72da7feaae9ead" +dependencies = [ + "aho-corasick", + "arrayvec", + "bitflags 2.13.2", + "char_str", + "compact_str 0.10.0", + "get-size2", + "is-macro", + "memchr", + "ruff_python_trivia", + "ruff_source_file", + "ruff_text_size", + "rustc-hash 2.1.3", + "thin-vec", + "thiserror 2.0.21", +] + +[[package]] +name = "ruff_python_parser" +version = "0.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37a22811d752aa9e255d7dd72524d14352cf9bc654ef79b399bf1eeeb6640fbb" +dependencies = [ + "bitflags 2.13.2", + "bstr", + "drop_bomb", + "get-size2", + "hashbrown 0.17.1", + "memchr", + "ruff_python_ast", + "ruff_python_trivia", + "ruff_text_size", + "ruff_unicode_names2", + "rustc-hash 2.1.3", + "stacker", + "static_assertions", + "thin-vec", + "unicode-ident", + "unicode-normalization", +] + +[[package]] +name = "ruff_python_trivia" +version = "0.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0322a5059fe0feb2e010ca6f31c24ac289f6b7e9e38359539491b10c57f1c5bc" +dependencies = [ + "itertools 0.15.0", + "memchr", + "ruff_source_file", + "ruff_text_size", + "rustc-hash 2.1.3", + "unicode-ident", + "unicode-normalization", +] + +[[package]] +name = "ruff_source_file" +version = "0.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6ae809a289b5c791f82aa45df33f2a92323e7a1c1d265c10e9ac884027a2e43" +dependencies = [ + "memchr", + "ruff_text_size", +] + +[[package]] +name = "ruff_text_size" +version = "0.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "daf6344d6915ced9316312c1ee3f24c4300c54295bc4c3b8f4e95b633ae5443b" +dependencies = [ + "get-size2", +] + +[[package]] +name = "ruff_unicode_names2" +version = "0.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13418b8fd029d597e35dedc36e91f47122d26075e4c86557574d9441753fb375" +dependencies = [ + "phf 0.11.3", + "ruff_unicode_names2_generator", +] + +[[package]] +name = "ruff_unicode_names2_generator" +version = "0.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37fd82af49d5685d9054e68185987acaaf62542f671b6df8935155664876bc39" +dependencies = [ + "phf_codegen", + "rand 0.8.5", +] + [[package]] name = "rumqttc" version = "0.24.0" @@ -10747,12 +11353,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "rustc-demangle" -version = "0.1.28" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb" - [[package]] name = "rustc-hash" version = "1.1.0" @@ -10765,22 +11365,13 @@ version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" -[[package]] -name = "rustc_version" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" -dependencies = [ - "semver 0.9.0", -] - [[package]] name = "rustc_version" version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" dependencies = [ - "semver 1.0.28", + "semver", ] [[package]] @@ -10860,9 +11451,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.35" +version = "0.23.40" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "533f54bc6a7d4f647e46ad909549eda97bf5afc1585190ef692b4286b198bd8f" +checksum = "ef86cd5876211988985292b91c96a8f2d298df24e75989a43a3c73f2d4d8168b" dependencies = [ "aws-lc-rs", "log", @@ -10881,7 +11472,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "70cc376c6ba1823ae229bacf8ad93c136d93524eab0e4e5e0e4f96b9c4e5b212" dependencies = [ "log", - "rustls 0.23.35", + "rustls 0.23.40", "rustls-native-certs 0.7.3", "rustls-pki-types", "rustls-webpki 0.103.15", @@ -10914,9 +11505,9 @@ dependencies = [ [[package]] name = "rustls-native-certs" -version = "0.8.4" +version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" dependencies = [ "openssl-probe 0.2.1", "rustls-pki-types", @@ -10963,8 +11554,8 @@ dependencies = [ "jni", "log", "once_cell", - "rustls 0.23.35", - "rustls-native-certs 0.8.4", + "rustls 0.23.40", + "rustls-native-certs 0.8.5", "rustls-platform-verifier-android", "rustls-webpki 0.103.15", "security-framework 3.7.0", @@ -10981,12 +11572,13 @@ checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" [[package]] name = "rustls-tokio-stream" -version = "0.5.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "faa7dc7c991d9164e55bbf1558029eb5b84d32cc4d61a7df5b8641b2deedc4b3" +checksum = "0560d12c0d8c672f849197de91b9ee61f5bf9aa024c97aaeeb112ec2f6c347fd" dependencies = [ + "derive-io", "futures", - "rustls 0.23.35", + "rustls 0.23.40", "socket2 0.5.10", "tokio", ] @@ -11024,63 +11616,6 @@ dependencies = [ "untrusted 0.9.0", ] -[[package]] -name = "rustpython-ast" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cdaf8ee5c1473b993b398c174641d3aa9da847af36e8d5eb8291930b72f31a5" -dependencies = [ - "is-macro", - "malachite-bigint", - "rustpython-parser-core", - "static_assertions", -] - -[[package]] -name = "rustpython-parser" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "868f724daac0caf9bd36d38caf45819905193a901e8f1c983345a68e18fb2abb" -dependencies = [ - "anyhow", - "is-macro", - "itertools 0.11.0", - "lalrpop-util", - "log", - "malachite-bigint", - "num-traits", - "phf 0.11.3", - "phf_codegen", - "rustc-hash 1.1.0", - "rustpython-ast", - "rustpython-parser-core", - "tiny-keccak", - "unic-emoji-char", - "unic-ucd-ident", - "unicode_names2", -] - -[[package]] -name = "rustpython-parser-core" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4b6c12fa273825edc7bccd9a734f0ad5ba4b8a2f4da5ff7efe946f066d0f4ad" -dependencies = [ - "is-macro", - "memchr", - "rustpython-parser-vendored", -] - -[[package]] -name = "rustpython-parser-vendored" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04fcea49a4630a3a5d940f4d514dc4f575ed63c14c3e3ed07146634aed7f67a6" -dependencies = [ - "memchr", - "once_cell", -] - [[package]] name = "rustversion" version = "1.0.23" @@ -11174,9 +11709,9 @@ checksum = "ece8e78b2f38ec51c51f5d475df0a7187ba5111b2a28bdc761ee05b075d40a71" [[package]] name = "schannel" -version = "0.1.29" +version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" dependencies = [ "windows-sys 0.61.2", ] @@ -11207,14 +11742,14 @@ dependencies = [ [[package]] name = "schemars" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "687274d293b6cdc6e73e0fee520bf2049650090d7164f87672d212a3c530cf4a" +checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" dependencies = [ "chrono", "dyn-clone", "ref-cast", - "schemars_derive 1.2.2", + "schemars_derive 1.2.3", "serde", "serde_json", ] @@ -11233,14 +11768,14 @@ dependencies = [ [[package]] name = "schemars_derive" -version = "1.2.2" +version = "1.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d98c67716b46af2f0b8cf752abc930f6f9aecfbf671ecfb531db8a31dbe4e2ba" +checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69" dependencies = [ "proc-macro2", "quote", "serde_derive_internals 0.30.0", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -11288,11 +11823,25 @@ version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" dependencies = [ - "base16ct", - "der", + "base16ct 0.2.0", + "der 0.7.10", "generic-array", - "pkcs8", - "serdect", + "pkcs8 0.10.2", + "serdect 0.2.0", + "subtle", + "zeroize", +] + +[[package]] +name = "sec1" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56d437c2f19203ce5f7122e507831de96f3d2d4d3be5af44a0b0a09d8a80e4d" +dependencies = [ + "base16ct 1.0.0", + "ctutils", + "der 0.8.2", + "hybrid-array", "subtle", "zeroize", ] @@ -11342,27 +11891,12 @@ dependencies = [ "libc", ] -[[package]] -name = "semver" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" -dependencies = [ - "semver-parser", -] - [[package]] name = "semver" version = "1.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" -[[package]] -name = "semver-parser" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" - [[package]] name = "seq-macro" version = "0.3.6" @@ -11439,7 +11973,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -11461,15 +11995,16 @@ checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] name = "serde_json" -version = "1.0.151" +version = "1.0.154" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" dependencies = [ + "foldhash 0.2.0", "indexmap 2.14.2", "itoa", "memchr", @@ -11515,7 +12050,7 @@ checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -11541,16 +12076,16 @@ dependencies = [ [[package]] name = "serde_v8" -version = "0.261.1" +version = "0.321.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3495190857461e87a2716141043218aad5281f219f54a03b7ebbe605b3b931df" +checksum = "fd3b6f6140192f569b88997e2ea7afeef6aa38b64374e84784ea1d1ea35679d3" dependencies = [ - "deno_error 0.6.1", + "deno_error", + "deno_v8", "num-bigint", "serde", "smallvec", "thiserror 2.0.21", - "v8", ] [[package]] @@ -11567,7 +12102,7 @@ dependencies = [ "indexmap 2.14.2", "jiff", "schemars 0.9.0", - "schemars 1.2.2", + "schemars 1.2.3", "serde_core", "serde_json", "serde_with_macros", @@ -11583,7 +12118,7 @@ dependencies = [ "darling 0.24.1", "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -11620,7 +12155,17 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a84f14a19e9a014bb9f4512488d9829a68e04ecabffb0f9904cd1ace94598177" dependencies = [ - "base16ct", + "base16ct 0.2.0", + "serde", +] + +[[package]] +name = "serdect" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66cf8fedced2fcf12406bcb34223dffb92eaf34908ede12fed414c82b7f00b3e" +dependencies = [ + "base16ct 1.0.0", "serde", ] @@ -11686,15 +12231,36 @@ dependencies = [ [[package]] name = "sha2" -version = "0.11.0" +version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" dependencies = [ "cfg-if", "cpufeatures 0.3.1", "digest 0.11.3", ] +[[package]] +name = "sha3" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77fd7028345d415a4034cf8777cd4f8ab1851274233b45f84e3d955502d93874" +dependencies = [ + "digest 0.10.7", + "keccak 0.1.6", +] + +[[package]] +name = "shake" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09057cb2149ad4cbd2da1e26b351f9a4c354219421229c69c3063e6f61947c4a" +dependencies = [ + "digest 0.11.3", + "keccak 0.2.2", + "sponge-cursor", +] + [[package]] name = "sharded-slab" version = "0.1.7" @@ -11735,6 +12301,16 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" +[[package]] +name = "signal-hook" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2" +dependencies = [ + "libc", + "signal-hook-registry", +] + [[package]] name = "signal-hook-registry" version = "1.4.8" @@ -11751,9 +12327,9 @@ version = "0.27.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1e303f8205714074f6068773f0e29527e0453937fe837c9717d066635b65f31" dependencies = [ - "pkcs8", + "pkcs8 0.10.2", "rand_core 0.6.4", - "signature", + "signature 2.2.0", "zeroize", ] @@ -11767,6 +12343,16 @@ dependencies = [ "rand_core 0.6.4", ] +[[package]] +name = "signature" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5" +dependencies = [ + "digest 0.11.3", + "rand_core 0.10.1", +] + [[package]] name = "simd-adler32" version = "0.3.10" @@ -11779,7 +12365,7 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" dependencies = [ - "rustc_version 0.4.1", + "rustc_version", "simdutf8", ] @@ -11836,9 +12422,9 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" [[package]] name = "smallvec" -version = "1.16.2" +version = "1.16.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e" +checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" dependencies = [ "serde", ] @@ -11947,7 +12533,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" dependencies = [ "base64ct", - "der", + "der 0.7.10", +] + +[[package]] +name = "spki" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9" +dependencies = [ + "base64ct", + "der 0.8.2", ] [[package]] @@ -11962,6 +12558,12 @@ dependencies = [ "unicode-segmentation", ] +[[package]] +name = "sponge-cursor" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a0219bd7d979d58245a4f41f695e1ac9f8befdffadd7f61f1bae9e39abc6620" + [[package]] name = "sql-builder" version = "3.1.1" @@ -12008,7 +12610,7 @@ dependencies = [ [[package]] name = "sqlx" version = "0.8.6" -source = "git+https://github.com/windmill-labs/sqlx?rev=6bdaee94fa62a01561125646da3f99eb341f2457#6bdaee94fa62a01561125646da3f99eb341f2457" +source = "git+https://github.com/windmill-labs/sqlx?rev=c1c5f1f2a07cb1fce0e47463c314697e08f4f26b#c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" dependencies = [ "sqlx-core", "sqlx-macros", @@ -12020,7 +12622,7 @@ dependencies = [ [[package]] name = "sqlx-core" version = "0.8.6" -source = "git+https://github.com/windmill-labs/sqlx?rev=6bdaee94fa62a01561125646da3f99eb341f2457#6bdaee94fa62a01561125646da3f99eb341f2457" +source = "git+https://github.com/windmill-labs/sqlx?rev=c1c5f1f2a07cb1fce0e47463c314697e08f4f26b#c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" dependencies = [ "base64 0.22.1", "bigdecimal", @@ -12041,7 +12643,7 @@ dependencies = [ "memchr", "once_cell", "percent-encoding", - "rustls 0.23.35", + "rustls 0.23.40", "serde", "serde_json", "sha2 0.10.9", @@ -12058,7 +12660,7 @@ dependencies = [ [[package]] name = "sqlx-macros" version = "0.8.6" -source = "git+https://github.com/windmill-labs/sqlx?rev=6bdaee94fa62a01561125646da3f99eb341f2457#6bdaee94fa62a01561125646da3f99eb341f2457" +source = "git+https://github.com/windmill-labs/sqlx?rev=c1c5f1f2a07cb1fce0e47463c314697e08f4f26b#c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" dependencies = [ "proc-macro2", "quote", @@ -12070,7 +12672,7 @@ dependencies = [ [[package]] name = "sqlx-macros-core" version = "0.8.6" -source = "git+https://github.com/windmill-labs/sqlx?rev=6bdaee94fa62a01561125646da3f99eb341f2457#6bdaee94fa62a01561125646da3f99eb341f2457" +source = "git+https://github.com/windmill-labs/sqlx?rev=c1c5f1f2a07cb1fce0e47463c314697e08f4f26b#c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" dependencies = [ "dotenvy", "either", @@ -12094,7 +12696,7 @@ dependencies = [ [[package]] name = "sqlx-mysql" version = "0.8.6" -source = "git+https://github.com/windmill-labs/sqlx?rev=6bdaee94fa62a01561125646da3f99eb341f2457#6bdaee94fa62a01561125646da3f99eb341f2457" +source = "git+https://github.com/windmill-labs/sqlx?rev=c1c5f1f2a07cb1fce0e47463c314697e08f4f26b#c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" dependencies = [ "atoi", "base64 0.22.1", @@ -12138,7 +12740,7 @@ dependencies = [ [[package]] name = "sqlx-postgres" version = "0.8.6" -source = "git+https://github.com/windmill-labs/sqlx?rev=6bdaee94fa62a01561125646da3f99eb341f2457#6bdaee94fa62a01561125646da3f99eb341f2457" +source = "git+https://github.com/windmill-labs/sqlx?rev=c1c5f1f2a07cb1fce0e47463c314697e08f4f26b#c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" dependencies = [ "atoi", "base64 0.22.1", @@ -12178,7 +12780,7 @@ dependencies = [ [[package]] name = "sqlx-sqlite" version = "0.8.6" -source = "git+https://github.com/windmill-labs/sqlx?rev=6bdaee94fa62a01561125646da3f99eb341f2457#6bdaee94fa62a01561125646da3f99eb341f2457" +source = "git+https://github.com/windmill-labs/sqlx?rev=c1c5f1f2a07cb1fce0e47463c314697e08f4f26b#c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" dependencies = [ "atoi", "chrono", @@ -12238,6 +12840,15 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" +[[package]] +name = "strck" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42316e70da376f3d113a68d138a60d8a9883c604fe97942721ec2068dab13a9f" +dependencies = [ + "unicode-ident", +] + [[package]] name = "string_enum" version = "1.0.2" @@ -12438,7 +13049,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bcf55c2d7555c93f4945e29f93b7529562be97ba16e60dd94c25724d746174ac" dependencies = [ "ascii", - "compact_str", + "compact_str 0.7.1", "memchr", "num-bigint", "once_cell", @@ -12742,15 +13353,26 @@ dependencies = [ [[package]] name = "syn" -version = "3.0.6" +version = "3.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] +[[package]] +name = "syn-match" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54b8f0a9004d6aafa6a588602a1119e6cdaacec9921aa1605383e6e7d6258fd6" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "sync_wrapper" version = "1.0.2" @@ -12760,6 +13382,18 @@ dependencies = [ "futures-core", ] +[[package]] +name = "synstructure" +version = "0.12.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f36bdaa60a83aca3921b5259d5400cbf5e90fc51931376a9bd4a0eb79aa7210f" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", + "unicode-xid", +] + [[package]] name = "synstructure" version = "0.13.2" @@ -12779,7 +13413,7 @@ checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -12793,11 +13427,14 @@ dependencies = [ [[package]] name = "sys_traits" -version = "0.1.16" +version = "0.1.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc4707edf3196e8037ee45018d1bb1bfb233b0e4fc440fa3d3f25bc69bfdaf26" +checksum = "c7a35f11f9773f11930a7d1e6276766f1577400ee2530b7f0cf3844c2dcbf12b" dependencies = [ + "junction", + "libc", "sys_traits_macros", + "windows-sys 0.59.0", ] [[package]] @@ -13052,15 +13689,6 @@ dependencies = [ "rustls-pemfile 2.2.0", ] -[[package]] -name = "temp_deno_which" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "366c5ccd670145885feb6efd6bbf2478ed236c4c3839046fcc8e2a1a84c51091" -dependencies = [ - "either", -] - [[package]] name = "tempfile" version = "3.27.0" @@ -13074,6 +13702,40 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "temporal_capi" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f48eb9ca4ca22caaa48d1e7a534ad3fd598a23d1a71945e8ad5ac0be501fa5f2" +dependencies = [ + "diplomat", + "diplomat-runtime", + "icu_calendar", + "icu_locale_core", + "num-traits", + "temporal_rs", + "timezone_provider", + "writeable", + "zoneinfo64", +] + +[[package]] +name = "temporal_rs" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a978fef907a27736827d336c0bfaab14fb8a7509dd6dc2b43c44e51d59aca5b" +dependencies = [ + "calendrical_calculations", + "core_maths", + "icu_calendar", + "icu_locale_core", + "ixdtf", + "num-traits", + "timezone_provider", + "tinystr", + "writeable", +] + [[package]] name = "termcolor" version = "1.4.1" @@ -13112,6 +13774,12 @@ dependencies = [ "unicode-width 0.2.2", ] +[[package]] +name = "thin-vec" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6a4b9ba8738cb4a4f399d37e266becfd475e75eb73425b87a05a2f2039ba63e" + [[package]] name = "thiserror" version = "1.0.69" @@ -13149,7 +13817,7 @@ checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -13274,6 +13942,18 @@ dependencies = [ "time-core", ] +[[package]] +name = "timezone_provider" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89ec4f4eebb4817fde02a411aedc7ac5f66c89c68c49e5d4b17a8139f077af52" +dependencies = [ + "tinystr", + "zerotrie", + "zerovec", + "zoneinfo64", +] + [[package]] name = "tiny-keccak" version = "2.0.2" @@ -13350,23 +14030,20 @@ dependencies = [ [[package]] name = "tokio" -version = "1.46.1" +version = "1.53.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0cc3a2344dafbe23a245241fe8b09735b521110d30fcefbbd5feb1797ca35d17" +checksum = "e95f91fcc7a621e8b030f6aa23c71fe9838ae2fb4d8118b75602a328f5144044" dependencies = [ - "backtrace", "bytes", - "io-uring", "libc", "mio", "parking_lot", "pin-project-lite", "signal-hook-registry", - "slab", - "socket2 0.5.10", + "socket2 0.6.5", "tokio-macros", "tracing", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -13395,13 +14072,13 @@ dependencies = [ [[package]] name = "tokio-macros" -version = "2.5.0" +version = "2.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e06d43f1345a3bcd39f6a56dbb7dcab2ba47e68e8ac134855e7e2bdbaf8cab8" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.119", + "syn 3.0.9", ] [[package]] @@ -13490,7 +14167,7 @@ version = "0.26.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" dependencies = [ - "rustls 0.23.35", + "rustls 0.23.40", "tokio", ] @@ -13592,7 +14269,7 @@ dependencies = [ "httparse", "rand 0.8.5", "ring 0.17.14", - "rustls-native-certs 0.8.4", + "rustls-native-certs 0.8.5", "rustls-pki-types", "tokio", "tokio-rustls 0.26.6", @@ -13622,9 +14299,9 @@ dependencies = [ [[package]] name = "toml_datetime" -version = "1.1.1+spec-1.1.0" +version = "1.1.2+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" dependencies = [ "serde_core", ] @@ -13644,21 +14321,21 @@ dependencies = [ [[package]] name = "toml_edit" -version = "0.25.15+spec-1.1.0" +version = "0.25.17+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1340ea94a5856333492c9064b02c778b191dd2c853778d9609debdcdfea3a614" +checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c" dependencies = [ "indexmap 2.14.2", - "toml_datetime 1.1.1+spec-1.1.0", + "toml_datetime 1.1.2+spec-1.1.0", "toml_parser", "winnow 1.0.4", ] [[package]] name = "toml_parser" -version = "1.1.3+spec-1.1.0" +version = "1.1.5+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" dependencies = [ "winnow 1.0.4", ] @@ -13669,13 +14346,10 @@ version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "877c5b330756d856ffcc4553ab34a5684481ade925ecc54bcd1bf02b1d0d4d52" dependencies = [ - "async-stream", "async-trait", - "axum 0.7.9", "base64 0.22.1", "bytes", "flate2", - "h2 0.4.20", "http 1.5.0", "http-body 1.1.0", "http-body-util", @@ -13684,9 +14358,8 @@ dependencies = [ "hyper-util", "percent-encoding", "pin-project", - "prost", + "prost 0.13.5", "rustls-pemfile 2.2.0", - "socket2 0.5.10", "tokio", "tokio-rustls 0.26.6", "tokio-stream", @@ -13704,7 +14377,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7e581ba15a835f4d9ea06c55ab1bd4dce26fc53752c69a04aac00703bfb49ba9" dependencies = [ "async-trait", - "axum 0.8.9", + "axum", "base64 0.22.1", "bytes", "flate2", @@ -13717,8 +14390,8 @@ dependencies = [ "hyper-util", "percent-encoding", "pin-project", - "prost", - "rustls-native-certs 0.8.4", + "prost 0.13.5", + "rustls-native-certs 0.8.5", "socket2 0.5.10", "tokio", "tokio-rustls 0.26.6", @@ -13775,7 +14448,7 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "151b5a3e3c45df17466454bb74e9ecedecc955269bdedbf4d150dfa393b55a36" dependencies = [ - "axum-core 0.5.6", + "axum-core", "cookie", "futures-util", "http 1.5.0", @@ -13973,9 +14646,9 @@ dependencies = [ [[package]] name = "tree-sitter-language" -version = "0.1.8" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca0d1bf6fdd806e43ae5198f82f527056d359def39e54e67a0f478ac09dac081" +checksum = "d0af592be68c579aa78a16846bd19422978c3c52e438523d45ff5d1bff1f9d4a" [[package]] name = "tree-sitter-r" @@ -13999,9 +14672,9 @@ dependencies = [ [[package]] name = "triomphe" -version = "0.1.16" +version = "0.1.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b40688ea6389c8171614b25491f71d4a27946e0c7ce2da1c6de27e25abf1a0ae" +checksum = "0d15f4f5898bcfc5d8a8e45ed30b2f108d710c1a2e5489dbf80e078f707181bc" dependencies = [ "serde", "stable_deref_trait", @@ -14109,7 +14782,7 @@ checksum = "f153acc4e99a5f2a5aefa09fb078be54e26271b2813f6041200b224c098d8328" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -14129,6 +14802,12 @@ dependencies = [ "web-time", ] +[[package]] +name = "unarray" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" + [[package]] name = "unic-char-property" version = "0.9.0" @@ -14150,17 +14829,6 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "80d7ff825a6a654ee85a63e80f92f054f904f21e7d12da4e22f9834a4aaa35bc" -[[package]] -name = "unic-emoji-char" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b07221e68897210270a38bde4babb655869637af0f69407f96053a34f76494d" -dependencies = [ - "unic-char-property", - "unic-char-range", - "unic-ucd-version", -] - [[package]] name = "unic-ucd-category" version = "0.9.0" @@ -14173,17 +14841,6 @@ dependencies = [ "unic-ucd-version", ] -[[package]] -name = "unic-ucd-ident" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e230a37c0381caa9219d67cf063aa3a375ffed5bf541a452db16e744bdab6987" -dependencies = [ - "unic-char-property", - "unic-char-range", - "unic-ucd-version", -] - [[package]] name = "unic-ucd-version" version = "0.9.0" @@ -14213,15 +14870,15 @@ checksum = "0825d2e09dcae814a4273c1e1435979d414ede25b2ee235b1545da6682483765" [[package]] name = "unicode-ident" -version = "1.0.26" +version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" [[package]] name = "unicode-normalization" -version = "0.1.25" +version = "0.1.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" dependencies = [ "tinyvec", ] @@ -14271,28 +14928,6 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39ec24b3121d976906ece63c9daad25b85969647682eee313cb5779fdd69e14e" -[[package]] -name = "unicode_names2" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1673eca9782c84de5f81b82e4109dcfb3611c8ba0d52930ec4a9478f547b2dd" -dependencies = [ - "phf 0.11.3", - "unicode_names2_generator", -] - -[[package]] -name = "unicode_names2_generator" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b91e5b84611016120197efd7dc93ef76774f4e084cd73c9fb3ea4a86c570c56e" -dependencies = [ - "getopts", - "log", - "phf_codegen", - "rand 0.8.5", -] - [[package]] name = "universal-hash" version = "0.5.1" @@ -14344,7 +14979,7 @@ dependencies = [ "log", "native-tls", "once_cell", - "rustls 0.23.35", + "rustls 0.23.40", "rustls-pki-types", "serde", "serde_json", @@ -14374,13 +15009,13 @@ checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" [[package]] name = "urlpattern" -version = "0.3.0" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "70acd30e3aa1450bc2eece896ce2ad0d178e9c079493819301573dae3c37ba6d" +checksum = "0f805818f843b548bacc19609eb3619dd2850e54746f5cada37927393c2ef4ec" dependencies = [ + "icu_properties", "regex", "serde", - "unic-ucd-ident", "url", ] @@ -14416,9 +15051,9 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" [[package]] name = "uuid" -version = "1.27.0" +version = "1.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97277d36b9c3ace13e58fa6e753f8b0bbbf302a18dd193240d70f9e29681059a" +checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606" dependencies = [ "getrandom 0.4.3", "js-sys", @@ -14428,20 +15063,36 @@ dependencies = [ [[package]] name = "v8" -version = "137.3.0" +version = "150.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33995a1fee055ff743281cde33a41f0d618ee0bdbe8bdf6859e11864499c2595" +checksum = "42a978ff11f15b24e5c05a7123cf2b68f41e763546699781a924ef4e2cf43a49" dependencies = [ - "bindgen 0.71.1", + "bindgen 0.72.1", "bitflags 2.13.2", "fslock", "gzip-header", "home", "miniz_oxide 0.8.9", "paste", + "temporal_capi", "which 6.0.3", ] +[[package]] +name = "v8x" +version = "149.4.0-rc.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3701ffb3692a24808503d17f758b0a3f688d2c451779247982566b5941033e63" +dependencies = [ + "bindgen 0.70.1", + "bitflags 2.13.2", + "cc", + "paste", + "temporal_capi", + "temporal_rs", + "timezone_provider", +] + [[package]] name = "valuable" version = "0.1.1" @@ -14581,7 +15232,7 @@ dependencies = [ "bumpalo", "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", "wasm-bindgen-shared", ] @@ -14624,7 +15275,7 @@ checksum = "3b84b5ac638bfb168196a1a461fcc8f46a294a18b1b6be52133b4e0db122cc9f" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] @@ -14661,11 +15312,11 @@ dependencies = [ [[package]] name = "wasm_dep_analyzer" -version = "0.3.0" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e51cf5f08b357e64cd7642ab4bbeb11aecab9e15520692129624fb9908b8df2c" +checksum = "a10e6b67c951a84de7029487e0e0a496860dae49f6699edd279d5ff35b8fbf54" dependencies = [ - "deno_error 0.6.1", + "deno_error", "thiserror 2.0.21", ] @@ -14766,6 +15417,12 @@ dependencies = [ "winsafe", ] +[[package]] +name = "which" +version = "8.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bae2f2b2b816647a1cab1acc91f5bd20812d53cb344382635ec2181940c8034f" + [[package]] name = "whoami" version = "1.6.1" @@ -14829,14 +15486,14 @@ dependencies = [ [[package]] name = "windmill" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "async-nats", "aws-config", "aws-credential-types", "aws-sdk-sqs", - "axum 0.8.9", + "axum", "base64 0.22.1", "chrono", "constant_time_eq 0.3.1", @@ -14856,7 +15513,7 @@ dependencies = [ "rdkafka", "reqwest 0.13.5", "rumqttc", - "rustls 0.23.35", + "rustls 0.23.40", "serde", "serde_derive", "serde_json", @@ -14887,6 +15544,7 @@ dependencies = [ "windmill-api-scripts", "windmill-api-settings", "windmill-api-users", + "windmill-audit", "windmill-autoscaling", "windmill-common", "windmill-dep-map", @@ -14918,7 +15576,7 @@ dependencies = [ [[package]] name = "windmill-ai" -version = "1.827.0" +version = "1.841.0" dependencies = [ "async-stream", "async-trait", @@ -14935,6 +15593,7 @@ dependencies = [ "indexmap 2.14.2", "lazy_static", "mime_guess", + "rand 0.9.5", "reqwest 0.13.5", "serde", "serde_json", @@ -14952,9 +15611,9 @@ dependencies = [ [[package]] name = "windmill-alerting" -version = "1.827.0" +version = "1.841.0" dependencies = [ - "axum 0.8.9", + "axum", "chrono", "serde", "serde_json", @@ -14965,7 +15624,7 @@ dependencies = [ [[package]] name = "windmill-api" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "argon2", @@ -14976,7 +15635,7 @@ dependencies = [ "async_zip", "aws-sdk-config", "aws-sigv4", - "axum 0.8.9", + "axum", "base32", "base64 0.22.1", "bytes", @@ -15008,17 +15667,19 @@ dependencies = [ "native-tls", "openidconnect", "openssl", + "p256", "pin-project", "postgres-native-tls 0.5.3", "prometheus", "quick-xml", "quick_cache", "rand 0.9.5", + "rcgen", "regex", "reqwest 0.13.5", "rsa", "rust-embed", - "rustls 0.23.35", + "rustls 0.23.40", "samael", "serde", "serde_json", @@ -15034,6 +15695,7 @@ dependencies = [ "tokio", "tokio-native-tls", "tokio-postgres", + "tokio-rustls 0.26.6", "tokio-stream", "tokio-util", "tower 0.5.3", @@ -15105,9 +15767,9 @@ dependencies = [ [[package]] name = "windmill-api-agent-workers" -version = "1.827.0" +version = "1.841.0" dependencies = [ - "axum 0.8.9", + "axum", "chrono", "http 1.5.0", "hyper 1.12.0", @@ -15120,6 +15782,7 @@ dependencies = [ "tracing", "uuid", "windmill-api-auth", + "windmill-audit", "windmill-common", "windmill-parser-py-imports", "windmill-queue", @@ -15128,9 +15791,9 @@ dependencies = [ [[package]] name = "windmill-api-assets" -version = "1.827.0" +version = "1.841.0" dependencies = [ - "axum 0.8.9", + "axum", "chrono", "serde", "serde_json", @@ -15145,10 +15808,10 @@ dependencies = [ [[package]] name = "windmill-api-auth" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", - "axum 0.8.9", + "axum", "chrono", "http 1.5.0", "itertools 0.14.0", @@ -15171,7 +15834,7 @@ dependencies = [ [[package]] name = "windmill-api-client" -version = "1.827.0" +version = "1.841.0" dependencies = [ "reqwest 0.12.28", "serde", @@ -15181,9 +15844,9 @@ dependencies = [ [[package]] name = "windmill-api-configs" -version = "1.827.0" +version = "1.841.0" dependencies = [ - "axum 0.8.9", + "axum", "chrono", "itertools 0.14.0", "serde", @@ -15198,9 +15861,9 @@ dependencies = [ [[package]] name = "windmill-api-debug" -version = "1.827.0" +version = "1.841.0" dependencies = [ - "axum 0.8.9", + "axum", "base64 0.22.1", "chrono", "ed25519-dalek", @@ -15220,10 +15883,10 @@ dependencies = [ [[package]] name = "windmill-api-embeddings" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", - "axum 0.8.9", + "axum", "candle-core", "candle-nn", "candle-transformers", @@ -15243,9 +15906,9 @@ dependencies = [ [[package]] name = "windmill-api-flow-conversations" -version = "1.827.0" +version = "1.841.0" dependencies = [ - "axum 0.8.9", + "axum", "chrono", "serde", "sql-builder", @@ -15259,9 +15922,9 @@ dependencies = [ [[package]] name = "windmill-api-flows" -version = "1.827.0" +version = "1.841.0" dependencies = [ - "axum 0.8.9", + "axum", "chrono", "hyper 1.12.0", "serde", @@ -15281,9 +15944,9 @@ dependencies = [ [[package]] name = "windmill-api-groups" -version = "1.827.0" +version = "1.841.0" dependencies = [ - "axum 0.8.9", + "axum", "chrono", "globset", "lazy_static", @@ -15303,9 +15966,9 @@ dependencies = [ [[package]] name = "windmill-api-inputs" -version = "1.827.0" +version = "1.841.0" dependencies = [ - "axum 0.8.9", + "axum", "chrono", "serde", "serde_json", @@ -15317,14 +15980,14 @@ dependencies = [ [[package]] name = "windmill-api-integration-tests" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "async-nats", "aws-config", "aws-credential-types", "aws-sdk-sqs", - "axum 0.8.9", + "axum", "base64 0.22.1", "futures", "hex", @@ -15353,10 +16016,10 @@ dependencies = [ [[package]] name = "windmill-api-jobs" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", - "axum 0.8.9", + "axum", "base64 0.22.1", "chrono", "http 1.5.0", @@ -15379,9 +16042,9 @@ dependencies = [ [[package]] name = "windmill-api-npm-proxy" -version = "1.827.0" +version = "1.841.0" dependencies = [ - "axum 0.8.9", + "axum", "chrono", "flate2", "futures", @@ -15389,7 +16052,7 @@ dependencies = [ "lazy_static", "quick_cache", "reqwest 0.13.5", - "semver 1.0.28", + "semver", "serde", "serde_json", "sha2 0.10.9", @@ -15407,10 +16070,10 @@ dependencies = [ [[package]] name = "windmill-api-openapi" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", - "axum 0.8.9", + "axum", "http 1.5.0", "indexmap 2.14.2", "itertools 0.14.0", @@ -15429,9 +16092,9 @@ dependencies = [ [[package]] name = "windmill-api-schedule" -version = "1.827.0" +version = "1.841.0" dependencies = [ - "axum 0.8.9", + "axum", "chrono", "chrono-tz", "serde", @@ -15449,10 +16112,10 @@ dependencies = [ [[package]] name = "windmill-api-scripts" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", - "axum 0.8.9", + "axum", "chrono", "futures", "http 1.5.0", @@ -15491,13 +16154,14 @@ dependencies = [ [[package]] name = "windmill-api-settings" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", - "axum 0.8.9", + "axum", "base64 0.22.1", "bytes", "chrono", + "ed25519-dalek", "futures", "lazy_static", "regex", @@ -15520,7 +16184,7 @@ dependencies = [ [[package]] name = "windmill-api-sse" -version = "1.827.0" +version = "1.841.0" dependencies = [ "lazy_static", "serde", @@ -15532,10 +16196,10 @@ dependencies = [ [[package]] name = "windmill-api-users" -version = "1.827.0" +version = "1.841.0" dependencies = [ "argon2", - "axum 0.8.9", + "axum", "chrono", "http 1.5.0", "hyper 1.12.0", @@ -15556,9 +16220,9 @@ dependencies = [ [[package]] name = "windmill-api-workers" -version = "1.827.0" +version = "1.841.0" dependencies = [ - "axum 0.8.9", + "axum", "chrono", "serde", "serde_json", @@ -15566,13 +16230,14 @@ dependencies = [ "uuid", "windmill-api-auth", "windmill-common", + "windmill-queue", ] [[package]] name = "windmill-api-workspaces" -version = "1.827.0" +version = "1.841.0" dependencies = [ - "axum 0.8.9", + "axum", "chrono", "constant_time_eq 0.3.1", "futures", @@ -15609,7 +16274,7 @@ dependencies = [ [[package]] name = "windmill-audit" -version = "1.827.0" +version = "1.841.0" dependencies = [ "chrono", "lazy_static", @@ -15624,10 +16289,10 @@ dependencies = [ [[package]] name = "windmill-autoscaling" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", - "axum 0.8.9", + "axum", "k8s-openapi", "kube", "serde", @@ -15643,7 +16308,7 @@ dependencies = [ [[package]] name = "windmill-common" -version = "1.827.0" +version = "1.841.0" dependencies = [ "aes-gcm", "aho-corasick", @@ -15657,7 +16322,7 @@ dependencies = [ "aws-sdk-secretsmanager", "aws-sdk-sts", "aws-smithy-types-convert", - "axum 0.8.9", + "axum", "backon", "base64 0.22.1", "bitflags 2.13.2", @@ -15679,9 +16344,12 @@ dependencies = [ "git-version", "globset", "hex", + "hkdf", "hmac 0.12.1", + "http 1.5.0", "hyper 1.12.0", "indexmap 2.14.2", + "ipnet", "itertools 0.14.0", "jsonwebtoken 10.4.0", "lazy_static", @@ -15696,6 +16364,7 @@ dependencies = [ "opentelemetry-otlp 0.30.0", "opentelemetry-semantic-conventions 0.30.0", "opentelemetry_sdk 0.30.0", + "p256", "pep440_rs", "phf 0.11.3", "pin-project-lite", @@ -15711,18 +16380,18 @@ dependencies = [ "reqwest-middleware", "reqwest-retry", "rsa", - "rustls 0.23.35", - "rustls-native-certs 0.8.4", + "rustls 0.23.40", + "rustls-native-certs 0.8.5", "ryu-js", "schemars 0.8.22", - "semver 1.0.28", + "semver", "serde", "serde_json", "serde_yml", "sha1", "sha2 0.10.9", "size", - "spki", + "spki 0.7.3", "sqlx", "strum", "strum_macros", @@ -15757,7 +16426,7 @@ dependencies = [ [[package]] name = "windmill-dep-map" -version = "1.827.0" +version = "1.841.0" dependencies = [ "chrono", "futures", @@ -15777,7 +16446,7 @@ dependencies = [ [[package]] name = "windmill-git-sync" -version = "1.827.0" +version = "1.841.0" dependencies = [ "regex", "serde", @@ -15794,7 +16463,7 @@ dependencies = [ [[package]] name = "windmill-indexer" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "astral-tokio-tar", @@ -15821,7 +16490,7 @@ dependencies = [ [[package]] name = "windmill-jseval" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "futures", @@ -15838,7 +16507,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.827.0" +version = "1.841.0" dependencies = [ "itertools 0.14.0", "lazy_static", @@ -15854,7 +16523,7 @@ dependencies = [ [[package]] name = "windmill-mcp" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "async-trait", @@ -15867,6 +16536,7 @@ dependencies = [ "serde", "serde_json", "sqlx", + "sse-stream", "tokio", "tokio-util", "tracing", @@ -15875,11 +16545,11 @@ dependencies = [ [[package]] name = "windmill-native-triggers" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "async-trait", - "axum 0.8.9", + "axum", "backon", "base64 0.22.1", "chrono", @@ -15906,12 +16576,12 @@ dependencies = [ [[package]] name = "windmill-oauth" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "arc-swap", "async-oauth2", - "axum 0.8.9", + "axum", "base64 0.22.1", "chrono", "hex", @@ -15931,7 +16601,7 @@ dependencies = [ [[package]] name = "windmill-object-store" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "async-stream", @@ -15940,7 +16610,7 @@ dependencies = [ "aws-credential-types", "aws-sdk-sts", "aws-smithy-types-convert", - "axum 0.8.9", + "axum", "bytes", "chrono", "datafusion", @@ -15967,7 +16637,7 @@ dependencies = [ [[package]] name = "windmill-operator" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "futures", @@ -15980,12 +16650,13 @@ dependencies = [ "thiserror 2.0.21", "tokio", "tracing", + "windmill-audit", "windmill-common", ] [[package]] name = "windmill-parser" -version = "1.827.0" +version = "1.841.0" dependencies = [ "convert_case 0.6.0", "serde", @@ -15994,7 +16665,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "lazy_static", @@ -16006,7 +16677,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "serde_json", @@ -16018,7 +16689,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "gosyn", @@ -16030,7 +16701,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "lazy_static", @@ -16042,7 +16713,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "serde_json", @@ -16054,7 +16725,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "nu-parser", @@ -16065,7 +16736,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -16076,30 +16747,30 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "itertools 0.14.0", - "rustpython-ast", - "rustpython-parser", + "ruff_python_ast", + "ruff_python_parser", "serde_json", "windmill-parser", ] [[package]] name = "windmill-parser-py-asset" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", - "rustpython-ast", - "rustpython-parser", + "ruff_python_ast", + "ruff_python_parser", "windmill-parser", "windmill-parser-sql-asset", ] [[package]] name = "windmill-parser-py-imports" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "async-recursion", @@ -16109,7 +16780,8 @@ dependencies = [ "phf 0.11.3", "regex", "regex-lite", - "rustpython-parser", + "ruff_python_ast", + "ruff_python_parser", "serde", "serde_json", "sqlx", @@ -16121,7 +16793,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "serde_json", @@ -16133,7 +16805,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "lazy_static", @@ -16147,7 +16819,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "convert_case 0.6.0", @@ -16164,7 +16836,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "lazy_static", @@ -16177,7 +16849,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "serde", @@ -16189,7 +16861,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "lazy_static", @@ -16207,7 +16879,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -16223,11 +16895,12 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", - "rustpython-ast", - "rustpython-parser", + "ruff_python_ast", + "ruff_python_parser", + "ruff_text_size", "serde", "serde_json", "sha2 0.10.9", @@ -16239,7 +16912,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "lazy_static", @@ -16253,11 +16926,11 @@ dependencies = [ [[package]] name = "windmill-queue" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "async-recursion", - "axum 0.8.9", + "axum", "backon", "chrono", "chrono-tz", @@ -16292,23 +16965,19 @@ dependencies = [ [[package]] name = "windmill-runtime-nativets" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "const_format", "deno_ast", - "deno_console", "deno_core", "deno_crypto", - "deno_error 0.6.1", + "deno_error", "deno_fetch", - "deno_fs", - "deno_io", "deno_net", "deno_permissions", "deno_telemetry", "deno_tls", - "deno_url", "deno_web", "deno_webidl", "futures", @@ -16317,13 +16986,15 @@ dependencies = [ "rcgen", "regex", "reqwest 0.13.5", - "rustls 0.23.35", + "rustls 0.23.40", "serde", "serde_json", "sqlx", + "sys_traits", "tokio", "tracing", "uuid", + "v8", "winapi", "windmill-common", "windmill-parser-ts", @@ -16332,7 +17003,7 @@ dependencies = [ [[package]] name = "windmill-sql-datatype-parser-wasm" -version = "1.827.0" +version = "1.841.0" dependencies = [ "getrandom 0.3.4", "wasm-bindgen", @@ -16343,11 +17014,11 @@ dependencies = [ [[package]] name = "windmill-store" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "async-recursion", - "axum 0.8.9", + "axum", "base64 0.22.1", "chrono", "dashmap", @@ -16378,11 +17049,11 @@ dependencies = [ [[package]] name = "windmill-test-utils" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "async-trait", - "axum 0.8.9", + "axum", "chrono", "futures", "serde", @@ -16402,11 +17073,11 @@ dependencies = [ [[package]] name = "windmill-trigger" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "async-trait", - "axum 0.8.9", + "axum", "chrono", "http 1.5.0", "hyper 1.12.0", @@ -16435,11 +17106,11 @@ dependencies = [ [[package]] name = "windmill-trigger-amqp" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "async-trait", - "axum 0.8.9", + "axum", "base64 0.22.1", "futures", "itertools 0.14.0", @@ -16462,11 +17133,11 @@ dependencies = [ [[package]] name = "windmill-trigger-azure" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "async-trait", - "axum 0.8.9", + "axum", "base64 0.22.1", "bytes", "chrono", @@ -16495,11 +17166,11 @@ dependencies = [ [[package]] name = "windmill-trigger-email" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "async-trait", - "axum 0.8.9", + "axum", "base64 0.22.1", "lazy_static", "regex", @@ -16515,11 +17186,11 @@ dependencies = [ [[package]] name = "windmill-trigger-gcp" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "async-trait", - "axum 0.8.9", + "axum", "base64 0.22.1", "bytes", "chrono", @@ -16549,11 +17220,11 @@ dependencies = [ [[package]] name = "windmill-trigger-http" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "async-trait", - "axum 0.8.9", + "axum", "base64 0.22.1", "chrono", "constant_time_eq 0.3.1", @@ -16586,11 +17257,11 @@ dependencies = [ [[package]] name = "windmill-trigger-kafka" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "async-trait", - "axum 0.8.9", + "axum", "base64 0.22.1", "itertools 0.14.0", "rdkafka", @@ -16609,11 +17280,11 @@ dependencies = [ [[package]] name = "windmill-trigger-mqtt" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "async-trait", - "axum 0.8.9", + "axum", "base64 0.22.1", "bytes", "itertools 0.14.0", @@ -16633,12 +17304,12 @@ dependencies = [ [[package]] name = "windmill-trigger-nats" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "async-nats", "async-trait", - "axum 0.8.9", + "axum", "base64 0.22.1", "itertools 0.14.0", "nkeys", @@ -16657,11 +17328,11 @@ dependencies = [ [[package]] name = "windmill-trigger-postgres" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "async-trait", - "axum 0.8.9", + "axum", "byteorder", "bytes", "chrono", @@ -16692,7 +17363,7 @@ dependencies = [ [[package]] name = "windmill-trigger-sqs" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "async-trait", @@ -16701,7 +17372,7 @@ dependencies = [ "aws-sdk-sqs", "aws-sdk-sts", "aws-smithy-types", - "axum 0.8.9", + "axum", "backon", "chrono", "itertools 0.14.0", @@ -16720,11 +17391,11 @@ dependencies = [ [[package]] name = "windmill-trigger-websocket" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "async-trait", - "axum 0.8.9", + "axum", "base64 0.22.1", "futures", "http 1.5.0", @@ -16745,7 +17416,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "bitflags 2.13.2", @@ -16764,14 +17435,14 @@ dependencies = [ [[package]] name = "windmill-worker" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "async-once-cell", "async-recursion", "async-stream", "async-trait", - "axum 0.8.9", + "axum", "backon", "base64 0.22.1", "bit-vec 0.6.3", @@ -16799,7 +17470,6 @@ dependencies = [ "jsonwebtoken 10.4.0", "lazy_static", "libffi-sys", - "libloading", "mappable-rc", "mime_guess", "mysql_async", @@ -16816,7 +17486,7 @@ dependencies = [ "postgres-protocol", "process-wrap", "prometheus", - "prost", + "prost 0.13.5", "quick_cache", "rand 0.9.5", "rcgen", @@ -16825,8 +17495,8 @@ dependencies = [ "reqwest-middleware", "rsa", "rust_decimal", - "rustls 0.23.35", - "rustls-native-certs 0.8.4", + "rustls 0.23.40", + "rustls-native-certs 0.8.5", "rustls-pemfile 2.2.0", "serde", "serde_json", @@ -16883,7 +17553,7 @@ dependencies = [ [[package]] name = "windmill-worker-volumes" -version = "1.827.0" +version = "1.841.0" dependencies = [ "bytes", "futures", @@ -17426,9 +18096,9 @@ dependencies = [ [[package]] name = "winresource" -version = "0.1.31" +version = "0.1.34" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0986a8b1d586b7d3e4fe3d9ea39fb451ae22869dcea4aa109d287a374d866087" +checksum = "a2bc6d36480b829272a5bdabf08e6dca8004761c1da7e35efef800540c66221b" dependencies = [ "version_check", ] @@ -17479,8 +18149,25 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1301e935010a701ae5f8655edc0ad17c44bad3ac5ce8c39185f75453b720ae94" dependencies = [ "const-oid 0.9.6", - "der", - "spki", + "der 0.7.10", + "spki 0.7.3", +] + +[[package]] +name = "x509-parser" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7069fba5b66b9193bd2c5d3d4ff12b839118f6bcbef5328efafafb5395cf63da" +dependencies = [ + "asn1-rs 0.5.2", + "data-encoding", + "der-parser 8.2.0", + "lazy_static", + "nom", + "oid-registry 0.6.1", + "rusticata-macros", + "thiserror 1.0.69", + "time", ] [[package]] @@ -17586,24 +18273,24 @@ checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", "synstructure 0.14.0", ] [[package]] name = "zerocopy" -version = "0.8.61" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "879fb705ce98c32e41ebdb970fbe1204f8492423b314c6ab0354c3e7b5542866" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.61" +version = "0.8.63" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "708882a28301d604fa039cc7727607a98d04c4b86dc76ec9cc683f805d709759" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" dependencies = [ "proc-macro2", "quote", @@ -17627,7 +18314,7 @@ checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", "synstructure 0.14.0", ] @@ -17683,14 +18370,14 @@ checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" dependencies = [ "proc-macro2", "quote", - "syn 3.0.6", + "syn 3.0.9", ] [[package]] name = "zip" -version = "7.2.0" +version = "7.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c42e33efc22a0650c311c2ef19115ce232583abbe80850bc8b66509ebef02de0" +checksum = "cc12baa6db2b15a140161ce53d72209dacea594230798c24774139b54ecaa980" dependencies = [ "crc32fast", "indexmap 2.14.2", @@ -17710,6 +18397,19 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" +[[package]] +name = "zoneinfo64" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed6eb2607e906160c457fd573e9297e65029669906b9ac8fb1b5cd5e055f0705" +dependencies = [ + "calendrical_calculations", + "icu_locale_core", + "potential_utf", + "resb", + "serde", +] + [[package]] name = "zstd" version = "0.13.3" @@ -17730,9 +18430,9 @@ dependencies = [ [[package]] name = "zstd-sys" -version = "2.1.0+zstd.1.5.7" +version = "2.1.2+zstd.1.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ef0a8027ec3ee71300ab3bcbcd0393f434aa72b91ca6d635a39941deae8eea0" +checksum = "481ada9c543b2323cbb7bbdbb5249177fbf0188ed959ed2c15e4b22421c84ed3" dependencies = [ "cc", "pkg-config", diff --git a/backend/Cargo.toml b/backend/Cargo.toml index 06fdc001f0..1851f386c2 100644 --- a/backend/Cargo.toml +++ b/backend/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "windmill" -version = "1.827.0" +version = "1.841.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.827.0" +version = "1.841.0" authors = ["Ruben Fiszel "] edition = "2021" @@ -156,7 +156,7 @@ bedrock = ["windmill-ai/bedrock", "windmill-api/bedrock", "windmill-worker/bedro mqtt_trigger = ["windmill-api/mqtt_trigger"] amqp_trigger = ["windmill-api/amqp_trigger"] native_trigger = ["windmill-api/native_trigger"] -sqs_trigger = ["windmill-api/sqs_trigger", "windmill-common/aws_auth", "windmill-api/openidconnect"] +sqs_trigger = ["windmill-api/sqs_trigger", "windmill-common/aws_auth", "openidconnect"] gcp_trigger = ["windmill-api/gcp_trigger"] azure_trigger = ["windmill-api/azure_trigger"] smtp = ["windmill-api/smtp", "windmill-common/smtp", "windmill-queue/smtp"] @@ -226,7 +226,12 @@ all_sqlx_features = ["all_languages", "enterprise", "enterprise_saml", "embeddin "windmill-git-sync/all_sqlx_features"] [patch.crates-io] -# v0.8.6 plus one commit: `Pool::begin` is not cancel-safe on Postgres. sqlx raises the +# v0.8.6 plus the fix below and two `#[sqlx::test]`-only changes, both set in .cargo/config.toml: +# `SQLX_TEST_TEMPLATE` clones each test database from a template migrated once per migration +# set instead of migrating it per test, and `SQLX_TEST_MAX_CONNECTIONS` lifts the cap on the +# connections all test pools share. The rev is tagged `windmill-0.8.6-test-template-c1c5f1f` in +# the fork so it stays fetchable. +# The fix: `Pool::begin` is not cancel-safe on Postgres. sqlx raises the # transaction depth its rollback-on-drop guard keys on only *after* the BEGIN round trip, so # a cancelled caller (a disconnecting API client, a `timeout`, an aborted task) leaves the # session in a transaction nothing will end, and the pool hands that connection out again — @@ -239,13 +244,13 @@ all_sqlx_features = ["all_languages", "enterprise", "enterprise_saml", "embeddin # Changing any of this — a bump, a rebase of the fork, dropping these lines — still compiles # clean, so run the guard that actually checks the behaviour is still there: # cargo test -p windmill-common --test sqlx_begin_cancel_safe -- --ignored -sqlx = { git = "https://github.com/windmill-labs/sqlx", rev = "6bdaee94fa62a01561125646da3f99eb341f2457" } -sqlx-core = { git = "https://github.com/windmill-labs/sqlx", rev = "6bdaee94fa62a01561125646da3f99eb341f2457" } -sqlx-macros = { git = "https://github.com/windmill-labs/sqlx", rev = "6bdaee94fa62a01561125646da3f99eb341f2457" } -sqlx-macros-core = { git = "https://github.com/windmill-labs/sqlx", rev = "6bdaee94fa62a01561125646da3f99eb341f2457" } -sqlx-postgres = { git = "https://github.com/windmill-labs/sqlx", rev = "6bdaee94fa62a01561125646da3f99eb341f2457" } -sqlx-mysql = { git = "https://github.com/windmill-labs/sqlx", rev = "6bdaee94fa62a01561125646da3f99eb341f2457" } -sqlx-sqlite = { git = "https://github.com/windmill-labs/sqlx", rev = "6bdaee94fa62a01561125646da3f99eb341f2457" } +sqlx = { git = "https://github.com/windmill-labs/sqlx", rev = "c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" } +sqlx-core = { git = "https://github.com/windmill-labs/sqlx", rev = "c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" } +sqlx-macros = { git = "https://github.com/windmill-labs/sqlx", rev = "c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" } +sqlx-macros-core = { git = "https://github.com/windmill-labs/sqlx", rev = "c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" } +sqlx-postgres = { git = "https://github.com/windmill-labs/sqlx", rev = "c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" } +sqlx-mysql = { git = "https://github.com/windmill-labs/sqlx", rev = "c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" } +sqlx-sqlite = { git = "https://github.com/windmill-labs/sqlx", rev = "c1c5f1f2a07cb1fce0e47463c314697e08f4f26b" } object_store = { git = "https://github.com/apache/arrow-rs-object-store", rev = "36752c975d4f29e20b57c91f81a10872dcd48ae7" } # Use tiberius main branch for libgssapi 0.8.1 fix (https://github.com/prisma/tiberius/issues/343) tiberius = { git = "https://github.com/prisma/tiberius", rev = "59db57960a14b422fb3a1309aa4aa47880896ff8" } @@ -281,6 +286,7 @@ windmill-api = { workspace = true, default-features = false } windmill-api-agent-workers = { workspace = true, optional = true } windmill-api-scripts.workspace = true windmill-api-settings.workspace = true +windmill-audit.workspace = true windmill-worker.workspace = true windmill-indexer = { workspace = true, optional = true } windmill-autoscaling = { workspace = true, optional = true } @@ -451,7 +457,7 @@ headers = "^0" hyper = { version = "^1", features = ["full"] } hyper-tls = "^0.6" hyper-util = { version = "^0.1", features = ["client-legacy", "http1", "tokio"] } -tokio = { version = "=1.46.1", features = ["full", "tracing", "time"] } +tokio = { version = "=1.53.2", features = ["full", "tracing", "time"] } tokio-stream = { version = "0.1.17" } tower = "^0" tower-http = { version = "^0.6", features = ["trace", "cors", "catch-panic"] } @@ -488,9 +494,11 @@ arc-swap = "1" ed25519-dalek = { version = "2", features = ["rand_core"] } magic-crypt = "^3" git-version = "^0" -malachite = "=0.4.18" -malachite-bigint = "=0.2.0" -rustpython-parser = "^0" +# Ruff's parser crates are internal to ruff and carry no semver guarantee: pin them exactly, +# and to the same release. +ruff_python_parser = "=0.0.17" +ruff_python_ast = "=0.0.17" +ruff_text_size = "=0.0.17" pep440_rs = "0.7.3" php-parser-rs = { git = "https://github.com/php-rust-tools/parser", rev = "ec4cb411dec09450946ef57920b7ffced7f6495d" } cron = "^0" @@ -498,6 +506,7 @@ mail-send = { version = "0.4.0", features = ["builder"], default-features=false urlencoding = "^2" quick-xml = { version = "^0.37", features = ["serialize"] } url = { version = "^2" , features = ["serde"]} +ipnet = "2" async-oauth2 = "0.5.1" reqwest = { version = "^0.13", features = ["json", "stream", "gzip", "multipart", "query", "form"] } # The reqwest object_store builds its HTTP clients with, for a custom `HttpConnector`. @@ -519,33 +528,29 @@ aws-sdk-rds = "^1" async-trait = "0.1.88" -v8 = "=137.1.0" # Exact version NOTE: Do not forget to update version and hash in flake.nix -# deno_* pin set: deno v2.4.0 base, with deno_ast force-overridden to =0.51.0. -# Rationale: deno_ast 0.51.0 is the first version pulling swc_common =14.0.4, -# the first swc_common patch that dropped `pub use serde::__private as serde;` -# (the line that capped our workspace serde pin at =1.0.220). v2.4.0's other -# pins keep deno_tls at 0.196.0 which uses permissive `rustls ^0.23.11`, -# compatible with aws-sdk-bedrockruntime's `^0.23.31` requirement. deno_tls -# 0.198+ tightened that to exact `=0.23.28`, which would have made any -# meaningful deno bump resolver-impossible against aws-sdk. -deno_fetch = "0.233.0" -deno_tls = "0.196.0" -deno_console = "0.209.0" -deno_url = "0.209.0" -deno_webidl = "0.209.0" -deno_web = "0.240.0" -# Sibling release of the pinned deno_core 0.352 / deno_web 0.240 stack -# (its deps are deno_core ^0.352, deno_web ^0.240, deno_error =0.6.1). A newer -# deno_crypto would force bumping the whole deno stack. -deno_crypto = "0.223.0" -deno_io = "0.119.0" -deno_fs = "0.119.0" -deno_net = "0.201.0" -deno_core = "0.352.0" +# deno_* pin set: the crates deno published together on 2026-09-16 (deno_core +# 0.412). +# V8 is pinned exactly because flake.nix fetches the prebuilt archive of that +# version: update its version and hash there with any bump. No default features, +# so the pin leaves the feature set deno_core picks untouched. +v8 = { version = "=150.4.0", default-features = false } +# These release as a matched set: each pins its siblings, deno_error exactly, +# and deno_tls pins rustls exactly (=0.23.40, the workspace `rustls` pin below +# must equal it). A bump moves all of them at once. +# deno_ast is independent of that set and stays at 0.51.0: a newer one pulls +# swc_common 17, which would force bumping every swc_* pin the parsers use. +deno_fetch = "0.283.0" +deno_tls = "0.246.0" +deno_webidl = "0.259.0" +deno_web = "0.290.0" +deno_crypto = "0.273.0" +deno_net = "0.251.0" +deno_core = "0.412.0" deno_ast = { version = "=0.51.0", features = ["transpiling"] } -deno_permissions = "0.68.0" -deno_telemetry = "0.31.0" -deno_error = "=0.6.1" +deno_permissions = "0.118.0" +deno_telemetry = "0.81.0" +deno_error = "=0.7.1" +sys_traits = { version = "0.1.28", features = ["real", "libc", "winapi"] } rustls-pemfile = "2.2.0" # only used with special deno_core_mac feature to prevent ffi issue on macos, requires libffi to be installed @@ -596,9 +601,11 @@ const_format = { version = "0.2.35", features = ["rust_1_64", "rust_1_51"] } const-str = "0.5" constant_time_eq = "0.3.1" rsa = "^0" +p256 = "0.13" spki = { version = "0.7", features = ["pem"] } pkcs1 = "0.7" aes-gcm = "0.10.3" +hkdf = "0.12.4" async_zip = { version = "0.0.17", features = ["tokio", "tokio-fs", "deflate", "chrono"] } once_cell = "1.17.1" dashmap = "6.1.0" @@ -682,7 +689,7 @@ aws-sdk-sqs = "^1.89.0" aws-sdk-sts = "^1.91.0" aws-sdk-sso = "=1.77.0" aws-sdk-ssooidc = "=1.78.0" -rustls = "=0.23.35" +rustls = "=0.23.40" async-once-cell = "0.5.4" size = "0.5.0" @@ -722,7 +729,6 @@ flume = { version = "0.11.1", features = ["async"] } kube = { version = "1.1.0", features = ["runtime", "derive"] } schemars = "0.8" k8s-openapi = { version = "0.25.0", features = ["latest"] } -libloading = "0.8.8" # Macro-related proc-macro2 = "1.0" diff --git a/backend/ee-repo-ref.txt b/backend/ee-repo-ref.txt index 5a36bc5e61..37990aa852 100644 --- a/backend/ee-repo-ref.txt +++ b/backend/ee-repo-ref.txt @@ -1 +1 @@ -e5689bf58a125ff46aabb6b5d0f030a7e5c715d3 +e922599943c472a6d0f736f629ae04081f866686 diff --git a/backend/migrations/20261008070335_worker_ping_draining.down.sql b/backend/migrations/20261008070335_worker_ping_draining.down.sql new file mode 100644 index 0000000000..64a5f2949d --- /dev/null +++ b/backend/migrations/20261008070335_worker_ping_draining.down.sql @@ -0,0 +1 @@ +ALTER TABLE worker_ping DROP COLUMN IF EXISTS draining; diff --git a/backend/migrations/20261008070335_worker_ping_draining.up.sql b/backend/migrations/20261008070335_worker_ping_draining.up.sql new file mode 100644 index 0000000000..33b5ad5e3e --- /dev/null +++ b/backend/migrations/20261008070335_worker_ping_draining.up.sql @@ -0,0 +1 @@ +ALTER TABLE worker_ping ADD COLUMN IF NOT EXISTS draining BOOLEAN NOT NULL DEFAULT FALSE; diff --git a/backend/migrations/20261008165042_runnable_job_stats.down.sql b/backend/migrations/20261008165042_runnable_job_stats.down.sql new file mode 100644 index 0000000000..21208736b4 --- /dev/null +++ b/backend/migrations/20261008165042_runnable_job_stats.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS runnable_job_stats; diff --git a/backend/migrations/20261008165042_runnable_job_stats.up.sql b/backend/migrations/20261008165042_runnable_job_stats.up.sql new file mode 100644 index 0000000000..cf676a037e --- /dev/null +++ b/backend/migrations/20261008165042_runnable_job_stats.up.sql @@ -0,0 +1,17 @@ +-- Hourly resource rollup per runnable and worker group, fed by the workers. +-- Memory figures are in kB, like v2_job_completed.memory_peak. +-- No foreign key to workspace: every worker upserts here, and the key would cost each row +-- a lookup and a lock on its workspace. Workspace deletion removes the rows itself. +CREATE TABLE IF NOT EXISTS runnable_job_stats ( + hour BIGINT NOT NULL, + workspace_id VARCHAR(50) NOT NULL, + runnable_path VARCHAR(255) NOT NULL, + worker_group TEXT NOT NULL, + job_count INTEGER NOT NULL DEFAULT 0, + total_duration_ms BIGINT NOT NULL DEFAULT 0, + max_memory_peak INTEGER NOT NULL DEFAULT 0, + sum_memory_peak BIGINT NOT NULL DEFAULT 0, + memory_sample_count INTEGER NOT NULL DEFAULT 0, + total_cpu_ms BIGINT NOT NULL DEFAULT 0, + PRIMARY KEY (hour, workspace_id, runnable_path, worker_group) +); diff --git a/backend/migrations/20261009164611_add_agent_favorite_kind.down.sql b/backend/migrations/20261009164611_add_agent_favorite_kind.down.sql new file mode 100644 index 0000000000..c50ff19ab5 --- /dev/null +++ b/backend/migrations/20261009164611_add_agent_favorite_kind.down.sql @@ -0,0 +1 @@ +DELETE FROM favorite WHERE favorite_kind = 'agent'; diff --git a/backend/migrations/20261009164611_add_agent_favorite_kind.up.sql b/backend/migrations/20261009164611_add_agent_favorite_kind.up.sql new file mode 100644 index 0000000000..c0959d2527 --- /dev/null +++ b/backend/migrations/20261009164611_add_agent_favorite_kind.up.sql @@ -0,0 +1,8 @@ +DO +$do$ +BEGIN + ALTER TYPE FAVORITE_KIND ADD VALUE 'agent'; +EXCEPTION WHEN OTHERS THEN + RAISE NOTICE 'Couldn''t create FAVORITE_KIND::agent: %', SQLERRM; +END +$do$; diff --git a/backend/migrations/20261009173546_agent_owner_prefix_index.down.sql b/backend/migrations/20261009173546_agent_owner_prefix_index.down.sql new file mode 100644 index 0000000000..d3e9318571 --- /dev/null +++ b/backend/migrations/20261009173546_agent_owner_prefix_index.down.sql @@ -0,0 +1 @@ +DROP INDEX IF EXISTS idx_resource_agent_owner_prefix; diff --git a/backend/migrations/20261009173546_agent_owner_prefix_index.up.sql b/backend/migrations/20261009173546_agent_owner_prefix_index.up.sql new file mode 100644 index 0000000000..be1fd5813f --- /dev/null +++ b/backend/migrations/20261009173546_agent_owner_prefix_index.up.sql @@ -0,0 +1,7 @@ +-- Backs the agent branch of /runnables/list and /runnables/counts, which reach the +-- `ai_agent` rows of `resource` by workspace and byte-ordered path prefix. Partial, so +-- neither walks the workspace's other resources (state, cache, ...). +-- Created CONCURRENTLY via the OVERRIDDEN_MIGRATIONS rewrite in windmill-api/src/db.rs. +CREATE INDEX IF NOT EXISTS idx_resource_agent_owner_prefix + ON resource (workspace_id, path text_pattern_ops) + WHERE resource_type = 'ai_agent'; diff --git a/backend/migrations/20261012180101_datatable_role_set.down.sql b/backend/migrations/20261012180101_datatable_role_set.down.sql new file mode 100644 index 0000000000..15384edae8 --- /dev/null +++ b/backend/migrations/20261012180101_datatable_role_set.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS datatable_role_set; diff --git a/backend/migrations/20261012180101_datatable_role_set.up.sql b/backend/migrations/20261012180101_datatable_role_set.up.sql new file mode 100644 index 0000000000..0093837d3b --- /dev/null +++ b/backend/migrations/20261012180101_datatable_role_set.up.sql @@ -0,0 +1,21 @@ +-- The logins behind a data table connection made as several roles at once: one Postgres login per +-- distinct set of data table roles, a member of each. Which roles a login holds is its +-- memberships on the cluster, and its name is derived from their catalog ids, so a row only has to +-- carry the credential. +-- +-- A row is written after its login exists and removed before the login is dropped, so a row always +-- names a login that can authenticate with `pwd`. +CREATE TABLE datatable_role_set ( + cluster VARCHAR(20) NOT NULL CHECK (cluster IN ('instance', 'external_instance')), + name VARCHAR(63) NOT NULL, + -- Generated by Windmill, never entered by anyone, and never leaves the server. + pwd TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + -- Recorded at most once a day. A login unused for long enough is dropped, and made again if + -- its set of roles is asked for later. + last_used_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (cluster, name) +); + +GRANT ALL ON datatable_role_set TO windmill_user; +GRANT ALL ON datatable_role_set TO windmill_admin; diff --git a/backend/migrations/20261012213357_widen_variable_value.down.sql b/backend/migrations/20261012213357_widen_variable_value.down.sql new file mode 100644 index 0000000000..48b61c3f65 --- /dev/null +++ b/backend/migrations/20261012213357_widen_variable_value.down.sql @@ -0,0 +1,12 @@ +DO $$ +DECLARE + too_long BIGINT; +BEGIN + SELECT count(*) INTO too_long FROM variable WHERE length(value) > 15000; + IF too_long > 0 THEN + RAISE EXCEPTION 'cannot narrow variable.value to VARCHAR(15000): % row(s) are longer than 15000 characters', too_long; + END IF; +END $$; + +ALTER TABLE variable DROP CONSTRAINT IF EXISTS variable_value_length; +ALTER TABLE variable ALTER COLUMN value TYPE VARCHAR(15000); diff --git a/backend/migrations/20261012213357_widen_variable_value.up.sql b/backend/migrations/20261012213357_widen_variable_value.up.sql new file mode 100644 index 0000000000..06dc8a191a --- /dev/null +++ b/backend/migrations/20261012213357_widen_variable_value.up.sql @@ -0,0 +1,8 @@ +-- AES-256-GCM ciphertext is 32 bytes (magic, nonce, tag) longer than legacy CBC before base64, +-- so the longest CBC value that fits 15000 chars is exactly 15040 chars once re-encrypted. +ALTER TABLE variable ALTER COLUMN value TYPE VARCHAR(15040); + +-- Only GCM secrets (base64 of the `wmA2` magic starts `d21BM`) may use the extra room: a longer +-- CBC value could never be re-encrypted to fit, and would fail every rotation of its workspace key. +ALTER TABLE variable ADD CONSTRAINT variable_value_length + CHECK (length(value) <= 15000 OR (is_secret AND value LIKE 'd21BM%')); diff --git a/backend/migrations/20261013165527_job_perms_viewer_data_access.down.sql b/backend/migrations/20261013165527_job_perms_viewer_data_access.down.sql new file mode 100644 index 0000000000..6741203ade --- /dev/null +++ b/backend/migrations/20261013165527_job_perms_viewer_data_access.down.sql @@ -0,0 +1 @@ +ALTER TABLE job_perms DROP COLUMN IF EXISTS viewer_data_access; diff --git a/backend/migrations/20261013165527_job_perms_viewer_data_access.up.sql b/backend/migrations/20261013165527_job_perms_viewer_data_access.up.sql new file mode 100644 index 0000000000..5d6a41ece4 --- /dev/null +++ b/backend/migrations/20261013165527_job_perms_viewer_data_access.up.sql @@ -0,0 +1,4 @@ +-- Set by the server on a job pushed for an app runnable whose policy says it reads data as its +-- viewer: data table connections that name no role and object storage permission rules then go by +-- end_user_email instead of the job's own identity. +ALTER TABLE job_perms ADD COLUMN IF NOT EXISTS viewer_data_access BOOLEAN NOT NULL DEFAULT false; diff --git a/backend/migrations/20261015063444_app_script_modules.down.sql b/backend/migrations/20261015063444_app_script_modules.down.sql new file mode 100644 index 0000000000..026e1e841a --- /dev/null +++ b/backend/migrations/20261015063444_app_script_modules.down.sql @@ -0,0 +1 @@ +ALTER TABLE app_script DROP COLUMN IF EXISTS modules; diff --git a/backend/migrations/20261015063444_app_script_modules.up.sql b/backend/migrations/20261015063444_app_script_modules.up.sql new file mode 100644 index 0000000000..aa8e6d5fb2 --- /dev/null +++ b/backend/migrations/20261015063444_app_script_modules.up.sql @@ -0,0 +1 @@ +ALTER TABLE app_script ADD COLUMN IF NOT EXISTS modules JSONB; diff --git a/backend/migrations/20261015114712_queue_workspace_scheduled_for_index.down.sql b/backend/migrations/20261015114712_queue_workspace_scheduled_for_index.down.sql new file mode 100644 index 0000000000..bebd678a1a --- /dev/null +++ b/backend/migrations/20261015114712_queue_workspace_scheduled_for_index.down.sql @@ -0,0 +1 @@ +DROP INDEX IF EXISTS v2_job_queue_workspace_scheduled_for; diff --git a/backend/migrations/20261015114712_queue_workspace_scheduled_for_index.up.sql b/backend/migrations/20261015114712_queue_workspace_scheduled_for_index.up.sql new file mode 100644 index 0000000000..63a22e003b --- /dev/null +++ b/backend/migrations/20261015114712_queue_workspace_scheduled_for_index.up.sql @@ -0,0 +1,10 @@ +-- Serves push_scheduled_job's already-exists check in windmill-queue/src/schedule.rs, which +-- looks up the queued jobs of one workspace at one occurrence. Without it that check scans the +-- whole queue on every schedule push. +-- Dropped before it is built because the OVERRIDDEN_MIGRATIONS rewrite in +-- windmill-api/src/db.rs runs both CONCURRENTLY: an interrupted concurrent build leaves an +-- invalid index that IF NOT EXISTS would skip rebuilding. +DROP INDEX IF EXISTS v2_job_queue_workspace_scheduled_for; + +CREATE INDEX IF NOT EXISTS v2_job_queue_workspace_scheduled_for + ON v2_job_queue (workspace_id, scheduled_for); diff --git a/backend/migrations/20261015135223_agent_on_behalf_of.down.sql b/backend/migrations/20261015135223_agent_on_behalf_of.down.sql new file mode 100644 index 0000000000..62cbe2e5de --- /dev/null +++ b/backend/migrations/20261015135223_agent_on_behalf_of.down.sql @@ -0,0 +1 @@ +-- Nothing to undo: older versions ignore both keys, and clearing them would drop toggles set since. diff --git a/backend/migrations/20261015135223_agent_on_behalf_of.up.sql b/backend/migrations/20261015135223_agent_on_behalf_of.up.sql new file mode 100644 index 0000000000..fce313d09a --- /dev/null +++ b/backend/migrations/20261015135223_agent_on_behalf_of.up.sql @@ -0,0 +1,19 @@ +-- An AI agent's `run_on_behalf_of` makes runs from its page take the identity in its +-- `on_behalf_of`, which the server resolves on every write. Before this, both keys were ordinary +-- JSON any writer of the agent could set, so a value written then could name someone else's +-- identity unchecked: clear them, and every agent starts with the toggle off. +UPDATE resource + SET value = value - 'on_behalf_of' - 'run_on_behalf_of' + WHERE resource_type = 'ai_agent' + AND jsonb_typeof(value) = 'object' + AND (value ? 'on_behalf_of' OR value ? 'run_on_behalf_of'); + +-- A deleted agent comes back from the trash as stored, so its copy there is cleared too. +UPDATE trashbin + SET item_data = jsonb_set(item_data, '{row,value}', + (item_data->'row'->'value') - 'on_behalf_of' - 'run_on_behalf_of') + WHERE item_kind = 'resource' + AND item_data->'row'->>'resource_type' = 'ai_agent' + AND jsonb_typeof(item_data->'row'->'value') = 'object' + AND (item_data->'row'->'value' ? 'on_behalf_of' + OR item_data->'row'->'value' ? 'run_on_behalf_of'); diff --git a/backend/migrations/20261015155831_ai_shared_session.down.sql b/backend/migrations/20261015155831_ai_shared_session.down.sql new file mode 100644 index 0000000000..bf6a32d4de --- /dev/null +++ b/backend/migrations/20261015155831_ai_shared_session.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS ai_shared_session; diff --git a/backend/migrations/20261015155831_ai_shared_session.up.sql b/backend/migrations/20261015155831_ai_shared_session.up.sql new file mode 100644 index 0000000000..37e8939c3b --- /dev/null +++ b/backend/migrations/20261015155831_ai_shared_session.up.sql @@ -0,0 +1,30 @@ +-- A read-only snapshot of an AI session transcript that its author shared by link. Sessions +-- otherwise live only in the author's browser; this row exists only while the share does. +-- Non-public shares are readable by members of the workspace, public ones by anyone with the +-- link, which is why `id` is a random UUID and never derived from the session. +CREATE TABLE ai_shared_session ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + workspace_id VARCHAR(50) NOT NULL REFERENCES workspace(id) ON DELETE CASCADE, + -- The browser-side session id. Unique per author so sharing the same session again + -- moves its one link forward rather than minting a second one. + session_id VARCHAR(255) NOT NULL, + email VARCHAR(255) NOT NULL, + created_by VARCHAR(255) NOT NULL, + name VARCHAR(255) NOT NULL, + is_public BOOLEAN NOT NULL DEFAULT false, + message_count INTEGER NOT NULL, + -- JSON kept as text: jsonb refuses the \u0000 escape a transcript can carry. + snapshot TEXT NOT NULL, + shared_at TIMESTAMPTZ NOT NULL DEFAULT now(), + UNIQUE (workspace_id, email, session_id) +); + +GRANT ALL ON ai_shared_session TO windmill_admin; +GRANT ALL ON ai_shared_session TO windmill_user; + +-- The handlers go through the raw pool and scope every query to the workspace themselves. +-- An admin-only policy is the backstop for a future query that reaches this table through +-- UserDB. +ALTER TABLE ai_shared_session ENABLE ROW LEVEL SECURITY; + +CREATE POLICY admin_policy ON ai_shared_session FOR ALL TO windmill_admin USING (true); diff --git a/backend/migrations/20261016120000_ms_teams_oauth_key.down.sql b/backend/migrations/20261016120000_ms_teams_oauth_key.down.sql new file mode 100644 index 0000000000..77a3e3dc5f --- /dev/null +++ b/backend/migrations/20261016120000_ms_teams_oauth_key.down.sql @@ -0,0 +1,4 @@ +-- Fold edits made under ms_teams back into `teams`, which the previous version reads. +UPDATE global_settings +SET value = (value - 'ms_teams') || jsonb_build_object('teams', value -> 'ms_teams') +WHERE name = 'oauths' AND value ? 'ms_teams'; diff --git a/backend/migrations/20261016120000_ms_teams_oauth_key.up.sql b/backend/migrations/20261016120000_ms_teams_oauth_key.up.sql new file mode 100644 index 0000000000..ab2462db8b --- /dev/null +++ b/backend/migrations/20261016120000_ms_teams_oauth_key.up.sql @@ -0,0 +1,6 @@ +-- The Teams Entra app now lives under oauths.ms_teams (bot + Graph connect). Copy the old +-- `teams` entry and keep it, so servers still on the previous version keep working during a +-- rolling upgrade. +UPDATE global_settings +SET value = value || jsonb_build_object('ms_teams', value -> 'teams') +WHERE name = 'oauths' AND value ? 'teams' AND NOT value ? 'ms_teams'; diff --git a/backend/migrations/20261016160346_fork_storage_namespace.down.sql b/backend/migrations/20261016160346_fork_storage_namespace.down.sql new file mode 100644 index 0000000000..47c6b58649 --- /dev/null +++ b/backend/migrations/20261016160346_fork_storage_namespace.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS fork_storage_namespace; diff --git a/backend/migrations/20261016160346_fork_storage_namespace.up.sql b/backend/migrations/20261016160346_fork_storage_namespace.up.sql new file mode 100644 index 0000000000..247a9e2da9 --- /dev/null +++ b/backend/migrations/20261016160346_fork_storage_namespace.up.sql @@ -0,0 +1,24 @@ +-- Workspace storages a fork/dev workspace isolates from its parent: its writes land under +-- `__wm_forks//` of that storage, and its reads fall back to the parent's keys. +-- One row per (fork, storage) chosen isolated at fork creation; forks created before this +-- table have none and keep sharing the parent's keys. +-- +-- Deliberately NO foreign key to workspace(id), like fork_ducklake_namespace: rows are also the +-- cleanup ledger and must OUTLIVE the workspace row when deleting the prefix fails after the +-- delete commits. A recreated same-id fork would otherwise read the deleted fork's objects +-- under the deterministic prefix; fork creation retries leftover rows and refuses to proceed +-- while they cannot be cleaned. +CREATE TABLE fork_storage_namespace ( + workspace_id VARCHAR(50) NOT NULL, + -- '' = the default storage, else a `secondary_storage` name. + storage TEXT NOT NULL, + -- The storage's resolved identity at fork creation (`:`), so cleanup deletes the prefix from the storage the fork wrote to even if the + -- name is repointed later. + storage_ref TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + PRIMARY KEY (workspace_id, storage) +); + +GRANT ALL ON fork_storage_namespace TO windmill_user; +GRANT ALL ON fork_storage_namespace TO windmill_admin; diff --git a/backend/oauth_connect.json b/backend/oauth_connect.json index 3c4de3b082..611e3f7c17 100644 --- a/backend/oauth_connect.json +++ b/backend/oauth_connect.json @@ -3,7 +3,7 @@ "auth_url": "https://github.com/login/oauth/authorize", "token_url": "https://github.com/login/oauth/access_token", "scopes": ["workflow", "repo"], - "scope_options": ["repo", "workflow", "gist", "read:org"] + "scope_options": ["repo", "workflow", "gist", "read:org", "read:project", "project"] }, "gitlab": { "auth_url": "https://gitlab.com/oauth/authorize", @@ -125,6 +125,69 @@ "prompt": "consent" } }, + "ms_onedrive": { + "req_body_auth": true, + "scopes": ["offline_access", "User.Read", "Files.ReadWrite"], + "scope_options": [ + { "value": "offline_access", "label": "Stay connected (refresh token)" }, + { "value": "User.Read", "label": "Read your profile" }, + { "value": "Files.Read", "label": "Read your files" }, + { "value": "Files.ReadWrite", "label": "Read, upload, edit and delete your files" }, + { "value": "Files.Read.All", "label": "Read all files you can access (shared and SharePoint drives)" }, + { "value": "Files.ReadWrite.All", "label": "Read and edit all files you can access (shared and SharePoint drives)" } + ], + "connect_config_template": { + "display_name": "Microsoft OneDrive", + "label": "Microsoft Entra tenant", + "placeholder": "common, organizations, or your tenant id", + "help_url": "https://learn.microsoft.com/en-us/entra/identity-platform/v2-protocols#endpoints", + "auth_url": "https://login.microsoftonline.com/{instance}/oauth2/v2.0/authorize", + "token_url": "https://login.microsoftonline.com/{instance}/oauth2/v2.0/token", + "req_body_auth": true, + "scopes": ["offline_access", "User.Read", "Files.ReadWrite"] + } + }, + "ms_sharepoint": { + "req_body_auth": true, + "scopes": ["offline_access", "User.Read", "Sites.ReadWrite.All"], + "scope_options": [ + { "value": "offline_access", "label": "Stay connected (refresh token)" }, + { "value": "User.Read", "label": "Read your profile" }, + { "value": "Sites.Read.All", "label": "Read sites, lists and files" }, + { "value": "Sites.ReadWrite.All", "label": "Read and edit lists, list items and files in all sites" }, + { "value": "Sites.Manage.All", "label": "Create and manage lists and libraries" } + ], + "connect_config_template": { + "display_name": "Microsoft SharePoint", + "label": "Microsoft Entra tenant", + "placeholder": "common, organizations, or your tenant id", + "help_url": "https://learn.microsoft.com/en-us/entra/identity-platform/v2-protocols#endpoints", + "auth_url": "https://login.microsoftonline.com/{instance}/oauth2/v2.0/authorize", + "token_url": "https://login.microsoftonline.com/{instance}/oauth2/v2.0/token", + "req_body_auth": true, + "scopes": ["offline_access", "User.Read", "Sites.ReadWrite.All"] + } + }, + "ms_excel": { + "req_body_auth": true, + "scopes": ["offline_access", "User.Read", "Files.ReadWrite"], + "scope_options": [ + { "value": "offline_access", "label": "Stay connected (refresh token)" }, + { "value": "User.Read", "label": "Read your profile" }, + { "value": "Files.ReadWrite", "label": "Read and edit workbooks in your OneDrive" }, + { "value": "Files.ReadWrite.All", "label": "Read and edit workbooks in shared and SharePoint drives" } + ], + "connect_config_template": { + "display_name": "Microsoft Excel", + "label": "Microsoft Entra tenant", + "placeholder": "common, organizations, or your tenant id", + "help_url": "https://learn.microsoft.com/en-us/entra/identity-platform/v2-protocols#endpoints", + "auth_url": "https://login.microsoftonline.com/{instance}/oauth2/v2.0/authorize", + "token_url": "https://login.microsoftonline.com/{instance}/oauth2/v2.0/token", + "req_body_auth": true, + "scopes": ["offline_access", "User.Read", "Files.ReadWrite"] + } + }, "gmail": { "auth_url": "https://accounts.google.com/o/oauth2/v2/auth", "token_url": "https://oauth2.googleapis.com/token", @@ -254,6 +317,14 @@ "type": "web_server" } }, + "asana": { + "auth_url": "https://app.asana.com/-/oauth_authorize", + "token_url": "https://app.asana.com/-/oauth_token", + "scopes": ["default"], + "scope_options": [ + { "value": "default", "label": "Full permissions (the Asana app must be registered with Full permissions)" } + ] + }, "notion": { "auth_url": "https://api.notion.com/v1/oauth/authorize", "token_url": "https://api.notion.com/v1/oauth/token", @@ -317,6 +388,20 @@ } } }, + "shopify": { + "grant_types": ["client_credentials"], + "connect_config_template": { + "display_name": "Shopify", + "label": "Shopify store", + "placeholder": "your-store", + "help_url": "https://shopify.dev/docs/apps/build/authentication-authorization/access-tokens/client-credentials-grant", + "token_url": "https://{instance}.myshopify.com/admin/oauth/access_token", + "strip_suffix": ".myshopify.com", + "resource_mapping": { + "store_name": "{instance}" + } + } + }, "sage_intacct": { "auth_url": "https://api.intacct.com/ia/api/v1/oauth2/authorize", "token_url": "https://api.intacct.com/ia/api/v1/oauth2/token", @@ -415,6 +500,101 @@ } } }, + "ms_teams": { + "req_body_auth": true, + "scopes": [ + "offline_access", + "User.Read", + "Team.ReadBasic.All", + "Channel.ReadBasic.All", + "ChannelMessage.Send", + "Chat.ReadWrite", + "OnlineMeetings.ReadWrite" + ], + "scope_options": [ + { + "value": "offline_access", + "label": "Stay connected (refresh token)" + }, + { + "value": "User.Read", + "label": "Read your profile" + }, + { + "value": "Team.ReadBasic.All", + "label": "List your teams" + }, + { + "value": "Channel.ReadBasic.All", + "label": "List channels" + }, + { + "value": "ChannelMessage.Send", + "label": "Post and reply in channels" + }, + { + "value": "Chat.ReadWrite", + "label": "Read, create and send in your chats" + }, + { + "value": "Chat.ReadBasic", + "label": "List your chats" + }, + { + "value": "Chat.Read", + "label": "Read your chat messages" + }, + { + "value": "Chat.Create", + "label": "Create chats" + }, + { + "value": "ChatMessage.Send", + "label": "Send chat messages" + }, + { + "value": "OnlineMeetings.ReadWrite", + "label": "Create and read online meetings" + }, + { + "value": "ChannelMessage.Read.All", + "label": "Read channel messages (admin consent)" + }, + { + "value": "ChannelMember.Read.All", + "label": "List channel members (admin consent)" + }, + { + "value": "TeamMember.Read.All", + "label": "List team members (admin consent)" + }, + { + "value": "Channel.Create", + "label": "Create channels (admin consent)" + }, + { + "value": "Schedule.Read.All", + "label": "Read Shifts schedules (admin consent)" + } + ], + "connect_config_template": { + "label": "Microsoft Entra tenant", + "placeholder": "organizations, or your tenant id", + "help_url": "https://learn.microsoft.com/en-us/entra/identity-platform/v2-protocols#endpoints", + "auth_url": "https://login.microsoftonline.com/{instance}/oauth2/v2.0/authorize", + "token_url": "https://login.microsoftonline.com/{instance}/oauth2/v2.0/token", + "req_body_auth": true, + "scopes": [ + "offline_access", + "User.Read", + "Team.ReadBasic.All", + "Channel.ReadBasic.All", + "ChannelMessage.Send", + "Chat.ReadWrite", + "OnlineMeetings.ReadWrite" + ] + } + }, "netsuite": { "connect_config_template": { "display_name": "NetSuite", @@ -445,5 +625,114 @@ "mailboxes.read" ], "req_body_auth": true + }, + "ms_outlook": { + "req_body_auth": true, + "scopes": ["offline_access", "User.Read", "Mail.ReadWrite", "Mail.Send", "Calendars.ReadWrite", "Contacts.ReadWrite"], + "scope_options": [ + { "value": "offline_access", "label": "Stay connected (refresh token)" }, + { "value": "User.Read", "label": "Read your profile" }, + { "value": "Mail.Send", "label": "Send mail" }, + { "value": "Mail.Read", "label": "Read and search mail" }, + { "value": "Mail.ReadWrite", "label": "Read, draft, move and modify mail" }, + { "value": "MailboxSettings.Read", "label": "Read mailbox settings and categories" }, + { "value": "Contacts.Read", "label": "Read contacts" }, + { "value": "Contacts.ReadWrite", "label": "Read, create and edit contacts" }, + { "value": "People.Read", "label": "Search relevant people" }, + { "value": "Calendars.Read", "label": "Read calendars and events" }, + { "value": "Calendars.ReadWrite", "label": "Read, create, edit and delete events" }, + { "value": "Calendars.Read.Shared", "label": "Read shared calendars and find meeting times" }, + { "value": "Mail.Send.Shared", "label": "Send mail from shared mailboxes" }, + { "value": "Mail.Read.Shared", "label": "Read mail in shared mailboxes" }, + { "value": "Mail.ReadWrite.Shared", "label": "Read and modify mail in shared mailboxes" } + ], + "connect_config_template": { + "display_name": "Outlook", + "label": "Microsoft Entra tenant", + "placeholder": "common, organizations, or your tenant id", + "help_url": "https://learn.microsoft.com/en-us/entra/identity-platform/v2-protocols#endpoints", + "auth_url": "https://login.microsoftonline.com/{instance}/oauth2/v2.0/authorize", + "token_url": "https://login.microsoftonline.com/{instance}/oauth2/v2.0/token", + "req_body_auth": true, + "scopes": ["offline_access", "User.Read", "Mail.ReadWrite", "Mail.Send", "Calendars.ReadWrite", "Contacts.ReadWrite"] + } + }, + "hubspot": { + "auth_url": "https://app.hubspot.com/oauth/authorize", + "token_url": "https://api.hubapi.com/oauth/v1/token", + "scopes": [ + "oauth", + "crm.objects.contacts.read", + "crm.objects.contacts.write", + "crm.objects.companies.read", + "crm.objects.companies.write", + "crm.objects.deals.read", + "crm.objects.deals.write", + "crm.objects.owners.read" + ], + "scope_options": [ + { "value": "oauth", "label": "Basic OAuth access (always required by HubSpot)" }, + { "value": "crm.objects.contacts.read", "label": "Read contacts, and notes, tasks, meetings and calls" }, + { "value": "crm.objects.contacts.write", "label": "Create and edit contacts, and notes, tasks, meetings and calls" }, + { "value": "crm.objects.companies.read", "label": "Read companies" }, + { "value": "crm.objects.companies.write", "label": "Create and edit companies" }, + { "value": "crm.objects.deals.read", "label": "Read deals and deal pipelines" }, + { "value": "crm.objects.deals.write", "label": "Create and edit deals" }, + { "value": "crm.objects.owners.read", "label": "Read owners (users assignable to records)" }, + { "value": "tickets", "label": "Read and edit tickets and ticket pipelines" }, + { "value": "crm.objects.line_items.read", "label": "Read line items" }, + { "value": "crm.objects.line_items.write", "label": "Create and edit line items" }, + { "value": "e-commerce", "label": "Read and edit products and line items" }, + { "value": "crm.objects.quotes.read", "label": "Read quotes" }, + { "value": "crm.objects.quotes.write", "label": "Create and edit quotes" }, + { "value": "crm.objects.leads.read", "label": "Read leads" }, + { "value": "crm.objects.leads.write", "label": "Create and edit leads" }, + { "value": "crm.objects.custom.read", "label": "Read custom object records" }, + { "value": "crm.objects.custom.write", "label": "Create and edit custom object records" }, + { "value": "crm.schemas.custom.read", "label": "Read custom object schemas" }, + { "value": "crm.lists.read", "label": "Read lists (segments)" }, + { "value": "crm.lists.write", "label": "Edit lists and their members" }, + { "value": "sales-email-read", "label": "Read the content of logged one-to-one emails" }, + { "value": "forms", "label": "Read and edit forms and their submissions" }, + { "value": "files", "label": "Read and upload files in the file manager" }, + { "value": "content", "label": "Read and edit marketing emails, blog posts, pages and templates" }, + { "value": "crm.objects.marketing_events.read", "label": "Read marketing events" }, + { "value": "marketing.campaigns.read", "label": "Read marketing campaigns (Marketing Hub Professional)" }, + { "value": "communication_preferences.read_write", "label": "Read and change email subscription preferences" }, + { "value": "automation", "label": "Read, create and enroll into workflows (Professional)" }, + { "value": "automation.sequences.read", "label": "Read sequences and sequence enrollments (Sales Hub Professional)" }, + { "value": "automation.sequences.enrollments.write", "label": "Enroll contacts in sequences (Sales Hub Professional)" }, + { "value": "conversations.read", "label": "Read inboxes, threads and messages" }, + { "value": "conversations.write", "label": "Send messages and update threads" }, + { "value": "scheduler.meetings.meeting-link.read", "label": "Read meeting links and their availability" } + ], + "extra_params": { + "optional_scope": "tickets crm.objects.line_items.read crm.objects.line_items.write e-commerce crm.objects.quotes.read crm.objects.quotes.write crm.objects.leads.read crm.objects.leads.write crm.objects.custom.read crm.objects.custom.write crm.schemas.custom.read crm.lists.read crm.lists.write sales-email-read forms files content crm.objects.marketing_events.read marketing.campaigns.read communication_preferences.read_write automation automation.sequences.read automation.sequences.enrollments.write conversations.read conversations.write scheduler.meetings.meeting-link.read" + }, + "req_body_auth": true + }, + "zendesk": { + "grant_types": ["authorization_code", "client_credentials"], + "scopes": ["read", "write"], + "cc_scopes": ["read", "write"], + "scope_options": [ + { "value": "read", "label": "Read tickets, users, organizations and Help Center content" }, + { "value": "write", "label": "Create, update and delete tickets, users, organizations and Help Center content" } + ], + "req_body_auth": true, + "connect_config_template": { + "display_name": "Zendesk", + "label": "Zendesk subdomain", + "placeholder": "yourcompany (from yourcompany.zendesk.com)", + "help_url": "https://developer.zendesk.com/documentation/api-basics/authentication/oauth-migration/", + "auth_url": "https://{instance}.zendesk.com/oauth/authorizations/new", + "token_url": "https://{instance}.zendesk.com/oauth/tokens", + "scopes": ["read", "write"], + "req_body_auth": true, + "strip_suffix": ".zendesk.com", + "resource_mapping": { + "subdomain": "{instance}" + } + } } } diff --git a/backend/parsers/windmill-parser-bash/Cargo.toml b/backend/parsers/windmill-parser-bash/Cargo.toml index 4c7db23313..62f0c3fac3 100644 --- a/backend/parsers/windmill-parser-bash/Cargo.toml +++ b/backend/parsers/windmill-parser-bash/Cargo.toml @@ -7,6 +7,8 @@ authors.workspace = true [lib] name = "windmill_parser_bash" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [target.'cfg(target_arch = "wasm32")'.dependencies] regex-lite.workspace = true diff --git a/backend/parsers/windmill-parser-csharp/Cargo.toml b/backend/parsers/windmill-parser-csharp/Cargo.toml index 07b0259224..3a283d5895 100644 --- a/backend/parsers/windmill-parser-csharp/Cargo.toml +++ b/backend/parsers/windmill-parser-csharp/Cargo.toml @@ -7,6 +7,8 @@ authors.workspace = true [lib] name = "windmill_parser_csharp" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [dependencies] windmill-parser.workspace = true diff --git a/backend/parsers/windmill-parser-go/Cargo.toml b/backend/parsers/windmill-parser-go/Cargo.toml index ecba62cff4..4e8805aad7 100644 --- a/backend/parsers/windmill-parser-go/Cargo.toml +++ b/backend/parsers/windmill-parser-go/Cargo.toml @@ -7,6 +7,8 @@ authors.workspace = true [lib] name = "windmill_parser_go" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [dependencies] windmill-parser.workspace = true diff --git a/backend/parsers/windmill-parser-graphql/Cargo.toml b/backend/parsers/windmill-parser-graphql/Cargo.toml index 7f0a93b6f3..557fb56402 100644 --- a/backend/parsers/windmill-parser-graphql/Cargo.toml +++ b/backend/parsers/windmill-parser-graphql/Cargo.toml @@ -7,6 +7,8 @@ authors.workspace = true [lib] name = "windmill_parser_graphql" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [target.'cfg(target_arch = "wasm32")'.dependencies] regex-lite.workspace = true diff --git a/backend/parsers/windmill-parser-java/Cargo.toml b/backend/parsers/windmill-parser-java/Cargo.toml index 19809e3120..5a575b891b 100644 --- a/backend/parsers/windmill-parser-java/Cargo.toml +++ b/backend/parsers/windmill-parser-java/Cargo.toml @@ -7,6 +7,8 @@ authors.workspace = true [lib] name = "windmill_parser_java" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [dependencies] windmill-parser.workspace = true diff --git a/backend/parsers/windmill-parser-nu/Cargo.toml b/backend/parsers/windmill-parser-nu/Cargo.toml index c8c3e0d616..78034a3a79 100644 --- a/backend/parsers/windmill-parser-nu/Cargo.toml +++ b/backend/parsers/windmill-parser-nu/Cargo.toml @@ -7,6 +7,9 @@ edition.workspace = true [lib] name = "windmill_parser_nu" path = "./src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [dependencies] windmill-parser.workspace = true diff --git a/backend/parsers/windmill-parser-php/Cargo.toml b/backend/parsers/windmill-parser-php/Cargo.toml index 8bd3182f91..37fcb70957 100644 --- a/backend/parsers/windmill-parser-php/Cargo.toml +++ b/backend/parsers/windmill-parser-php/Cargo.toml @@ -7,6 +7,8 @@ authors.workspace = true [lib] name = "windmill_parser_php" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [dependencies] windmill-parser.workspace = true diff --git a/backend/parsers/windmill-parser-py-asset/Cargo.toml b/backend/parsers/windmill-parser-py-asset/Cargo.toml index ddd6446079..46d5c55a42 100644 --- a/backend/parsers/windmill-parser-py-asset/Cargo.toml +++ b/backend/parsers/windmill-parser-py-asset/Cargo.toml @@ -7,10 +7,12 @@ authors.workspace = true [lib] name = "windmill_parser_py_asset" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [dependencies] windmill-parser.workspace = true windmill-parser-sql-asset.workspace = true -rustpython-parser.workspace = true -rustpython-ast = { version = "0.4.0", features = ["visitor"] } +ruff_python_parser.workspace = true +ruff_python_ast.workspace = true anyhow.workspace = true diff --git a/backend/parsers/windmill-parser-py-asset/src/lib.rs b/backend/parsers/windmill-parser-py-asset/src/lib.rs index 9c70b93d64..2919b74607 100644 --- a/backend/parsers/windmill-parser-py-asset/src/lib.rs +++ b/backend/parsers/windmill-parser-py-asset/src/lib.rs @@ -1,5 +1,8 @@ -use rustpython_ast::{Constant, Expr, ExprConstant, Visitor}; -use rustpython_parser::{ast::Suite, Parse}; +use ruff_python_ast::{ + visitor::{walk_expr, walk_stmt, Visitor}, + Expr, ExprCall, ExprDict, FStringPartRef, InterpolatedStringElement, Keyword, Stmt, StmtAssign, +}; +use ruff_python_parser::parse_module; use std::collections::HashMap; use windmill_parser::asset_parser::{ asset_was_used, merge_assets, parse_asset_syntax, parse_pipeline_annotations, AssetKind, @@ -8,12 +11,12 @@ use windmill_parser::asset_parser::{ use AssetUsageAccessType::*; pub fn parse_assets(input: &str) -> anyhow::Result { - let ast = Suite::parse(input, "main.py") - .map_err(|e| anyhow::anyhow!("Error parsing code: {}", e.to_string()))?; + let ast = parse_module(input) + .map_err(|e| anyhow::anyhow!("Error parsing code: {}", e.to_string()))? + .into_suite(); let mut assets_finder = AssetsFinder { assets: vec![], var_identifiers: HashMap::new() }; - ast.into_iter() - .for_each(|stmt| assets_finder.visit_stmt(stmt)); + assets_finder.visit_body(&ast); for (kind, path, _) in assets_finder.var_identifiers.into_values() { // if a db = wmill.datatable() was never used (e.g db.query(...)), @@ -43,13 +46,72 @@ struct AssetsFinder { var_identifiers: HashMap, } -impl Visitor for AssetsFinder { +impl<'a> Visitor<'a> for AssetsFinder { + fn visit_stmt(&mut self, stmt: &'a Stmt) { + if let Stmt::Assign(node) = stmt { + self.track_assignment(node); + } + // Continue with generic visit to catch any other assets in the statement + walk_stmt(self, stmt); + } + + fn visit_expr(&mut self, expr: &'a Expr) { + match expr { + // A detected asset call does not recurse, + // so this is only reached when no further context was found + Expr::StringLiteral(s) => self.visit_str(s.value.to_str()), + Expr::FString(f) => { + // Literal text between two interpolations reads as one string, across the + // pieces of an implicitly concatenated f-string too. + let mut literal = String::new(); + for part in &f.value { + match part { + FStringPartRef::Literal(s) => literal.push_str(&s.value), + FStringPartRef::FString(f) => { + for element in &f.elements { + match element { + InterpolatedStringElement::Literal(l) => { + literal.push_str(&l.value) + } + InterpolatedStringElement::Interpolation(_) => { + self.visit_str(&std::mem::take(&mut literal)) + } + } + } + } + } + } + self.visit_str(&literal); + walk_expr(self, expr); + } + Expr::Call(node) => { + if self.visit_expr_call_inner(node).is_err() { + walk_expr(self, expr); + } + } + _ => walk_expr(self, expr), + } + } +} + +impl AssetsFinder { + fn visit_str(&mut self, s: &str) { + if let Some((kind, path)) = parse_asset_syntax(s, false) { + self.assets.push(ParseAssetsResult { + kind, + path: path.to_string(), + access_type: None, + columns: None, + }); + } + } + // Handle assignment statements like: x = wmill.datatable('name') - fn visit_stmt_assign(&mut self, node: rustpython_ast::StmtAssign) { + fn track_assignment(&mut self, node: &StmtAssign) { // Check if the value is a call to a tracked function if let Some(Expr::Name(expr_name)) = node.targets.first() { // Remove any tracked variables with that name in case of reassignment - let Ok(var_name) = expr_name.id.parse::(); + let var_name = expr_name.id.to_string(); let removed = self.var_identifiers.remove(&var_name); // if a db = wmill.datatable() or similar was removed, but never used (e.g db.query(...)), // we still want to register the asset as unknown access type @@ -69,59 +131,12 @@ impl Visitor for AssetsFinder { if let Some((kind, name, schema)) = self.extract_asset_from_call(&node.value) { // Track target variable - let Ok(var_name) = expr_name.id.parse::(); self.var_identifiers .insert(var_name, (kind.clone(), name.clone(), schema.clone())); } } - // Continue with generic visit to catch any other assets in the expression - self.generic_visit_stmt_assign(node); } - // visit_call_expr will not recurse if it detects an asset, - // so this will only be called when no further context was found - fn visit_expr_constant(&mut self, node: ExprConstant) { - match node.value { - Constant::Str(s) => { - if let Some((kind, path)) = parse_asset_syntax(&s, false) { - self.assets.push(ParseAssetsResult { - kind, - path: path.to_string(), - access_type: None, - columns: None, - }); - } - } - _ => self.generic_visit_expr_constant(node), - } - } - - fn visit_expr_call(&mut self, node: rustpython_ast::ExprCall) { - match self.visit_expr_call_inner(&node) { - Ok(_) => {} - Err(_) => { - // Check keyword arguments for assets before falling back to generic visit - for keyword in &node.keywords { - if let Expr::Constant(ExprConstant { value: Constant::Str(s), .. }) = - &keyword.value - { - if let Some((kind, path)) = parse_asset_syntax(s, false) { - self.assets.push(ParseAssetsResult { - kind, - path: path.to_string(), - access_type: None, - columns: None, - }); - } - } - } - self.generic_visit_expr_call(node); - } - } - } -} - -impl AssetsFinder { /// Extract asset info from calls like wmill.datatable('name'), wmill.ducklake('name'), etc. fn extract_asset_from_call( &self, @@ -147,18 +162,20 @@ impl AssetsFinder { // Get the first argument (the asset name) let name = call + .arguments .args .first() .or_else(|| { // Try keyword argument 'name' or 'path' - call.keywords + call.arguments + .keywords .iter() .find(|kw| matches!(kw.arg.as_deref(), Some("name") | Some("path"))) .map(|kw| &kw.value) }) .and_then(|first_arg| { - if let Expr::Constant(ExprConstant { value: Constant::Str(name), .. }) = first_arg { - Some(name.clone()) + if let Expr::StringLiteral(name) = first_arg { + Some(name.value.to_str().to_string()) } else { None } @@ -179,44 +196,39 @@ impl AssetsFinder { Some((kind, name, schema)) } - fn visit_expr_call_inner(&mut self, node: &rustpython_ast::ExprCall) -> Result<(), ()> { + fn visit_expr_call_inner(&mut self, node: &ExprCall) -> Result<(), ()> { let ident: String = node .func .as_name_expr() - .and_then(|o| o.id.parse().ok()) + .map(|o| o.id.to_string()) .or_else(|| { node.func .as_attribute_expr() - .and_then(|attr| attr.attr.parse().ok()) + .map(|attr| attr.attr.to_string()) }) .ok_or(())?; // `obj_name` is the object (receiver) - i.e., `obj` in `obj.method()` - let obj_name: String = if let Expr::Attribute(rustpython_ast::ExprAttribute { - value, .. - }) = node.func.as_ref() - { - if let Expr::Name(expr_name) = value.as_ref() { - expr_name.id.parse().map_err(|_| ())? - } else { - return Err(()); - } - } else { - return Err(()); - }; + let obj_name: String = node + .func + .as_attribute_expr() + .and_then(|attr| attr.value.as_name_expr()) + .map(|name| name.id.to_string()) + .ok_or(())?; if obj_name == "wmill" { // Continue } else if let Some((kind, ref path, ref schema)) = self.var_identifiers.get(&obj_name) { if ident == "query" { - let expr_name = node.args.get(0).or_else(|| { - node.keywords + let expr_name = node.arguments.args.get(0).or_else(|| { + node.arguments + .keywords .iter() .find(|kw| kw.arg.as_deref() == Some("name")) .map(|kw| &kw.value) }); let sql = match expr_name { - Some(Expr::Constant(ExprConstant { value: Constant::Str(sql), .. })) => sql, + Some(Expr::StringLiteral(sql)) => sql.value.to_str(), _ => return Err(()), }; // We use the SQL parser to detect RW, specific tables, etc. @@ -224,7 +236,7 @@ impl AssetsFinder { *kind, path, schema.as_deref(), - &sql, + sql, ); match sql_assets { Ok(Some(sql_assets)) => self.assets.extend(sql_assets), @@ -252,9 +264,10 @@ impl AssetsFinder { }; let arg_val = match arg { - Arg(i, name) => node.args.get(i).or_else(|| { + Arg(i, name) => node.arguments.args.get(i).or_else(|| { // Get arg by name - node.keywords + node.arguments + .keywords .iter() .find(|kw| kw.arg.as_deref() == Some(name)) .map(|kw| &kw.value) @@ -270,8 +283,9 @@ impl AssetsFinder { self.assets .push(ParseAssetsResult { kind, path, access_type, columns: None }); } - Some(Expr::Constant(ExprConstant { value: Constant::Str(value), .. })) => { - let path = parse_asset_syntax(&value, false) + Some(Expr::StringLiteral(value)) => { + let value = value.value.to_str(); + let path = parse_asset_syntax(value, false) .map(|(_, p)| p) .unwrap_or(std::borrow::Cow::Borrowed(value)); self.assets.push(ParseAssetsResult { @@ -291,26 +305,24 @@ impl AssetsFinder { struct Arg(usize, &'static str); /// Extract a string-literal keyword argument, e.g. `s3="value"` in a call. -fn keyword_str_value(keywords: &[rustpython_ast::Keyword], name: &str) -> Option { +fn keyword_str_value(keywords: &[Keyword], name: &str) -> Option { keywords .iter() .find(|kw| kw.arg.as_deref() == Some(name)) .and_then(|kw| match &kw.value { - Expr::Constant(ExprConstant { value: Constant::Str(s), .. }) => Some(s.clone()), + Expr::StringLiteral(s) => Some(s.value.to_str().to_string()), _ => None, }) } /// Extract a string-literal value from a dict literal, e.g. `{"s3": "value"}`. -fn dict_str_value(dict: &rustpython_ast::ExprDict, name: &str) -> Option { - dict.keys +fn dict_str_value(dict: &ExprDict, name: &str) -> Option { + dict.items .iter() - .zip(dict.values.iter()) - .find_map(|(key, value)| match (key.as_ref()?, value) { - ( - Expr::Constant(ExprConstant { value: Constant::Str(k), .. }), - Expr::Constant(ExprConstant { value: Constant::Str(v), .. }), - ) if k.as_str() == name => Some(v.clone()), + .find_map(|item| match (item.key.as_ref()?, &item.value) { + (Expr::StringLiteral(k), Expr::StringLiteral(v)) if k.value.to_str() == name => { + Some(v.value.to_str().to_string()) + } _ => None, }) } @@ -328,12 +340,13 @@ fn dict_str_value(dict: &rustpython_ast::ExprDict, name: &str) -> Option /// matches the TS object form and the `# on s3:///…` trigger form exactly. fn s3_object_arg_path(expr: &Expr) -> Option { let uri = match expr { - Expr::Constant(ExprConstant { value: Constant::Str(s), .. }) => { + Expr::StringLiteral(s) => { + let s = s.value.to_str(); match s .strip_prefix("s3://") .and_then(|rest| rest.split_once('/')) { - Some((_, key)) if !key.is_empty() => s.clone(), + Some((_, key)) if !key.is_empty() => s.to_string(), _ => return None, } } @@ -347,8 +360,9 @@ fn s3_object_arg_path(expr: &Expr) -> Option { if func_name != "S3Object" { return None; } - let key = keyword_str_value(&call.keywords, "s3")?; - let storage = keyword_str_value(&call.keywords, "storage").unwrap_or_default(); + let key = keyword_str_value(&call.arguments.keywords, "s3")?; + let storage = + keyword_str_value(&call.arguments.keywords, "storage").unwrap_or_default(); format!("s3://{storage}/{key}") } Expr::Dict(dict) => { @@ -822,4 +836,62 @@ def main(): },]) ); } + + #[test] + fn test_py_asset_parser_recent_syntax() { + let input = r#" +import wmill +lazy import polars + +type Rows = list[dict] + +def main[T](name: str): + try: + with wmill.load_s3_file_reader('s3:///in.csv') as f: + f.read() + except ValueError, TypeError: + pass + greeting = t"hello {name}" + return f"{wmill.get_resource("u/user/pg")["host"]}" +"#; + let s = parse_assets(input).map(|o| o.assets); + assert_eq!( + s.map_err(|e| e.to_string()), + Ok(vec![ + ParseAssetsResult { + kind: AssetKind::S3Object, + path: "/in.csv".to_string(), + access_type: Some(R), + columns: None, + }, + ParseAssetsResult { + kind: AssetKind::Resource, + path: "u/user/pg".to_string(), + access_type: None, + columns: None, + }, + ]) + ); + } + + #[test] + fn test_py_asset_parser_schema_qualified_db_without_table() { + let input = r#" +import wmill +def main(): + db = wmill.datatable('dt:sch') + db.query("ATTACH 'ducklake://other' AS o") + db.query("SELECT * FROM t") +"#; + let s = parse_assets(input).map(|o| o.assets); + assert_eq!( + s.map_err(|e| e.to_string()) + .map(|a| a.into_iter().map(|a| (a.kind, a.path)).collect::>()), + Ok(vec![ + (AssetKind::DataTable, "dt".to_string()), + (AssetKind::DataTable, "dt/sch.t".to_string()), + (AssetKind::Ducklake, "other".to_string()), + ]) + ); + } } diff --git a/backend/parsers/windmill-parser-py-imports/Cargo.toml b/backend/parsers/windmill-parser-py-imports/Cargo.toml index 565e1422bb..be0c1062b7 100644 --- a/backend/parsers/windmill-parser-py-imports/Cargo.toml +++ b/backend/parsers/windmill-parser-py-imports/Cargo.toml @@ -7,6 +7,9 @@ authors.workspace = true [lib] name = "windmill_parser_py_imports" path = "./src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [target.'cfg(target_arch = "wasm32")'.dependencies] regex-lite.workspace = true @@ -23,7 +26,8 @@ tracing.workspace = true [dependencies] windmill-parser.workspace = true -rustpython-parser.workspace = true +ruff_python_parser.workspace = true +ruff_python_ast.workspace = true phf.workspace = true itertools.workspace = true serde_json.workspace = true diff --git a/backend/parsers/windmill-parser-py-imports/src/lib.rs b/backend/parsers/windmill-parser-py-imports/src/lib.rs index de7f51bc79..f1718c6d94 100644 --- a/backend/parsers/windmill-parser-py-imports/src/lib.rs +++ b/backend/parsers/windmill-parser-py-imports/src/lib.rs @@ -13,9 +13,9 @@ use async_recursion::async_recursion; use itertools::Itertools; use lazy_static::lazy_static; #[cfg(not(target_arch = "wasm32"))] -use std::str::FromStr; -#[cfg(not(target_arch = "wasm32"))] use std::collections::HashMap; +#[cfg(not(target_arch = "wasm32"))] +use std::str::FromStr; use mapping::{FULL_IMPORTS_MAP, SHORT_IMPORTS_MAP}; #[cfg(not(target_arch = "wasm32"))] @@ -23,11 +23,8 @@ use regex::Regex; #[cfg(target_arch = "wasm32")] use regex_lite::Regex; -use rustpython_parser::{ - ast::{Stmt, StmtImport, StmtImportFrom, Suite}, - text_size::TextRange, - Parse, -}; +use ruff_python_ast::{Stmt, StmtImport, StmtImportFrom}; +use ruff_python_parser::parse_module; #[cfg(not(target_arch = "wasm32"))] use sqlx::{Pool, Postgres}; #[cfg(not(target_arch = "wasm32"))] @@ -160,6 +157,7 @@ pub struct ImportPin { } pub fn parse_code_for_imports(code: &str, path: &str) -> anyhow::Result> { + let full_code = code; // Use regex to safely find the main function definition let mut code = DEF_MAIN_RE .split(code) @@ -186,16 +184,22 @@ pub fn parse_code_for_imports(code: &str, path: &str) -> anyhow::Result (code, parsed.into_suite()), + // The split lands on any line reading like the definition of `main`, one inside a + // string included: what precedes it is then not a module, while the whole file is. + Err(e) => match parse_module(full_code) { + Ok(parsed) => (full_code.to_string(), parsed.into_suite()), + Err(_) => anyhow::bail!("Error parsing code for imports: {}", e.to_string()), + }, + }; // Note: We're still using the original code for finding pins, // as the TextRange values from the parsed AST would be based on code_with_fake_main // but we want to match against the original code - let find_pin = |range: TextRange, key: String| { + let find_pin = |stmt_end: usize, key: String| { let hs = code .chars() - .skip(range.end().to_usize()) + .skip(stmt_end) .take_while(|e| *e != '\n') .collect::(); @@ -226,9 +230,9 @@ pub fn parse_code_for_imports(code: &str, path: &str) -> anyhow::Result = ast .into_iter() .filter_map(|x| match x { - Stmt::Import(StmtImport { names, range }) => names + Stmt::Import(StmtImport { names, range, .. }) => names .get(0) - .and_then(|al| find_pin(range, al.name.to_string())) + .and_then(|al| find_pin(range.end().to_usize(), al.name.to_string())) .or(Some( names .into_iter() @@ -239,15 +243,11 @@ pub fn parse_code_for_imports(code: &str, path: &str) -> anyhow::Result>(), )), - Stmt::ImportFrom(StmtImportFrom { level: Some(i), module, .. }) if i.to_u32() > 0 => { - Some(process_import( - module.map(|x| x.to_string()), - path, - i.to_usize(), - )) - } + Stmt::ImportFrom(StmtImportFrom { level, module, .. }) if level > 0 => Some( + process_import(module.map(|x| x.to_string()), path, level as usize), + ), Stmt::ImportFrom(StmtImportFrom { level: _, module, range, .. }) => find_pin( - range, + range.end().to_usize(), module.clone().map(|x| x.to_string()).unwrap_or_default(), ) .or(Some(process_import(module.map(|x| x.to_string()), path, 0))), @@ -268,6 +268,33 @@ pub fn parse_code_for_imports(code: &str, path: &str) -> anyhow::Result>, +) -> Option> { + let dir = script_path + .rsplit_once('/') + .map(|(dir, _)| dir) + .unwrap_or(""); + let sources: HashMap = modules? + .iter() + .filter_map(|(key, module)| { + let stem = key.strip_suffix(".py")?; + let path = if dir.is_empty() { + stem.to_string() + } else { + format!("{dir}/{stem}") + }; + Some((path, module.content.clone())) + }) + .collect(); + (!sources.is_empty()).then_some(sources) +} + #[cfg(not(target_arch = "wasm32"))] pub async fn parse_python_imports( code: &str, @@ -278,6 +305,10 @@ pub async fn parse_python_imports( locked_v: &mut Option, raw_workspace_dependencies_o: &Option, temp_script_refs: &Option>, + // Content of relative imports that ship with the importer rather than being deployed + // (its modules), keyed by the path a relative import resolves to. Wins over both + // `temp_script_refs` and the deployed script, as the module file does at run time. + module_sources: Option<&HashMap>, ) -> error::Result<(Vec, Option)> { let mut compile_error_hint: Option = None; let mut imports = parse_python_imports_inner( @@ -291,6 +322,7 @@ pub async fn parse_python_imports( locked_v, raw_workspace_dependencies_o, temp_script_refs, + module_sources, ) .await? .into_values() @@ -349,15 +381,19 @@ async fn parse_python_imports_inner( locked_v: &mut Option, raw_workspace_dependencies_o: &Option, temp_script_refs: &Option>, + module_sources: Option<&HashMap>, ) -> error::Result> { tracing::debug!("Parsing python imports for path: {}", path); - let PythonAnnotations { py310, py311, py312, py313, .. } = PythonAnnotations::parse(&code); + let PythonAnnotations { py310, py311, py312, py313, py314, py315, .. } = + PythonAnnotations::parse(&code); tracing::debug!( - "Found python annotations - py310: {}, py311: {}, py312: {}, py313: {}", + "Found python annotations - py310: {}, py311: {}, py312: {}, py313: {}, py314: {}, py315: {}", py310, py311, py312, - py313 + py313, + py314, + py315 ); let mut push_version_specifiers = |perform, unparsed: String| -> error::Result<()> { @@ -373,6 +409,8 @@ async fn parse_python_imports_inner( push_version_specifiers(py311, "==3.11.*".to_owned())?; push_version_specifiers(py312, "==3.12.*".to_owned())?; push_version_specifiers(py313, "==3.13.*".to_owned())?; + push_version_specifiers(py314, "==3.14.*".to_owned())?; + push_version_specifiers(py315, "==3.15.*".to_owned())?; for x in code.lines() { if x.starts_with("# py:") || x.starts_with("#py:") { @@ -512,9 +550,16 @@ async fn parse_python_imports_inner( for n in nimports.into_iter() { let mut nested = match n { NImport::Relative(rpath) => { - // First try to get content from temp_script_refs cache if available - let code_from_cache = if let Some(hash) = temp_script_refs.as_ref().and_then(|dt| dt.get(&rpath)) { - tracing::debug!("Found relative import '{}' in temp_script_refs with hash '{}'", rpath, hash); + let code_from_cache = if let Some(content) = + module_sources.and_then(|m| m.get(&rpath)) + { + Some(content.clone()) + } else if let Some(hash) = temp_script_refs.as_ref().and_then(|dt| dt.get(&rpath)) { + tracing::debug!( + "Found relative import '{}' in temp_script_refs with hash '{}'", + rpath, + hash + ); match windmill_common::cache::raw_script_temp::load(hash.clone(), db).await { Ok(content) => Some(content), Err(e) => { @@ -529,19 +574,17 @@ async fn parse_python_imports_inner( // Use cached content if available, otherwise fall back to deployed script let code = match code_from_cache { Some(content) => content, - None => { - sqlx::query_scalar!( - r#" + None => sqlx::query_scalar!( + r#" SELECT content FROM script WHERE path = $1 AND workspace_id = $2 AND archived = false ORDER BY created_at DESC LIMIT 1 "#, - &rpath, - w_id - ) - .fetch_optional(db) - .await? - .unwrap_or_else(|| "".to_string()) - } + &rpath, + w_id + ) + .fetch_optional(db) + .await? + .unwrap_or_else(|| "".to_string()), }; if already_visited.contains(&rpath) { @@ -561,6 +604,7 @@ async fn parse_python_imports_inner( locked_v, raw_workspace_dependencies_o, temp_script_refs, + module_sources, ) .await? .into_values() diff --git a/backend/parsers/windmill-parser-py-imports/src/mapping.rs b/backend/parsers/windmill-parser-py-imports/src/mapping.rs index 6246a1f156..90f3fab99c 100644 --- a/backend/parsers/windmill-parser-py-imports/src/mapping.rs +++ b/backend/parsers/windmill-parser-py-imports/src/mapping.rs @@ -383,5 +383,10 @@ pub static SHORT_IMPORTS_MAP: PyMap = phf_map! { "vt" => "vt-py", "grpc" => "grpcio", "serpapi" => "google-search-results", + "pptx" => "python-pptx", + "OpenSSL" => "pyOpenSSL", + "win32api" => "pywin32", + "ruamel" => "ruamel.yaml", + "speech-recognition" => "SpeechRecognition", // Add new entry here ^ }; diff --git a/backend/parsers/windmill-parser-py-imports/tests/tests.rs b/backend/parsers/windmill-parser-py-imports/tests/tests.rs index c853c8e5b4..6d3d75a239 100644 --- a/backend/parsers/windmill-parser-py-imports/tests/tests.rs +++ b/backend/parsers/windmill-parser-py-imports/tests/tests.rs @@ -1,7 +1,9 @@ mod tests { use sqlx::{Pool, Postgres}; - use windmill_parser_py_imports::parse_python_imports; + use windmill_parser_py_imports::{ + parse_code_for_imports, parse_python_imports, ImportPin, NImport, + }; #[sqlx::test(fixtures("base"))] async fn test_parse_python_imports(db: Pool) -> anyhow::Result<()> { @@ -27,6 +29,7 @@ def main(): &mut None, &None, &None, + None, ) .await?; // println!("{}", serde_json::to_string(&r)?); @@ -69,6 +72,7 @@ def main(): &mut None, &None, &None, + None, ) .await?; println!("{}", serde_json::to_string(&r)?); @@ -101,6 +105,7 @@ def main(): &mut None, &None, &None, + None, ) .await?; println!("{}", serde_json::to_string(&r)?); @@ -117,4 +122,87 @@ def main(): Ok(()) } + + fn auto(pkg: &str) -> NImport { + NImport::Auto { pkg: pkg.to_string(), key: None } + } + + #[test] + fn test_parse_lazy_imports() -> anyhow::Result<()> { + let code = " +lazy import requests +lazy import numpy # pin: numpy==2.1.0 +lazy from pandas import DataFrame +lazy from f.shared import helper +lazy = 1 + +def main(): + pass +"; + assert_eq!( + parse_code_for_imports(code, "f/foo/bar")?, + vec![ + NImport::Pin { + pins: vec![ImportPin { + pkg: "numpy==2.1.0".to_string(), + path: "f/foo/bar".to_string() + }], + key: "numpy".to_string() + }, + auto("pandas"), + auto("requests"), + NImport::Relative("f/shared".to_string()), + ] + ); + Ok(()) + } + + #[test] + fn test_parse_imports_recent_syntax_before_main() -> anyhow::Result<()> { + let code = r#" +import requests + +type Alias = list[int] +NAME = "x" +D = {"a": 1} +L = [[1], [2]] +TEMPLATE = t"hello {NAME}" +PEP701 = f"{D["a"]} {'\n'.join(["x"])}" +PEP798 = [*a for a in L] + +try: + import ujson +except ImportError, ValueError: + pass + +def main(): + pass +"#; + assert_eq!( + parse_code_for_imports(code, "f/foo/bar")?, + vec![auto("requests")] + ); + Ok(()) + } + + #[test] + fn test_parse_imports_main_lookalike_in_docstring() -> anyhow::Result<()> { + for example in ["def main[T](x: T):", "def main(x):"] { + let code = format!( + "\"\"\"Usage example:\n{example}\n return x\n\"\"\"\nimport requests # pin: requests==2.32.0\n\ndef main(value: str):\n return value\n" + ); + assert_eq!( + parse_code_for_imports(&code, "f/foo/bar")?, + vec![NImport::Pin { + pins: vec![ImportPin { + pkg: "requests==2.32.0".to_string(), + path: "f/foo/bar".to_string() + }], + key: "requests".to_string() + }], + "{code}" + ); + } + Ok(()) + } } diff --git a/backend/parsers/windmill-parser-py/Cargo.toml b/backend/parsers/windmill-parser-py/Cargo.toml index 0c50e0f8d8..1f34643572 100644 --- a/backend/parsers/windmill-parser-py/Cargo.toml +++ b/backend/parsers/windmill-parser-py/Cargo.toml @@ -7,11 +7,13 @@ authors.workspace = true [lib] name = "windmill_parser_py" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [dependencies] windmill-parser.workspace = true -rustpython-parser.workspace = true +ruff_python_parser.workspace = true +ruff_python_ast.workspace = true itertools.workspace = true serde_json.workspace = true anyhow.workspace = true -rustpython-ast = { version = "0.4.0", features = ["visitor"] } diff --git a/backend/parsers/windmill-parser-py/src/lib.rs b/backend/parsers/windmill-parser-py/src/lib.rs index 086a354d02..5a9eabc33e 100644 --- a/backend/parsers/windmill-parser-py/src/lib.rs +++ b/backend/parsers/windmill-parser-py/src/lib.rs @@ -13,13 +13,11 @@ use itertools::Itertools; use serde_json::json; use windmill_parser::{json_to_typ, Arg, MainArgSignature, ObjectType, Typ}; -use rustpython_parser::{ - ast::{ - Constant, Expr, ExprAttribute, ExprConstant, ExprDict, ExprList, ExprName, Stmt, - StmtAssign, StmtAsyncFunctionDef, StmtClassDef, StmtFunctionDef, Suite, - }, - Parse, +use ruff_python_ast::{ + Expr, ExprAttribute, ExprDict, ExprList, ExprName, Number, Parameters, Stmt, StmtAssign, + StmtClassDef, StmtFunctionDef, }; +use ruff_python_parser::parse_module; pub mod pydantic_parser; @@ -81,22 +79,24 @@ fn should_parse_for_models(code: &str) -> bool { || code.contains("import dataclasses") } +/// What follows `def ` or `async def ` on a line opening that function's +/// parameters or type parameters. +fn strip_def<'a>(line: &'a str, name: &str) -> Option<&'a str> { + let rest = line + .strip_prefix("async def ") + .or_else(|| line.strip_prefix("def "))? + .strip_prefix(name)?; + (rest.starts_with('(') || rest.starts_with('[')).then_some(rest) +} + fn filter_non_main(code: &str, main_name: &str) -> String { - let def_main = format!("def {}(", main_name); - let async_def_main = format!("async def {}(", main_name); let mut filtered_code = String::new(); let mut code_iter = code.split("\n"); let mut remaining: String = String::new(); while let Some(line) = code_iter.next() { - if line.starts_with(&async_def_main) { - filtered_code += &async_def_main; - remaining += line.strip_prefix(&async_def_main).unwrap(); - remaining += "\n"; - remaining += &code_iter.join("\n"); - break; - } else if line.starts_with(&def_main) { - filtered_code += &def_main; - remaining += line.strip_prefix(&def_main).unwrap(); + if let Some(rest) = strip_def(line, main_name) { + filtered_code += &line[..line.len() - rest.len()]; + remaining += rest; remaining += "\n"; remaining += &code_iter.join("\n"); break; @@ -106,6 +106,26 @@ fn filter_non_main(code: &str, main_name: &str) -> String { return String::new(); } let mut chars = remaining.chars(); + + // PEP 695 type parameters, `def main[T](x: T)`, sit between the name and the parameters. + if remaining.starts_with('[') { + let mut open_brackets = 0; + for c in chars.by_ref() { + if c == '[' { + open_brackets += 1; + } else if c == ']' { + open_brackets -= 1; + } + filtered_code.push(c); + if open_brackets == 0 { + break; + } + } + } + if chars.next() != Some('(') { + return String::new(); + } + filtered_code.push('('); let mut open_parens = 1; while let Some(c) = chars.next() { @@ -183,15 +203,15 @@ fn extract_code_metadata(code: &str, main_name: &str) -> CodeMetadata { let filtered_code = filter_relevant_statements(code); - let ast = match Suite::parse(&filtered_code, "main.py") { - Ok(ast) => ast, + let ast = match parse_module(&filtered_code) { + Ok(parsed) => parsed.into_suite(), Err(_) => return CodeMetadata { enums, descriptions }, }; for stmt in ast { match stmt { - Stmt::ClassDef(StmtClassDef { name, body, bases, .. }) if has_enum => { - let is_enum = bases.iter().any(|base| { + Stmt::ClassDef(class_def) if has_enum => { + let is_enum = class_def.bases().iter().any(|base| { matches!(base, Expr::Name(ExprName { id, .. }) if id == "Enum" || id == "IntEnum" || id == "StrEnum" || id == "Flag" || id == "IntFlag") @@ -201,17 +221,15 @@ fn extract_code_metadata(code: &str, main_name: &str) -> CodeMetadata { let mut values = Vec::new(); let mut members = HashMap::new(); + let StmtClassDef { name, body, .. } = class_def; for item in body { if let Stmt::Assign(StmtAssign { targets, value, .. }) = item { if let Some(Expr::Name(ExprName { id: target_name, .. })) = targets.first() { if !target_name.starts_with('_') { - if let Expr::Constant(ExprConstant { - value: Constant::Str(val), - .. - }) = value.as_ref() - { + if let Expr::StringLiteral(val) = value.as_ref() { + let val = val.value.to_str(); values.push(val.to_string()); members.insert(target_name.to_string(), val.to_string()); } @@ -225,15 +243,13 @@ fn extract_code_metadata(code: &str, main_name: &str) -> CodeMetadata { } } } - Stmt::FunctionDef(StmtFunctionDef { name: func_name, body, .. }) if has_docstring => { - if &func_name == main_name { + Stmt::FunctionDef(StmtFunctionDef { + name: func_name, body, is_async: false, .. + }) if has_docstring => { + if func_name.as_str() == main_name { if let Some(Stmt::Expr(expr_stmt)) = body.first() { - if let Expr::Constant(ExprConstant { - value: Constant::Str(docstring), - .. - }) = expr_stmt.value.as_ref() - { - descriptions = parse_docstring_args(docstring); + if let Expr::StringLiteral(docstring) = expr_stmt.value.as_ref() { + descriptions = parse_docstring_args(docstring.value.to_str()); } } } @@ -294,6 +310,27 @@ fn parse_docstring_args(docstring: &str) -> HashMap { descriptions } +/// A line that reads as the definition of `main_name` can also sit inside a string, a docstring +/// showing an example for instance. When several lines do, only the parsed module tells which +/// one is the function. +fn main_params_among_lookalikes(code: &str, main_name: &str) -> Option { + code.split('\n') + .filter(|line| strip_def(line, main_name).is_some()) + .nth(1)?; + parse_module(code) + .ok()? + .into_suite() + .into_iter() + .find_map(|x| match x { + Stmt::FunctionDef(StmtFunctionDef { name, parameters, .. }) + if name.as_str() == main_name => + { + Some(*parameters) + } + _ => None, + }) +} + /// skip_params is a micro optimization for when we just want to find the main /// function without parsing all the params. pub fn parse_python_signature( @@ -310,41 +347,39 @@ pub fn parse_python_signature( // - If no models: parse only the filtered main function let (params, module) = if should_parse_for_models(code) { // Parse full code once for both Pydantic detection and signature extraction - let ast = Suite::parse(code, "main.py") - .map_err(|e| anyhow::anyhow!("Error parsing code: {}", e.to_string()))?; + let ast = parse_module(code) + .map_err(|e| anyhow::anyhow!("Error parsing code: {}", e.to_string()))? + .into_suite(); // Extract main function from full AST let params = ast.iter().find_map(|x| match x { - Stmt::FunctionDef(StmtFunctionDef { name, args, .. }) if name == &main_name => { - Some(args.as_ref().clone()) - } - Stmt::AsyncFunctionDef(StmtAsyncFunctionDef { name, args, .. }) - if name == &main_name => + Stmt::FunctionDef(StmtFunctionDef { name, parameters, .. }) + if name.as_str() == main_name => { - Some(args.as_ref().clone()) + Some(parameters.as_ref().clone()) } _ => None, }); // Keep AST for Pydantic/dataclass detection (params, Some(ast)) + } else if let Some(params) = main_params_among_lookalikes(code, &main_name) { + (Some(params), None) } else { // No models detected - parse only the filtered main function let filtered_code = filter_non_main(code, &main_name); if filtered_code.is_empty() { (None, None) } else { - let ast = Suite::parse(&filtered_code, "main.py") - .map_err(|e| anyhow::anyhow!("Error parsing code: {}", e.to_string()))?; + let ast = parse_module(&filtered_code) + .map_err(|e| anyhow::anyhow!("Error parsing code: {}", e.to_string()))? + .into_suite(); let params = ast.into_iter().find_map(|x| match x { - Stmt::FunctionDef(StmtFunctionDef { name, args, .. }) if &name == &main_name => { - Some(*args) - } - Stmt::AsyncFunctionDef(StmtAsyncFunctionDef { name, args, .. }) - if &name == &main_name => + Stmt::FunctionDef(StmtFunctionDef { name, parameters, .. }) + if name.as_str() == main_name => { - Some(*args) + Some(*parameters) } _ => None, }); @@ -378,8 +413,6 @@ pub fn parse_python_signature( if !skip_params && params.is_some() { let params = params.unwrap(); - let def_arg_start = params.args.len() - params.defaults().count(); - // Two-pass approach for lazy metadata extraction: // Pass 1: Parse types without enum info to determine if metadata is needed // Pass 2: Re-parse unknown types with metadata only if necessary @@ -392,11 +425,11 @@ pub fn parse_python_signature( .iter() .enumerate() .map(|(i, x)| { - let arg_name = x.as_arg().arg.to_string(); + let arg_name = x.parameter.name.to_string(); let (typ, has_default) = x - .as_arg() + .parameter .annotation - .as_ref() + .as_deref() .map_or((Typ::Unknown, false), |e| { parse_expr(e, &empty_enums, module_ref) }); @@ -423,21 +456,16 @@ pub fn parse_python_signature( .into_iter() .map(|(i, arg_name, mut typ, mut has_default)| { if matches!(typ, Typ::Resource(_)) && !metadata.enums.is_empty() { - if let Some(annotation) = params.args[i].as_arg().annotation.as_ref() { + if let Some(annotation) = params.args[i].parameter.annotation.as_deref() { (typ, has_default) = parse_expr(annotation, &metadata.enums, module_ref); } } - let default = if i >= def_arg_start { - params - .defaults() - .nth(i - def_arg_start) - .map(|expr| to_value(expr, &metadata.enums)) - .flatten() - } else { - None - }; + let default = params.args[i] + .default + .as_deref() + .and_then(|expr| to_value(expr, &metadata.enums)); let should_get_type_from_default = match &typ { Typ::Unknown => true, @@ -465,10 +493,10 @@ pub fn parse_python_signature( // debounce accumulation support. Falls back to docstring // description if no union array pattern is found. let union_otyp = params.args[i] - .as_arg() + .parameter .annotation - .as_ref() - .and_then(|ann| detect_py_union_array_otyp(ann.as_ref())); + .as_deref() + .and_then(detect_py_union_array_otyp); Arg { otyp: union_otyp.or_else(|| { @@ -509,12 +537,8 @@ pub fn parse_python_signature( } } -fn parse_expr( - e: &Box, - enums: &HashMap, - module: Option<&[Stmt]>, -) -> (Typ, bool) { - match e.as_ref() { +fn parse_expr(e: &Expr, enums: &HashMap, module: Option<&[Stmt]>) -> (Typ, bool) { + match e { Expr::Name(ExprName { id, .. }) => (parse_typ(id.as_ref(), enums, module), false), Expr::Attribute(x) => { if let Some(name) = x.value.as_name_expr() { @@ -531,12 +555,9 @@ fn parse_expr( } } Expr::BinOp(x) => { - if matches!( - x.right.as_ref(), - Expr::Constant(ExprConstant { value: Constant::None, .. }) - ) { + if x.right.is_none_literal_expr() { (parse_expr(&x.left, enums, module).0, true) - } else if detect_py_union_array_otyp(e.as_ref()).is_some() { + } else if detect_py_union_array_otyp(e).is_some() { // T | list[T] — parsed type is Unknown; otyp is set separately (Typ::Unknown, false) } else { @@ -552,7 +573,7 @@ fn parse_expr( .elts .iter() .map(|x| match x { - Expr::Constant(c) => c.value.as_str().map(|x| x.to_string()), + Expr::StringLiteral(s) => Some(s.value.to_str().to_string()), _ => None, }) .filter_map(|x| x) @@ -625,15 +646,26 @@ fn map_resource_name(x: &str) -> String { } } -fn to_value(et: &Expr, enums: &HashMap) -> Option { +fn to_value(et: &Expr, enums: &HashMap) -> Option { match et { - Expr::Constant(ExprConstant { value, .. }) => Some(constant_to_value(value)), - Expr::Dict(ExprDict { keys, values, .. }) => { - let v = keys - .into_iter() - .zip(values) - .map(|(k, v)| { - let key = k + Expr::NoneLiteral(_) => Some(json!(null)), + Expr::BooleanLiteral(b) => Some(json!(b.value)), + Expr::StringLiteral(s) => Some(json!(s.value.to_str())), + Expr::BytesLiteral(b) => Some(json!(b.value.bytes().collect::>())), + Expr::NumberLiteral(n) => Some(match &n.value { + Number::Int(i) => { + serde_json::from_str(&i.to_string()).unwrap_or(json!("invalid number")) + } + Number::Float(f) => json!(f), + Number::Complex { real, imag } => json!([real, imag]), + }), + Expr::EllipsisLiteral(_) => Some(json!("...")), + Expr::Dict(ExprDict { items, .. }) => { + let v = items + .iter() + .map(|item| { + let key = item + .key .as_ref() .map(|e| to_value(e, enums)) .flatten() @@ -642,7 +674,7 @@ fn to_value(et: &Expr, enums: &HashMap) -> Option None, }) .unwrap_or_else(|| "no_key".to_string()); - (key, to_value(&v, enums)) + (key, to_value(&item.value, enums)) }) .collect::>(); Some(json!(v)) @@ -672,20 +704,6 @@ fn to_value(et: &Expr, enums: &HashMap) -> Option serde_json::Value { - match c { - Constant::None => json!(null), - Constant::Bool(b) => json!(b), - Constant::Str(s) => json!(s), - Constant::Bytes(b) => json!(b), - Constant::Int(i) => serde_json::from_str(&i.to_string()).unwrap_or(json!("invalid number")), - Constant::Tuple(t) => json!(t.iter().map(constant_to_value).collect::>()), - Constant::Float(f) => json!(f), - Constant::Complex { real, imag } => json!([real, imag]), - Constant::Ellipsis => json!("..."), - } -} - #[cfg(test)] mod tests { @@ -1323,4 +1341,89 @@ def main(color: Color = Color.RED): ); Ok(()) } + + #[test] + fn test_parse_python_sig_type_params() -> anyhow::Result<()> { + for code in [ + "def main[T](x: str, y: int = 3):\n return x\n", + "async def main[T: (int, str), *Ts](x: str, y: int = 3):\n return x\n", + // parsed whole rather than pre-filtered down to `main` + "from dataclasses import dataclass\n\ndef main[T](x: str, y: int = 3):\n return x\n", + ] { + let result = parse_python_signature(code, None, false)?; + assert_eq!(result.auto_kind, None, "{code}"); + assert_eq!( + result + .args + .iter() + .map(|a| (a.name.as_str(), &a.typ, &a.default)) + .collect::>(), + vec![ + ("x", &Typ::Str(None), &None), + ("y", &Typ::Int, &Some(json!(3))) + ], + "{code}" + ); + } + Ok(()) + } + + // A script with a model class is parsed whole, so syntax anywhere in it reaches the parser. + #[test] + fn test_parse_python_sig_recent_syntax() -> anyhow::Result<()> { + let code = r#" +from dataclasses import dataclass +lazy import requests +lazy from pandas import DataFrame + +type Alias = list[int] + +@dataclass +class Point: + x: int + +try: + import a +except ImportError, ValueError: + pass + +D = {"a": 1} +L = [[1], [2]] +PEP701 = f"{D["a"]} {'\n'.join(["x"])}" +PEP798 = [*a for a in L] + +def main(p: Point, name: str = "world"): + return t"hello {name}" +"#; + let result = parse_python_signature(code, None, false)?; + assert_eq!(result.args.len(), 2); + assert_eq!( + result.args[0].typ, + Typ::Object(ObjectType::new( + Some("Point".to_string()), + Some(vec![windmill_parser::ObjectProperty { + key: "x".to_string(), + typ: Box::new(Typ::Int) + }]) + )) + ); + assert_eq!(result.args[1].default, Some(json!("world"))); + Ok(()) + } + + #[test] + fn test_parse_python_sig_main_lookalike_in_docstring() -> anyhow::Result<()> { + for example in ["def main[T](x: T):", "def main(x: int, y: int):"] { + let code = format!( + "\"\"\"Usage example:\n{example}\n return x\n\"\"\"\n\ndef main(value: str):\n return value\n" + ); + let result = parse_python_signature(&code, None, false)?; + assert_eq!( + result.args.iter().map(|a| &a.name).collect::>(), + vec!["value"], + "{code}" + ); + } + Ok(()) + } } diff --git a/backend/parsers/windmill-parser-py/src/pydantic_parser.rs b/backend/parsers/windmill-parser-py/src/pydantic_parser.rs index e229d97a8a..78a0a3c354 100644 --- a/backend/parsers/windmill-parser-py/src/pydantic_parser.rs +++ b/backend/parsers/windmill-parser-py/src/pydantic_parser.rs @@ -11,8 +11,8 @@ //! This module provides functionality to detect and parse Pydantic models and Python //! dataclasses from Python AST, enabling automatic UI generation for complex data structures. -use rustpython_parser::ast::{ - Constant, Expr, ExprAttribute, ExprCall, ExprConstant, ExprName, ExprTuple, Stmt, StmtAnnAssign, +use ruff_python_ast::{ + Decorator, Expr, ExprAttribute, ExprCall, ExprName, ExprTuple, Stmt, StmtAnnAssign, }; use std::collections::HashSet; use windmill_parser::{ObjectProperty, ObjectType, Typ}; @@ -64,7 +64,7 @@ fn detect_model_type_impl( // Mark as being visited visited.insert(class_name.to_string()); - let result = if is_pydantic_base(&class_def.bases) { + let result = if is_pydantic_base(class_def.bases()) { // Pydantic BaseModel parse_model_fields(&class_def.body, class_def.name.as_str(), module, visited) } else if has_dataclass_decorator(&class_def.decorator_list) @@ -115,9 +115,9 @@ fn is_pydantic_base(bases: &[Expr]) -> bool { } /// Checks if a class has @dataclass decorator (standard library) -fn has_dataclass_decorator(decorators: &[Expr]) -> bool { +fn has_dataclass_decorator(decorators: &[Decorator]) -> bool { for decorator in decorators { - match decorator { + match &decorator.expression { // Match: @dataclass Expr::Name(ExprName { id, .. }) if id.as_str() == "dataclass" => { return true; @@ -160,9 +160,9 @@ fn has_dataclass_decorator(decorators: &[Expr]) -> bool { } /// Checks if a class has @pydantic.dataclasses.dataclass decorator (Pydantic v2) -fn has_pydantic_dataclass_decorator(decorators: &[Expr]) -> bool { +fn has_pydantic_dataclass_decorator(decorators: &[Decorator]) -> bool { for decorator in decorators { - match decorator { + match &decorator.expression { // Match: @pydantic.dataclasses.dataclass Expr::Attribute(ExprAttribute { attr, value, .. }) if attr.as_str() == "dataclass" => { if let Expr::Attribute(ExprAttribute { @@ -350,10 +350,10 @@ fn extract_field_type( // String annotations: "ForwardRef" (forward references) // Not fully supported - return Unknown with warning - Expr::Constant(ExprConstant { value: Constant::Str(s), .. }) => { + Expr::StringLiteral(s) => { eprintln!( "Forward references like \"{forward_ref}\" are not yet supported, treating as Unknown", - forward_ref = s, + forward_ref = s.value.to_str(), ); Typ::Unknown } diff --git a/backend/parsers/windmill-parser-r/Cargo.toml b/backend/parsers/windmill-parser-r/Cargo.toml index 42701f9c12..d489bc966d 100644 --- a/backend/parsers/windmill-parser-r/Cargo.toml +++ b/backend/parsers/windmill-parser-r/Cargo.toml @@ -7,6 +7,8 @@ authors.workspace = true [lib] name = "windmill_parser_r" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [dependencies] windmill-parser.workspace = true diff --git a/backend/parsers/windmill-parser-ruby/Cargo.toml b/backend/parsers/windmill-parser-ruby/Cargo.toml index 779b0116a0..ca996528b1 100644 --- a/backend/parsers/windmill-parser-ruby/Cargo.toml +++ b/backend/parsers/windmill-parser-ruby/Cargo.toml @@ -7,6 +7,8 @@ authors.workspace = true [lib] name = "windmill_parser_ruby" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [dependencies] windmill-parser.workspace = true diff --git a/backend/parsers/windmill-parser-rust/Cargo.toml b/backend/parsers/windmill-parser-rust/Cargo.toml index e1dcf84449..e4654590ff 100644 --- a/backend/parsers/windmill-parser-rust/Cargo.toml +++ b/backend/parsers/windmill-parser-rust/Cargo.toml @@ -7,6 +7,8 @@ authors.workspace = true [lib] name = "windmill_parser_rust" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [dependencies] windmill-parser.workspace = true diff --git a/backend/parsers/windmill-parser-sql-asset/Cargo.toml b/backend/parsers/windmill-parser-sql-asset/Cargo.toml index 73835b2c06..5b22c38350 100644 --- a/backend/parsers/windmill-parser-sql-asset/Cargo.toml +++ b/backend/parsers/windmill-parser-sql-asset/Cargo.toml @@ -7,6 +7,8 @@ authors.workspace = true [lib] name = "windmill_parser_sql_asset" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [dependencies] windmill-parser.workspace = true diff --git a/backend/parsers/windmill-parser-sql-asset/src/asset_parser_utils.rs b/backend/parsers/windmill-parser-sql-asset/src/asset_parser_utils.rs index b29c6c99ac..4d77da15bb 100644 --- a/backend/parsers/windmill-parser-sql-asset/src/asset_parser_utils.rs +++ b/backend/parsers/windmill-parser-sql-asset/src/asset_parser_utils.rs @@ -20,13 +20,16 @@ pub fn parse_wmill_sdk_sql_assets( Ok(mut sql_assets) => { if let Some(schema) = schema { for asset in &mut sql_assets.assets { - if asset.kind == kind && asset.path.starts_with(asset_name) { - asset.path = format!( - "{}/{}.{}", - asset_name, - schema, - &asset.path[asset_name.len() + 1..] - ); + if asset.kind != kind { + continue; + } + // A statement can name the database alone, with no table to qualify. + let table = asset + .path + .strip_prefix(asset_name) + .and_then(|rest| rest.strip_prefix('/')); + if let Some(table) = table { + asset.path = format!("{asset_name}/{schema}.{table}"); } } } diff --git a/backend/parsers/windmill-parser-sql/Cargo.toml b/backend/parsers/windmill-parser-sql/Cargo.toml index 143b02a2cc..7963de819c 100644 --- a/backend/parsers/windmill-parser-sql/Cargo.toml +++ b/backend/parsers/windmill-parser-sql/Cargo.toml @@ -7,6 +7,8 @@ authors.workspace = true [lib] name = "windmill_parser_sql" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [target.'cfg(target_arch = "wasm32")'.dependencies] regex-lite.workspace = true diff --git a/backend/parsers/windmill-parser-sql/src/lib.rs b/backend/parsers/windmill-parser-sql/src/lib.rs index 10929e409a..341906a3e3 100644 --- a/backend/parsers/windmill-parser-sql/src/lib.rs +++ b/backend/parsers/windmill-parser-sql/src/lib.rs @@ -235,7 +235,7 @@ lazy_static::lazy_static! { // -- $name (type) = default static ref RE_ARG_DUCKDB: Regex = Regex::new(r#"(?m)^-- \$(\w+) \(([A-Za-z0-9_\[\]]+)\)(?: ?\= ?(.+))? *(?:\r|\n|$)"#).unwrap(); - static ref RE_ARG_SNOWFLAKE: Regex = Regex::new(r#"(?m)^-- \? (\w+) \((\w+)\)(?: ?\= ?(.+))? *(?:\r|\n|$)"#).unwrap(); + static ref RE_ARG_SNOWFLAKE: Regex = Regex::new(r#"(?m)^-- \? (\w+) \((\w+(?:\[\])?)\)(?: ?\= ?(.+))? *(?:\r|\n|$)"#).unwrap(); static ref RE_ARG_MSSQL: Regex = Regex::new(r#"(?m)^-- @(?:P|p)\d+ (\w+) \((\w+)\)(?: ?\= ?(.+))? *(?:\r|\n|$)"#).unwrap(); @@ -254,6 +254,12 @@ fn parsed_default(parsed_typ: &Typ, default: String) -> Option= 2 && default.starts_with("'") && default.ends_with("'") => { Some(json!(&default[1..default.len() - 1])) } + Typ::List(_) => Some( + serde_json::from_str::(&default) + .ok() + .filter(|v| v.is_array()) + .unwrap_or_else(|| json!(default)), + ), _ => Some(json!(default)), } } @@ -1039,7 +1045,11 @@ pub fn parse_duckdb_typ(typ: &str) -> Typ { } pub fn parse_snowflake_typ(typ: &str) -> Typ { + if let Some(base_typ) = typ.strip_suffix("[]") { + return Typ::List(Box::new(parse_snowflake_typ(base_typ))); + } match typ { + "array" => Typ::List(Box::new(Typ::Unknown)), "varchar" | "text" | "string" | "char" | "character" => Typ::Str(None), "binary" | "varbinary" => Typ::Bytes, "date" | "time" | "datetime" | "timestamp" | "timestamp_ntz" | "timestamp_ltz" @@ -1591,6 +1601,39 @@ SELECT ?; Ok(()) } + #[test] + fn test_parse_snowflake_array_types() -> anyhow::Result<()> { + let code = r#" +-- ? groups (varchar[]) +-- ? ids (int[]) = [1, 2] +-- ? anything (ARRAY) +SELECT 1; +"#; + let args = parse_snowflake_sig(code)?.args; + assert_eq!(args[1].default, Some(json!([1, 2]))); + let got = args + .iter() + .map(|a| (a.name.as_str(), a.otyp.as_deref(), &a.typ)) + .collect::>(); + assert_eq!( + got, + vec![ + ( + "groups", + Some("varchar[]"), + &Typ::List(Box::new(Typ::Str(None))) + ), + ("ids", Some("int[]"), &Typ::List(Box::new(Typ::Int))), + ( + "anything", + Some("array"), + &Typ::List(Box::new(Typ::Unknown)) + ), + ] + ); + Ok(()) + } + #[test] fn test_parse_mssql_sig() -> anyhow::Result<()> { let code = r#" diff --git a/backend/parsers/windmill-parser-ts-asset/Cargo.toml b/backend/parsers/windmill-parser-ts-asset/Cargo.toml index f1c668d4eb..17a0279bdc 100644 --- a/backend/parsers/windmill-parser-ts-asset/Cargo.toml +++ b/backend/parsers/windmill-parser-ts-asset/Cargo.toml @@ -7,6 +7,8 @@ authors.workspace = true [lib] name = "windmill_parser_ts_asset" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [target.'cfg(target_arch = "wasm32")'.dependencies] wasm-bindgen.workspace = true diff --git a/backend/parsers/windmill-parser-ts/Cargo.toml b/backend/parsers/windmill-parser-ts/Cargo.toml index 5f04b14f3b..36dce90090 100644 --- a/backend/parsers/windmill-parser-ts/Cargo.toml +++ b/backend/parsers/windmill-parser-ts/Cargo.toml @@ -8,6 +8,9 @@ authors.workspace = true [lib] name = "windmill_parser_ts" path = "./src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [target.'cfg(target_arch = "wasm32")'.dependencies] wasm-bindgen.workspace = true diff --git a/backend/parsers/windmill-parser-ts/src/lib.rs b/backend/parsers/windmill-parser-ts/src/lib.rs index ac75080994..8059851707 100644 --- a/backend/parsers/windmill-parser-ts/src/lib.rs +++ b/backend/parsers/windmill-parser-ts/src/lib.rs @@ -189,7 +189,20 @@ pub fn parse_expr_for_imports(code: &str, skip_type_only: bool) -> anyhow::Resul /// // Returns: ["f/utils"] /// ``` pub fn parse_relative_imports(code: &str, path: &str) -> anyhow::Result> { - let imports = parse_expr_for_imports(code, false)?; + resolve_relative_imports(code, path, false) +} + +/// [`parse_relative_imports`] without type-only imports, which are erased before the code runs. +pub fn parse_runtime_relative_imports(code: &str, path: &str) -> anyhow::Result> { + resolve_relative_imports(code, path, true) +} + +fn resolve_relative_imports( + code: &str, + path: &str, + skip_type_only: bool, +) -> anyhow::Result> { + let imports = parse_expr_for_imports(code, skip_type_only)?; let script_dir = path.rsplit_once('/').map(|(dir, _)| dir).unwrap_or(""); let mut resolved: Vec = imports diff --git a/backend/parsers/windmill-parser-ts/tests/tests.rs b/backend/parsers/windmill-parser-ts/tests/tests.rs index b4abc23488..8b9587d3a2 100644 --- a/backend/parsers/windmill-parser-ts/tests/tests.rs +++ b/backend/parsers/windmill-parser-ts/tests/tests.rs @@ -4,7 +4,7 @@ mod tests { use windmill_parser::{Arg, MainArgSignature, ObjectProperty, ObjectType, Typ}; use windmill_parser_ts::{ parse_deno_signature, parse_expr_for_imports, parse_relative_imports, - remove_pinned_import_specifiers, + parse_runtime_relative_imports, remove_pinned_import_specifiers, }; /// The server parses defaults natively, where a non-JSON literal cannot be evaluated @@ -944,6 +944,19 @@ export const label = "pkg@1.2.3"; assert_eq!(result, vec!["f/folder/helper"]); } + #[test] + fn test_runtime_relative_imports_skip_type_only() { + let code = r#" + import type { Shape } from "./types"; + import { helper } from "./helper"; + export async function main(s: Shape) { return helper(s); } + "#; + let result = parse_runtime_relative_imports(code, "f/folder/script").unwrap(); + assert_eq!(result, vec!["f/folder/helper"]); + let all = parse_relative_imports(code, "f/folder/script").unwrap(); + assert_eq!(all, vec!["f/folder/helper", "f/folder/types"]); + } + #[test] fn test_relative_imports_double_dot() { let code = r#" diff --git a/backend/parsers/windmill-parser-wac/Cargo.toml b/backend/parsers/windmill-parser-wac/Cargo.toml index d354b1c653..5dccb0aa0a 100644 --- a/backend/parsers/windmill-parser-wac/Cargo.toml +++ b/backend/parsers/windmill-parser-wac/Cargo.toml @@ -7,10 +7,14 @@ authors.workspace = true [lib] name = "windmill_parser_wac" path = "./src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [dependencies] -rustpython-parser.workspace = true -rustpython-ast = { version = "0.4.0", features = ["visitor"] } +ruff_python_parser.workspace = true +ruff_python_ast.workspace = true +ruff_text_size.workspace = true swc_common.workspace = true swc_ecma_parser.workspace = true swc_ecma_ast.workspace = true diff --git a/backend/parsers/windmill-parser-wac/src/python.rs b/backend/parsers/windmill-parser-wac/src/python.rs index f91067b711..e8fb72ff2f 100644 --- a/backend/parsers/windmill-parser-wac/src/python.rs +++ b/backend/parsers/windmill-parser-wac/src/python.rs @@ -1,12 +1,12 @@ use std::collections::HashMap; -use rustpython_parser::{ - ast::{ - Expr, ExprAwait, ExprCall, ExprName, Stmt, StmtExpr, StmtFor, StmtIf, StmtReturn, StmtTry, - StmtTryStar, StmtWhile, - }, - Parse, +use ruff_python_ast::{ + CmpOp, ElifElseClause, ExceptHandler, Expr, ExprAttribute, ExprAwait, ExprCall, ExprName, + Number, Parameters, Stmt, StmtExpr, StmtFor, StmtFunctionDef, StmtIf, StmtReturn, StmtTry, + StmtWhile, }; +use ruff_python_parser::parse_module; +use ruff_text_size::{Ranged, TextSize}; use crate::dag::{DagEdge, DagNode, DagNodeType, Param, WorkflowDag}; use crate::validation::{self, CompileError}; @@ -42,9 +42,9 @@ type TaskFunctions = HashMap>; fn collect_task_functions(stmts: &[Stmt]) -> TaskFunctions { let mut tasks = HashMap::new(); for stmt in stmts { - if let Stmt::AsyncFunctionDef(func) = stmt { + if let Stmt::FunctionDef(func @ StmtFunctionDef { is_async: true, .. }) = stmt { for dec in &func.decorator_list { - match dec { + match &dec.expression { // @task (bare decorator) Expr::Name(ExprName { id, .. }) if id.as_str() == "task" => { tasks.insert(func.name.to_string(), None); @@ -68,13 +68,9 @@ fn collect_task_functions(stmts: &[Stmt]) -> TaskFunctions { if let Expr::Name(ExprName { id, .. }) = call.func.as_ref() { if id.as_str() == "task_script" || id.as_str() == "task_flow" { // Extract the path from the first positional argument - let path = call.args.first().and_then(|arg| { - if let Expr::Constant(c) = arg { - if let rustpython_parser::ast::Constant::Str(s) = &c.value { - return Some(s.to_string()); - } - } - None + let path = call.arguments.args.first().and_then(|arg| match arg { + Expr::StringLiteral(s) => Some(s.value.to_str().to_string()), + _ => None, }); // Extract variable name from target if let Some(Expr::Name(ExprName { id: var_name, .. })) = @@ -92,13 +88,11 @@ fn collect_task_functions(stmts: &[Stmt]) -> TaskFunctions { /// Extract the `path=` keyword argument from a `@task(path="...")` call. fn extract_task_path_kwarg(call: &ExprCall) -> Option { - for kw in &call.keywords { + for kw in &call.arguments.keywords { if let Some(ref arg) = kw.arg { if arg.as_str() == "path" { - if let Expr::Constant(c) = &kw.value { - if let rustpython_parser::ast::Constant::Str(s) = &c.value { - return Some(s.to_string()); - } + if let Expr::StringLiteral(s) = &kw.value { + return Some(s.value.to_str().to_string()); } } } @@ -150,10 +144,9 @@ impl WacWalker { fn line_of_expr(&self, expr: &Expr) -> usize { let offset = match expr { - Expr::Call(c) => c.range.start().to_usize(), - Expr::Await(a) => a.range.start().to_usize(), - Expr::Attribute(a) => a.range.start().to_usize(), - Expr::Name(n) => n.range.start().to_usize(), + Expr::Call(_) | Expr::Await(_) | Expr::Attribute(_) | Expr::Name(_) => { + expr.start().to_usize() + } _ => 0, }; self.line_index.line_of(offset) @@ -161,17 +154,15 @@ impl WacWalker { fn line_of_stmt(&self, stmt: &Stmt) -> usize { let offset = match stmt { - Stmt::If(s) => s.range.start().to_usize(), - Stmt::For(s) => s.range.start().to_usize(), - Stmt::While(s) => s.range.start().to_usize(), - Stmt::Return(s) => s.range.start().to_usize(), - Stmt::Expr(s) => s.range.start().to_usize(), - Stmt::Try(s) => s.range.start().to_usize(), - Stmt::TryStar(s) => s.range.start().to_usize(), - Stmt::Assign(s) => s.range.start().to_usize(), - Stmt::AnnAssign(s) => s.range.start().to_usize(), - Stmt::FunctionDef(s) => s.range.start().to_usize(), - Stmt::AsyncFunctionDef(s) => s.range.start().to_usize(), + Stmt::If(_) + | Stmt::For(_) + | Stmt::While(_) + | Stmt::Return(_) + | Stmt::Expr(_) + | Stmt::Try(_) + | Stmt::Assign(_) + | Stmt::AnnAssign(_) + | Stmt::FunctionDef(_) => stmt.start().to_usize(), _ => 0, }; self.line_index.line_of(offset) @@ -190,9 +181,7 @@ impl WacWalker { /// Check if an expression is `asyncio.gather(...)` call fn is_asyncio_gather_call(expr: &Expr) -> bool { if let Expr::Call(call) = expr { - if let Expr::Attribute(rustpython_parser::ast::ExprAttribute { value, attr, .. }) = - call.func.as_ref() - { + if let Expr::Attribute(ExprAttribute { value, attr, .. }) = call.func.as_ref() { if attr.as_str() == "gather" { if let Expr::Name(ExprName { id, .. }) = value.as_ref() { return id.as_str() == "asyncio"; @@ -222,20 +211,20 @@ impl WacWalker { fn expr_to_source(expr: &Expr) -> String { match expr { Expr::Compare(c) => { - let left = Self::expr_to_source(&c.left); - if let Some(comparator) = c.comparators.first() { + let left = Self::expr_to_source(&c.operands[0]); + if let Some(comparator) = c.comparators().first() { let right = Self::expr_to_source(comparator); let op = match c.ops.first() { - Some(rustpython_parser::ast::CmpOp::Gt) => ">", - Some(rustpython_parser::ast::CmpOp::Lt) => "<", - Some(rustpython_parser::ast::CmpOp::GtE) => ">=", - Some(rustpython_parser::ast::CmpOp::LtE) => "<=", - Some(rustpython_parser::ast::CmpOp::Eq) => "==", - Some(rustpython_parser::ast::CmpOp::NotEq) => "!=", - Some(rustpython_parser::ast::CmpOp::In) => "in", - Some(rustpython_parser::ast::CmpOp::NotIn) => "not in", - Some(rustpython_parser::ast::CmpOp::Is) => "is", - Some(rustpython_parser::ast::CmpOp::IsNot) => "is not", + Some(CmpOp::Gt) => ">", + Some(CmpOp::Lt) => "<", + Some(CmpOp::GtE) => ">=", + Some(CmpOp::LtE) => "<=", + Some(CmpOp::Eq) => "==", + Some(CmpOp::NotEq) => "!=", + Some(CmpOp::In) => "in", + Some(CmpOp::NotIn) => "not in", + Some(CmpOp::Is) => "is", + Some(CmpOp::IsNot) => "is not", None => "?", }; format!("{left} {op} {right}") @@ -253,14 +242,14 @@ impl WacWalker { format!("{value}.{}", a.attr) } Expr::Name(n) => n.id.to_string(), - Expr::Constant(c) => match &c.value { - rustpython_parser::ast::Constant::Str(s) => format!("\"{s}\""), - rustpython_parser::ast::Constant::Int(i) => i.to_string(), - rustpython_parser::ast::Constant::Float(f) => f.to_string(), - rustpython_parser::ast::Constant::Bool(b) => b.to_string(), - rustpython_parser::ast::Constant::None => "None".to_string(), - _ => "...".to_string(), + Expr::StringLiteral(s) => format!("\"{}\"", s.value.to_str()), + Expr::NumberLiteral(n) => match &n.value { + Number::Int(i) => i.to_string(), + Number::Float(f) => f.to_string(), + Number::Complex { .. } => "...".to_string(), }, + Expr::BooleanLiteral(b) => b.value.to_string(), + Expr::NoneLiteral(_) => "None".to_string(), _ => "...".to_string(), } } @@ -279,8 +268,16 @@ impl WacWalker { match stmt { Stmt::Expr(StmtExpr { value, .. }) => self.expr_contains_step(value), Stmt::Assign(a) => self.expr_contains_step(&a.value), - Stmt::If(s) => self.body_contains_step(&s.body) || self.body_contains_step(&s.orelse), - Stmt::For(s) => self.body_contains_step(&s.body) || self.body_contains_step(&s.orelse), + Stmt::If(s) => { + self.body_contains_step(&s.body) + || s.elif_else_clauses + .iter() + .any(|clause| self.body_contains_step(&clause.body)) + } + // `async for` is not modelled: its body is skipped like any unsupported statement + Stmt::For(s) if !s.is_async => { + self.body_contains_step(&s.body) || self.body_contains_step(&s.orelse) + } Stmt::While(s) => { self.body_contains_step(&s.body) || self.body_contains_step(&s.orelse) } @@ -289,19 +286,7 @@ impl WacWalker { || self.body_contains_step(&s.orelse) || self.body_contains_step(&s.finalbody) || s.handlers.iter().any(|h| match h { - rustpython_parser::ast::ExceptHandler::ExceptHandler(eh) => { - self.body_contains_step(&eh.body) - } - }) - } - Stmt::TryStar(s) => { - self.body_contains_step(&s.body) - || self.body_contains_step(&s.orelse) - || self.body_contains_step(&s.finalbody) - || s.handlers.iter().any(|h| match h { - rustpython_parser::ast::ExceptHandler::ExceptHandler(eh) => { - self.body_contains_step(&eh.body) - } + ExceptHandler::ExceptHandler(eh) => self.body_contains_step(&eh.body), }) } Stmt::Return(_) => false, @@ -319,11 +304,12 @@ impl WacWalker { match expr { Expr::Await(ExprAwait { value, .. }) => self.expr_contains_step(value), Expr::Call(call) => { - if self.is_task_fn_call(&Expr::Call(call.clone())) { - return true; - } - if Self::is_asyncio_gather_call(&Expr::Call(call.clone())) { - return call.args.iter().any(|a| self.expr_contains_step(a)); + if Self::is_asyncio_gather_call(expr) { + return call + .arguments + .args + .iter() + .any(|a| self.expr_contains_step(a)); } false } @@ -370,12 +356,11 @@ impl WacWalker { Stmt::Expr(StmtExpr { value, .. }) => self.walk_expr_stmt(value), Stmt::Assign(a) => self.walk_expr_stmt(&a.value), Stmt::If(if_stmt) => self.walk_if(if_stmt), - Stmt::For(for_stmt) => self.walk_for(for_stmt), + Stmt::For(for_stmt) if !for_stmt.is_async => self.walk_for(for_stmt), Stmt::While(while_stmt) => self.walk_while(while_stmt), Stmt::Try(try_stmt) => self.walk_try(try_stmt), - Stmt::TryStar(try_stmt) => self.walk_try_star(try_stmt), Stmt::Return(ret) => self.walk_return(ret), - Stmt::FunctionDef(_) | Stmt::AsyncFunctionDef(_) => { + Stmt::FunctionDef(_) => { if self.stmt_contains_step(stmt) { self.errors.push(validation::error_step_in_nested_function( self.line_of_stmt(stmt), @@ -392,7 +377,7 @@ impl WacWalker { if let Expr::Await(ExprAwait { value, .. }) = expr { // await task_fn(...) if let Expr::Call(call) = value.as_ref() { - if self.is_task_fn_call(&Expr::Call(call.clone())) { + if self.is_task_fn_call(value) { return self.emit_step(call, expr); } // Check for SDK-level calls: step(), sleep(), wait_for_approval() @@ -430,15 +415,12 @@ impl WacWalker { "step" => { // step("name", fn) — extract the name from the first string argument let name = call + .arguments .args .first() - .and_then(|arg| { - if let Expr::Constant(c) = arg { - if let rustpython_parser::ast::Constant::Str(s) = &c.value { - return Some(s.to_string()); - } - } - None + .and_then(|arg| match arg { + Expr::StringLiteral(s) => Some(s.value.to_str().to_string()), + _ => None, }) .unwrap_or_else(|| "step".to_string()); let id = self.next_id(); @@ -452,6 +434,7 @@ impl WacWalker { } "sleep" => { let seconds = call + .arguments .args .first() .map(|arg| Self::expr_to_source(arg)) @@ -517,10 +500,10 @@ impl WacWalker { }); let mut step_ids = Vec::new(); - for arg in &gather_call.args { + for arg in &gather_call.arguments.args { // Each arg should be task_fn(...) if let Expr::Call(call) = arg { - if self.is_task_fn_call(&Expr::Call(call.clone())) { + if self.is_task_fn_call(arg) { let (name, script) = self .extract_step_info_from_task_call(call) .unwrap_or(("unknown".into(), "unknown".into())); @@ -553,15 +536,33 @@ impl WacWalker { } fn walk_if(&mut self, if_stmt: &StmtIf) -> Option<(String, String)> { - let has_steps_in_body = self.body_contains_step(&if_stmt.body); - let has_steps_in_else = self.body_contains_step(&if_stmt.orelse); + self.walk_if_chain( + if_stmt.start(), + &if_stmt.test, + &if_stmt.body, + &if_stmt.elif_else_clauses, + ) + } + + /// An `elif` is laid out as an `if` nested alone in the `else` of the clause before it. + fn walk_if_chain( + &mut self, + start: TextSize, + test: &Expr, + body: &[Stmt], + clauses: &[ElifElseClause], + ) -> Option<(String, String)> { + let has_steps_in_body = self.body_contains_step(body); + let has_steps_in_else = clauses + .iter() + .any(|clause| self.body_contains_step(&clause.body)); if !has_steps_in_body && !has_steps_in_else { return None; } - let line = self.line_index.line_of(if_stmt.range.start().to_usize()); - let condition_source = Self::expr_to_source(&if_stmt.test); + let line = self.line_index.line_of(start.to_usize()); + let condition_source = Self::expr_to_source(test); let branch_id = self.next_id(); let branch_node_id = self.add_node(DagNode { @@ -573,15 +574,19 @@ impl WacWalker { let mut last_ids = Vec::new(); - if let Some((true_first, true_last)) = self.walk_body(&if_stmt.body) { + if let Some((true_first, true_last)) = self.walk_body(body) { self.add_edge(&branch_node_id, &true_first, Some("true".to_string())); last_ids.push(true_last); } else { last_ids.push(branch_node_id.clone()); } - if !if_stmt.orelse.is_empty() { - if let Some((else_first, else_last)) = self.walk_body(&if_stmt.orelse) { + if let Some((clause, clauses)) = clauses.split_first() { + let orelse = match &clause.test { + Some(test) => self.walk_if_chain(clause.start(), test, &clause.body, clauses), + None => self.walk_body(&clause.body), + }; + if let Some((else_first, else_last)) = orelse { self.add_edge(&branch_node_id, &else_first, Some("false".to_string())); last_ids.push(else_last); } else { @@ -611,7 +616,7 @@ impl WacWalker { return None; } - let line = self.line_index.line_of(for_stmt.range.start().to_usize()); + let line = self.line_index.line_of(for_stmt.start().to_usize()); let iter_source = Self::expr_to_source(&for_stmt.iter); let start_id = self.next_id(); @@ -644,7 +649,7 @@ impl WacWalker { return None; } - let line = self.line_index.line_of(while_stmt.range.start().to_usize()); + let line = self.line_index.line_of(while_stmt.start().to_usize()); let condition = Self::expr_to_source(&while_stmt.test); let start_id = self.next_id(); @@ -677,39 +682,14 @@ impl WacWalker { || self.body_contains_step(&try_stmt.orelse) || self.body_contains_step(&try_stmt.finalbody) || try_stmt.handlers.iter().any(|h| match h { - rustpython_parser::ast::ExceptHandler::ExceptHandler(eh) => { - self.body_contains_step(&eh.body) - } + ExceptHandler::ExceptHandler(eh) => self.body_contains_step(&eh.body), }); if !has_steps { return None; } - let line = self.line_index.line_of(try_stmt.range.start().to_usize()); - self.emit_try_catch_branch( - &try_stmt.body, - &try_stmt.handlers, - &try_stmt.finalbody, - line, - ) - } - - fn walk_try_star(&mut self, try_stmt: &StmtTryStar) -> Option<(String, String)> { - let has_steps = self.body_contains_step(&try_stmt.body) - || self.body_contains_step(&try_stmt.orelse) - || self.body_contains_step(&try_stmt.finalbody) - || try_stmt.handlers.iter().any(|h| match h { - rustpython_parser::ast::ExceptHandler::ExceptHandler(eh) => { - self.body_contains_step(&eh.body) - } - }); - - if !has_steps { - return None; - } - - let line = self.line_index.line_of(try_stmt.range.start().to_usize()); + let line = self.line_index.line_of(try_stmt.start().to_usize()); self.emit_try_catch_branch( &try_stmt.body, &try_stmt.handlers, @@ -721,7 +701,7 @@ impl WacWalker { fn emit_try_catch_branch( &mut self, try_body: &[Stmt], - handlers: &[rustpython_parser::ast::ExceptHandler], + handlers: &[ExceptHandler], finally_body: &[Stmt], line: usize, ) -> Option<(String, String)> { @@ -746,7 +726,7 @@ impl WacWalker { // Except handlers for handler in handlers { match handler { - rustpython_parser::ast::ExceptHandler::ExceptHandler(eh) => { + ExceptHandler::ExceptHandler(eh) => { if let Some((catch_first, catch_last)) = self.walk_body(&eh.body) { self.add_edge(&branch_node_id, &catch_first, Some("except".to_string())); last_ids.push(catch_last); @@ -783,7 +763,7 @@ impl WacWalker { } fn walk_return(&mut self, ret: &StmtReturn) -> Option<(String, String)> { - let line = self.line_index.line_of(ret.range.start().to_usize()); + let line = self.line_index.line_of(ret.start().to_usize()); let id = self.next_id(); let node_id = self.add_node(DagNode { id: id.clone(), @@ -796,12 +776,12 @@ impl WacWalker { } /// Extract workflow function parameters (no longer skips ctx) -fn extract_params(args: &rustpython_parser::ast::Arguments) -> Vec { +fn extract_params(args: &Parameters) -> Vec { let mut params = Vec::new(); for arg_with_default in args.args.iter().chain(args.posonlyargs.iter()) { - let name = arg_with_default.def.arg.to_string(); + let name = arg_with_default.parameter.name.to_string(); let typ = arg_with_default - .def + .parameter .annotation .as_ref() .map(|ann| WacWalker::expr_to_source(ann)); @@ -811,59 +791,34 @@ fn extract_params(args: &rustpython_parser::ast::Arguments) -> Vec { } pub fn parse_python_workflow(code: &str) -> Result> { - let ast = rustpython_parser::ast::Suite::parse(code, "") - .map_err(|e| vec![CompileError { message: format!("Parse error: {e}"), line: 0 }])?; + let ast = parse_module(code) + .map_err(|e| vec![CompileError { message: format!("Parse error: {e}"), line: 0 }])? + .into_suite(); // First pass: collect @task functions let task_functions = collect_task_functions(&ast); - // Find the @workflow async def - let workflow_fn = ast.iter().find_map(|stmt| { - if let Stmt::AsyncFunctionDef(func) = stmt { - let has_workflow_decorator = func.decorator_list.iter().any(|dec| { - if let Expr::Name(ExprName { id, .. }) = dec { - id.as_str() == "workflow" - } else { - false - } - }); - if has_workflow_decorator { - return Some(func); + let workflow_fns = || { + ast.iter().filter_map(|stmt| match stmt { + Stmt::FunctionDef(func) + if func.decorator_list.iter().any(|dec| { + matches!(&dec.expression, Expr::Name(ExprName { id, .. }) if id.as_str() == "workflow") + }) => + { + Some(func) } - } - // Also check non-async for error reporting - if let Stmt::FunctionDef(func) = stmt { - let has_workflow_decorator = func.decorator_list.iter().any(|dec| { - if let Expr::Name(ExprName { id, .. }) = dec { - id.as_str() == "workflow" - } else { - false - } - }); - if has_workflow_decorator { - return None; // Will be reported as not-async below - } - } - None - }); + _ => None, + }) + }; - // Check for non-async workflow function - let non_async_workflow = ast.iter().find_map(|stmt| { - if let Stmt::FunctionDef(func) = stmt { - let has_workflow_decorator = func.decorator_list.iter().any(|dec| { - if let Expr::Name(ExprName { id, .. }) = dec { - id.as_str() == "workflow" - } else { - false - } - }); - if has_workflow_decorator { - let line_index = LineIndex::new(code); - return Some(line_index.line_of(func.range.start().to_usize())); - } - } - None - }); + // Find the @workflow async def + let workflow_fn = workflow_fns().find(|func| func.is_async); + + // Check for non-async workflow function. The statement starts at its first decorator, + // the name sits on the `def` line the error points at. + let non_async_workflow = workflow_fns() + .find(|func| !func.is_async) + .map(|func| LineIndex::new(code).line_of(func.name.start().to_usize())); if let Some(line) = non_async_workflow { if workflow_fn.is_none() { @@ -875,7 +830,7 @@ pub fn parse_python_workflow(code: &str) -> Result String { hasher.update(code.as_bytes()); format!("{:x}", hasher.finalize()) } - -trait ToUsize { - fn to_usize(self) -> usize; -} - -impl ToUsize for rustpython_parser::text_size::TextSize { - fn to_usize(self) -> usize { - u32::from(self) as usize - } -} diff --git a/backend/parsers/windmill-parser-wac/tests/python_tests.rs b/backend/parsers/windmill-parser-wac/tests/python_tests.rs index cf117da9e7..c0de489153 100644 --- a/backend/parsers/windmill-parser-wac/tests/python_tests.rs +++ b/backend/parsers/windmill-parser-wac/tests/python_tests.rs @@ -363,3 +363,77 @@ async def main(x: str): )); assert!(matches!(dag.nodes[5].node_type, DagNodeType::Return)); } + +#[test] +fn test_elif_chain_nests_branches() { + let code = r#" +from wmill import workflow, task + +@task +async def a(): ... +@task +async def b(): ... +@task +async def c(): ... + +@workflow +async def main(x: int): + if x > 2: + await a() + elif x == 2: + await b() + else: + await c() +"#; + + let dag = parse_python_workflow(code).expect("should parse"); + let branches: Vec<(&str, usize)> = dag + .nodes + .iter() + .filter_map(|n| match &n.node_type { + DagNodeType::Branch { condition_source } => Some((condition_source.as_str(), n.line)), + _ => None, + }) + .collect(); + assert_eq!(branches, vec![("x > 2", 13), ("x == 2", 15)]); + + // The `elif` branch hangs off the `false` edge of the `if` before it + let (outer, inner) = (&dag.nodes[0].id, &dag.nodes[2].id); + assert!(dag + .edges + .iter() + .any(|e| &e.from == outer && &e.to == inner && e.label.as_deref() == Some("false"))); + assert_eq!( + dag.nodes + .iter() + .filter(|n| matches!(n.node_type, DagNodeType::Merge)) + .count(), + 2 + ); +} + +#[test] +fn test_workflow_with_recent_syntax() { + let code = r#" +from wmill import workflow, task +lazy import polars + +type Rows = list[dict] + +@task +async def load[T](rows: T): ... + +@workflow +async def main(name: str): + try: + await load(t"hello {name}") + except ValueError, TypeError: + pass +"#; + + let dag = parse_python_workflow(code).expect("should parse"); + assert!(dag + .nodes + .iter() + .any(|n| matches!(&n.node_type, DagNodeType::Step { name, .. } if name == "load"))); +} diff --git a/backend/parsers/windmill-parser-wasm/Cargo.lock b/backend/parsers/windmill-parser-wasm/Cargo.lock index 99d82bb43b..f89fa1d49a 100644 --- a/backend/parsers/windmill-parser-wasm/Cargo.lock +++ b/backend/parsers/windmill-parser-wasm/Cargo.lock @@ -2,21 +2,22 @@ # It is not intended for manual editing. version = 4 -[[package]] -name = "addr2line" -version = "0.25.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b5d307320b3181d6d7954e663bd7c774a838b8220fe0593c86d9fb09f498b4b" -dependencies = [ - "gimli", -] - [[package]] name = "adler2" version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common 0.1.7", + "generic-array", +] + [[package]] name = "aes" version = "0.7.5" @@ -24,11 +25,36 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e8b47f52ea9bae42228d07ec09eb676433d7c4ed1ebdf0f1d1c29ed446f1ab8" dependencies = [ "cfg-if", - "cipher", + "cipher 0.3.0", "cpufeatures 0.2.17", "opaque-debug", ] +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher 0.4.4", + "cpufeatures 0.2.17", +] + +[[package]] +name = "aes-gcm" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" +dependencies = [ + "aead", + "aes 0.8.4", + "cipher 0.4.4", + "ctr", + "ghash", + "subtle", +] + [[package]] name = "ahash" version = "0.7.8" @@ -254,6 +280,35 @@ version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" +[[package]] +name = "attribute-derive" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f9ef7a68684657ce9da341c934c73b63df7a3585a61e366d84c84ed5d3d167" +dependencies = [ + "attribute-derive-macro", + "manyhow", + "proc-macro2", + "quote", + "syn 3.0.7", +] + +[[package]] +name = "attribute-derive-macro" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300d426e5e73549125bb8e4649bdd5508f82c94ddf898fb0517246e71dfb8e98" +dependencies = [ + "collection_literals", + "interpolator", + "manyhow", + "proc-macro-utils", + "proc-macro2", + "quote", + "quote-use", + "syn 3.0.7", +] + [[package]] name = "autocfg" version = "1.5.0" @@ -360,21 +415,6 @@ dependencies = [ "tokio", ] -[[package]] -name = "backtrace" -version = "0.3.76" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bb531853791a215d7c62a30daf0dde835f381ab5de4589cfe7c649d2cbe92bd6" -dependencies = [ - "addr2line", - "cfg-if", - "libc", - "miniz_oxide", - "object", - "rustc-demangle", - "windows-link", -] - [[package]] name = "base64" version = "0.21.7" @@ -428,7 +468,7 @@ dependencies = [ "proc-macro2", "quote", "regex", - "rustc-hash 2.1.1", + "rustc-hash", "shlex", "syn 2.0.117", ] @@ -510,7 +550,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2cb03d1bed155d89dce0f845b7899b18a9a163e148fd004e1c28421a783e2d8e" dependencies = [ "block-padding", - "cipher", + "cipher 0.3.0", ] [[package]] @@ -620,6 +660,15 @@ version = "1.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2e93abca9e28e0a1b9877922aacb20576e05d4679ffa78c3d6dc22a26a216659" +[[package]] +name = "castaway" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a" +dependencies = [ + "rustversion", +] + [[package]] name = "cc" version = "1.2.56" @@ -670,6 +719,18 @@ dependencies = [ "rand_core 0.10.1", ] +[[package]] +name = "char_str" +version = "0.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cba78a5abb515610e10af297615434b019755b5d7be14e559ff5340dff50c4" +dependencies = [ + "castaway", + "get-size2", + "itoa", + "ryu", +] + [[package]] name = "chrono" version = "0.4.44" @@ -713,6 +774,16 @@ dependencies = [ "generic-array", ] +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common 0.1.7", + "inout", +] + [[package]] name = "clang-sys" version = "1.8.1" @@ -779,6 +850,12 @@ version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" +[[package]] +name = "collection_literals" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2550f75b8cfac212855f6b1885455df8eaee8fe8e246b647d69146142e016084" + [[package]] name = "colorchoice" version = "1.0.4" @@ -795,6 +872,19 @@ dependencies = [ "memchr", ] +[[package]] +name = "compact_str" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79fcda08c33bb58b97008b2cdada6622500e949e060f5913361763121abd2416" +dependencies = [ + "castaway", + "cfg-if", + "itoa", + "static_assertions", + "zmij", +] + [[package]] name = "compression-codecs" version = "0.4.37" @@ -1019,12 +1109,6 @@ dependencies = [ "winapi", ] -[[package]] -name = "crunchy" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" - [[package]] name = "crypto-common" version = "0.1.7" @@ -1032,6 +1116,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" dependencies = [ "generic-array", + "rand_core 0.6.4", "typenum", ] @@ -1044,6 +1129,15 @@ dependencies = [ "hybrid-array", ] +[[package]] +name = "ctr" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +dependencies = [ + "cipher 0.4.4", +] + [[package]] name = "ctutils" version = "0.4.2" @@ -1093,27 +1187,6 @@ dependencies = [ "powerfmt", ] -[[package]] -name = "derive_more" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a9b99b9cbbe49445b21764dc0625032a89b145a2642e67603e1c936f5458d05" -dependencies = [ - "derive_more-impl", -] - -[[package]] -name = "derive_more-impl" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb7330aeadfbe296029522e6c40f315320aba36fc43a5b3632f3795348f3bd22" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.117", - "unicode-xid", -] - [[package]] name = "des" version = "0.7.0" @@ -1121,7 +1194,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac41dd49fb554432020d52c875fc290e110113f864c6b1b525cd62c7e7747a5d" dependencies = [ "byteorder", - "cipher", + "cipher 0.3.0", "opaque-debug", ] @@ -1196,6 +1269,12 @@ version = "0.15.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" +[[package]] +name = "drop_bomb" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bda8e21c04aca2ae33ffc2fd8c23134f3cac46db123ba97bd9d3f3b8a4a85e1" + [[package]] name = "dunce" version = "1.0.5" @@ -1502,6 +1581,31 @@ dependencies = [ "version_check", ] +[[package]] +name = "get-size-derive2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28f0daa179069133df60523e0f59d0a6bd2d3db9ccae01b630896d269c4a802e" +dependencies = [ + "attribute-derive", + "quote", + "syn 3.0.7", +] + +[[package]] +name = "get-size2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "050a5d07359ebfac7f0b74916d94cfa30575e45fdc7e9bfbb0f76d5d4203325a" +dependencies = [ + "compact_str", + "get-size-derive2", + "hashbrown 0.17.1", + "ordermap", + "smallvec", + "thin-vec", +] + [[package]] name = "gethostname" version = "0.4.3" @@ -1563,10 +1667,14 @@ dependencies = [ ] [[package]] -name = "gimli" -version = "0.32.3" +name = "ghash" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7" +checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" +dependencies = [ + "opaque-debug", + "polyval", +] [[package]] name = "git-version" @@ -1686,6 +1794,12 @@ version = "0.16.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + [[package]] name = "hashlink" version = "0.10.0" @@ -1758,7 +1872,7 @@ dependencies = [ "hashbrown 0.14.5", "new_debug_unreachable", "once_cell", - "rustc-hash 2.1.1", + "rustc-hash", "triomphe", ] @@ -1870,7 +1984,7 @@ dependencies = [ "libc", "percent-encoding", "pin-project-lite", - "socket2 0.6.3", + "socket2", "system-configuration", "tokio", "tower-service", @@ -2012,16 +2126,31 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.13.0" +version = "2.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", - "hashbrown 0.16.1", + "hashbrown 0.17.1", "serde", "serde_core", ] +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + +[[package]] +name = "interpolator" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71dd52191aae121e8611f1e8dc3e324dd0dd1dee1e6dd91d10ee07a3cfb4d9d8" + [[package]] name = "inventory" version = "0.3.22" @@ -2031,17 +2160,6 @@ dependencies = [ "rustversion", ] -[[package]] -name = "io-uring" -version = "0.7.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4d09b98f7eace8982db770e4408e7470b028ce513ac28fecdc6bf4c30fe92b62" -dependencies = [ - "bitflags", - "cfg-if", - "libc", -] - [[package]] name = "ipnet" version = "2.12.0" @@ -2082,15 +2200,6 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" -[[package]] -name = "itertools" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57" -dependencies = [ - "either", -] - [[package]] name = "itertools" version = "0.13.0" @@ -2109,6 +2218,15 @@ dependencies = [ "either", ] +[[package]] +name = "itertools" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc" +dependencies = [ + "either", +] + [[package]] name = "itoa" version = "1.0.17" @@ -2212,12 +2330,6 @@ version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a4933f3f57a8e9d9da04db23fb153356ecaf00cbd14aee46279c33dc80925c37" -[[package]] -name = "lalrpop-util" -version = "0.20.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "507460a910eb7b32ee961886ff48539633b788a36b65692b95f225b844c82553" - [[package]] name = "lazy_static" version = "1.5.0" @@ -2376,7 +2488,7 @@ version = "3.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6c42f95f9d296f2dcb50665f507ed5a68a171453142663ce44d77a4eb217b053" dependencies = [ - "aes", + "aes 0.7.5", "base64 0.21.7", "block-modes", "crc-any", @@ -2388,61 +2500,26 @@ dependencies = [ ] [[package]] -name = "malachite" -version = "0.4.22" +name = "manyhow" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2fbdf9cb251732db30a7200ebb6ae5d22fe8e11397364416617d2c2cf0c51cb5" +checksum = "8c69ea6e469ca785c846b25dd69eac9e9c916b51d8ada1f212866787ee1da12d" dependencies = [ - "malachite-base", - "malachite-nz", - "malachite-q", + "manyhow-macros", + "proc-macro2", + "quote", + "syn 3.0.7", ] [[package]] -name = "malachite-base" -version = "0.4.22" +name = "manyhow-macros" +version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ea0ed76adf7defc1a92240b5c36d5368cfe9251640dcce5bd2d0b7c1fd87aeb" +checksum = "22fc5c1b2c4000056dae3619fea36e79ce79dabfee4907d2dcad6612b189e370" dependencies = [ - "hashbrown 0.14.5", - "itertools 0.11.0", - "libm", - "ryu", -] - -[[package]] -name = "malachite-bigint" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d149aaa2965d70381709d9df4c7ee1fc0de1c614a4efc2ee356f5e43d68749f8" -dependencies = [ - "derive_more", - "malachite", - "num-integer", - "num-traits", - "paste", -] - -[[package]] -name = "malachite-nz" -version = "0.4.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "34a79feebb2bc9aa7762047c8e5495269a367da6b5a90a99882a0aeeac1841f7" -dependencies = [ - "itertools 0.11.0", - "libm", - "malachite-base", -] - -[[package]] -name = "malachite-q" -version = "0.4.22" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50f235d5747b1256b47620f5640c2a17a88c7569eebdf27cd9cb130e1a619191" -dependencies = [ - "itertools 0.11.0", - "malachite-base", - "malachite-nz", + "proc-macro-utils", + "proc-macro2", + "quote", ] [[package]] @@ -2575,9 +2652,9 @@ dependencies = [ [[package]] name = "mio" -version = "1.1.1" +version = "1.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a69bcab0ad47271a0234d9422b131806bf3968021e5dc9328caf2d4cd58557fc" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" dependencies = [ "libc", "wasi 0.11.1+wasi-snapshot-preview1", @@ -2949,6 +3026,15 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" +[[package]] +name = "ordermap" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a756ddcdeb6c0efc8927bdf0ed112885815a35ba350472a467be5104f01ca1" +dependencies = [ + "indexmap", +] + [[package]] name = "owo-colors" version = "4.3.0" @@ -2984,12 +3070,6 @@ dependencies = [ "windows-link", ] -[[package]] -name = "paste" -version = "1.0.15" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" - [[package]] name = "pem" version = "3.0.6" @@ -3173,6 +3253,18 @@ version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" +[[package]] +name = "polyval" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "opaque-debug", + "universal-hash", +] + [[package]] name = "postgres-native-tls" version = "0.5.1" @@ -3286,6 +3378,17 @@ dependencies = [ "version_check", ] +[[package]] +name = "proc-macro-utils" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eeaf08a13de400bc215877b5bdc088f241b12eb42f0a548d3390dc1c56bb7071" +dependencies = [ + "proc-macro2", + "quote", + "smallvec", +] + [[package]] name = "proc-macro2" version = "1.0.106" @@ -3401,9 +3504,9 @@ dependencies = [ "pin-project-lite", "quinn-proto", "quinn-udp", - "rustc-hash 2.1.1", + "rustc-hash", "rustls", - "socket2 0.6.3", + "socket2", "thiserror 2.0.18", "tokio", "tracing", @@ -3422,7 +3525,7 @@ dependencies = [ "lru-slab", "rand 0.9.5", "ring", - "rustc-hash 2.1.1", + "rustc-hash", "rustls", "rustls-pki-types", "slab", @@ -3441,7 +3544,7 @@ dependencies = [ "cfg_aliases", "libc", "once_cell", - "socket2 0.6.3", + "socket2", "tracing", "windows-sys 0.60.2", ] @@ -3455,6 +3558,28 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "quote-use" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48356e493823dc3c1d7e9fc7b3ff204ecec48afbdd718fc4134091b88eb63f3d" +dependencies = [ + "quote", + "quote-use-macros", +] + +[[package]] +name = "quote-use-macros" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cf1c5de6a7cc231c71e03c77aa4c7019097859ea7029156b54d2894a8430704" +dependencies = [ + "proc-macro-utils", + "proc-macro2", + "quote", + "syn 3.0.7", +] + [[package]] name = "r-efi" version = "5.3.0" @@ -3835,6 +3960,106 @@ dependencies = [ "zeroize", ] +[[package]] +name = "ruff_python_ast" +version = "0.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15434b06df7d930fad2818639a4e0fec4af9c770121c45a96b72da7feaae9ead" +dependencies = [ + "aho-corasick", + "arrayvec", + "bitflags", + "char_str", + "compact_str", + "get-size2", + "is-macro", + "memchr", + "ruff_python_trivia", + "ruff_source_file", + "ruff_text_size", + "rustc-hash", + "thin-vec", + "thiserror 2.0.18", +] + +[[package]] +name = "ruff_python_parser" +version = "0.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37a22811d752aa9e255d7dd72524d14352cf9bc654ef79b399bf1eeeb6640fbb" +dependencies = [ + "bitflags", + "bstr", + "drop_bomb", + "get-size2", + "hashbrown 0.17.1", + "memchr", + "ruff_python_ast", + "ruff_python_trivia", + "ruff_text_size", + "ruff_unicode_names2", + "rustc-hash", + "stacker", + "static_assertions", + "thin-vec", + "unicode-ident", + "unicode-normalization", +] + +[[package]] +name = "ruff_python_trivia" +version = "0.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0322a5059fe0feb2e010ca6f31c24ac289f6b7e9e38359539491b10c57f1c5bc" +dependencies = [ + "itertools 0.15.0", + "memchr", + "ruff_source_file", + "ruff_text_size", + "rustc-hash", + "unicode-ident", + "unicode-normalization", +] + +[[package]] +name = "ruff_source_file" +version = "0.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6ae809a289b5c791f82aa45df33f2a92323e7a1c1d265c10e9ac884027a2e43" +dependencies = [ + "memchr", + "ruff_text_size", +] + +[[package]] +name = "ruff_text_size" +version = "0.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "daf6344d6915ced9316312c1ee3f24c4300c54295bc4c3b8f4e95b633ae5443b" +dependencies = [ + "get-size2", +] + +[[package]] +name = "ruff_unicode_names2" +version = "0.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13418b8fd029d597e35dedc36e91f47122d26075e4c86557574d9441753fb375" +dependencies = [ + "phf 0.11.3", + "ruff_unicode_names2_generator", +] + +[[package]] +name = "ruff_unicode_names2_generator" +version = "0.0.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37fd82af49d5685d9054e68185987acaaf62542f671b6df8935155664876bc39" +dependencies = [ + "phf_codegen", + "rand 0.8.6", +] + [[package]] name = "rust_decimal" version = "1.40.0" @@ -3851,18 +4076,6 @@ dependencies = [ "serde_json", ] -[[package]] -name = "rustc-demangle" -version = "0.1.27" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b50b8869d9fc858ce7266cce0194bd74df58b9d0e3f6df3a9fc8eb470d95c09d" - -[[package]] -name = "rustc-hash" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" - [[package]] name = "rustc-hash" version = "2.1.1" @@ -3971,63 +4184,6 @@ dependencies = [ "untrusted 0.9.0", ] -[[package]] -name = "rustpython-ast" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cdaf8ee5c1473b993b398c174641d3aa9da847af36e8d5eb8291930b72f31a5" -dependencies = [ - "is-macro", - "malachite-bigint", - "rustpython-parser-core", - "static_assertions", -] - -[[package]] -name = "rustpython-parser" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "868f724daac0caf9bd36d38caf45819905193a901e8f1c983345a68e18fb2abb" -dependencies = [ - "anyhow", - "is-macro", - "itertools 0.11.0", - "lalrpop-util", - "log", - "malachite-bigint", - "num-traits", - "phf 0.11.3", - "phf_codegen", - "rustc-hash 1.1.0", - "rustpython-ast", - "rustpython-parser-core", - "tiny-keccak", - "unic-emoji-char", - "unic-ucd-ident", - "unicode_names2", -] - -[[package]] -name = "rustpython-parser-core" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4b6c12fa273825edc7bccd9a734f0ad5ba4b8a2f4da5ff7efe946f066d0f4ad" -dependencies = [ - "is-macro", - "memchr", - "rustpython-parser-vendored", -] - -[[package]] -name = "rustpython-parser-vendored" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04fcea49a4630a3a5d940f4d514dc4f575ed63c14c3e3ed07146634aed7f67a6" -dependencies = [ - "memchr", - "once_cell", -] - [[package]] name = "rustversion" version = "1.0.22" @@ -4040,6 +4196,12 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" +[[package]] +name = "ryu-js" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04d056b875a9d2e6cb9a61d127afee9ac5999b9f87bcb32079d1318e505be714" + [[package]] name = "same-file" version = "1.0.6" @@ -4409,16 +4571,6 @@ dependencies = [ "version_check", ] -[[package]] -name = "socket2" -version = "0.5.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678" -dependencies = [ - "libc", - "windows-sys 0.52.0", -] - [[package]] name = "socket2" version = "0.6.3" @@ -4680,15 +4832,15 @@ checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" [[package]] name = "stacker" -version = "0.1.23" +version = "0.1.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08d74a23609d509411d10e2176dc2a4346e3b4aea2e7b1869f19fdedbc71c013" +checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967" dependencies = [ "cc", "cfg-if", "libc", "psm", - "windows-sys 0.59.0", + "windows-sys 0.61.2", ] [[package]] @@ -4830,7 +4982,7 @@ dependencies = [ "new_debug_unreachable", "num-bigint", "once_cell", - "rustc-hash 2.1.1", + "rustc-hash", "serde", "siphasher 0.3.11", "swc_atoms", @@ -4852,7 +5004,7 @@ dependencies = [ "num-bigint", "once_cell", "phf 0.11.3", - "rustc-hash 2.1.1", + "rustc-hash", "string_enum", "swc_atoms", "swc_common", @@ -4871,7 +5023,7 @@ dependencies = [ "either", "num-bigint", "phf 0.11.3", - "rustc-hash 2.1.1", + "rustc-hash", "seq-macro", "serde", "smallvec", @@ -4974,6 +5126,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "syn" +version = "3.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d62a2e0561533f2ca2561d0cf27fd9fedb640a1bf2616ff5d5c80d99017faadc" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "sync_wrapper" version = "1.0.2" @@ -5102,6 +5265,12 @@ dependencies = [ "unicode-width 0.2.2", ] +[[package]] +name = "thin-vec" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6a4b9ba8738cb4a4f399d37e266becfd475e75eb73425b87a05a2f2039ba63e" + [[package]] name = "thiserror" version = "1.0.69" @@ -5193,15 +5362,6 @@ dependencies = [ "time-core", ] -[[package]] -name = "tiny-keccak" -version = "2.0.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237" -dependencies = [ - "crunchy", -] - [[package]] name = "tinystr" version = "0.8.2" @@ -5229,34 +5389,31 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.46.1" +version = "1.53.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0cc3a2344dafbe23a245241fe8b09735b521110d30fcefbbd5feb1797ca35d17" +checksum = "e95f91fcc7a621e8b030f6aa23c71fe9838ae2fb4d8118b75602a328f5144044" dependencies = [ - "backtrace", "bytes", - "io-uring", "libc", "mio", "parking_lot", "pin-project-lite", "signal-hook-registry", - "slab", - "socket2 0.5.10", + "socket2", "tokio-macros", "tracing", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] name = "tokio-macros" -version = "2.5.0" +version = "2.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e06d43f1345a3bcd39f6a56dbb7dcab2ba47e68e8ac134855e7e2bdbaf8cab8" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.7", ] [[package]] @@ -5289,7 +5446,7 @@ dependencies = [ "postgres-protocol", "postgres-types", "rand 0.10.1", - "socket2 0.6.3", + "socket2", "tokio", "tokio-util", "whoami 2.1.0", @@ -5325,6 +5482,7 @@ dependencies = [ "bytes", "futures-core", "futures-sink", + "futures-util", "pin-project-lite", "tokio", ] @@ -5663,17 +5821,6 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "80d7ff825a6a654ee85a63e80f92f054f904f21e7d12da4e22f9834a4aaa35bc" -[[package]] -name = "unic-emoji-char" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0b07221e68897210270a38bde4babb655869637af0f69407f96053a34f76494d" -dependencies = [ - "unic-char-property", - "unic-char-range", - "unic-ucd-version", -] - [[package]] name = "unic-ucd-category" version = "0.9.0" @@ -5686,17 +5833,6 @@ dependencies = [ "unic-ucd-version", ] -[[package]] -name = "unic-ucd-ident" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e230a37c0381caa9219d67cf063aa3a375ffed5bf541a452db16e744bdab6987" -dependencies = [ - "unic-char-property", - "unic-char-range", - "unic-ucd-version", -] - [[package]] name = "unic-ucd-version" version = "0.9.0" @@ -5776,25 +5912,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" [[package]] -name = "unicode_names2" -version = "1.3.0" +name = "universal-hash" +version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1673eca9782c84de5f81b82e4109dcfb3611c8ba0d52930ec4a9478f547b2dd" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" dependencies = [ - "phf 0.11.3", - "unicode_names2_generator", -] - -[[package]] -name = "unicode_names2_generator" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b91e5b84611016120197efd7dc93ef76774f4e084cd73c9fb3ea4a86c570c56e" -dependencies = [ - "getopts", - "log", - "phf_codegen", - "rand 0.8.6", + "crypto-common 0.1.7", + "subtle", ] [[package]] @@ -6216,8 +6340,9 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "windmill-common" -version = "1.827.0" +version = "1.841.0" dependencies = [ + "aes-gcm", "aho-corasick", "anyhow", "arc-swap", @@ -6245,6 +6370,7 @@ dependencies = [ "git-version", "globset", "hex", + "hkdf", "hmac 0.12.1", "hyper", "indexmap", @@ -6260,12 +6386,14 @@ dependencies = [ "pin-project-lite", "pkcs1", "postgres-native-tls", + "postgres-protocol", "quick_cache", "rand 0.9.5", "regex", "reqwest", "reqwest-middleware", "reqwest-retry", + "ryu-js", "semver", "serde", "serde_json", @@ -6302,7 +6430,7 @@ dependencies = [ [[package]] name = "windmill-macros" -version = "1.827.0" +version = "1.841.0" dependencies = [ "proc-macro2", "quote", @@ -6314,7 +6442,7 @@ dependencies = [ [[package]] name = "windmill-parser" -version = "1.827.0" +version = "1.841.0" dependencies = [ "convert_case", "serde", @@ -6323,7 +6451,7 @@ dependencies = [ [[package]] name = "windmill-parser-bash" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "lazy_static", @@ -6335,7 +6463,7 @@ dependencies = [ [[package]] name = "windmill-parser-csharp" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "serde_json", @@ -6347,7 +6475,7 @@ dependencies = [ [[package]] name = "windmill-parser-go" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "gosyn", @@ -6359,7 +6487,7 @@ dependencies = [ [[package]] name = "windmill-parser-graphql" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "lazy_static", @@ -6371,7 +6499,7 @@ dependencies = [ [[package]] name = "windmill-parser-java" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "serde_json", @@ -6383,7 +6511,7 @@ dependencies = [ [[package]] name = "windmill-parser-nu" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "nu-parser", @@ -6394,7 +6522,7 @@ dependencies = [ [[package]] name = "windmill-parser-php" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "itertools 0.14.0", @@ -6405,30 +6533,30 @@ dependencies = [ [[package]] name = "windmill-parser-py" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "itertools 0.14.0", - "rustpython-ast", - "rustpython-parser", + "ruff_python_ast", + "ruff_python_parser", "serde_json", "windmill-parser", ] [[package]] name = "windmill-parser-py-asset" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", - "rustpython-ast", - "rustpython-parser", + "ruff_python_ast", + "ruff_python_parser", "windmill-parser", "windmill-parser-sql-asset", ] [[package]] name = "windmill-parser-py-imports" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "async-recursion", @@ -6438,7 +6566,8 @@ dependencies = [ "phf 0.11.3", "regex", "regex-lite", - "rustpython-parser", + "ruff_python_ast", + "ruff_python_parser", "serde", "serde_json", "sqlx", @@ -6450,7 +6579,7 @@ dependencies = [ [[package]] name = "windmill-parser-r" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "serde_json", @@ -6462,7 +6591,7 @@ dependencies = [ [[package]] name = "windmill-parser-ruby" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "lazy_static", @@ -6476,7 +6605,7 @@ dependencies = [ [[package]] name = "windmill-parser-rust" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "convert_case", @@ -6493,7 +6622,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "lazy_static", @@ -6506,7 +6635,7 @@ dependencies = [ [[package]] name = "windmill-parser-sql-asset" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "serde", @@ -6518,7 +6647,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "lazy_static", @@ -6536,7 +6665,7 @@ dependencies = [ [[package]] name = "windmill-parser-ts-asset" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "serde-wasm-bindgen", @@ -6552,11 +6681,12 @@ dependencies = [ [[package]] name = "windmill-parser-wac" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", - "rustpython-ast", - "rustpython-parser", + "ruff_python_ast", + "ruff_python_parser", + "ruff_text_size", "serde", "serde_json", "sha2 0.10.9", @@ -6568,7 +6698,7 @@ dependencies = [ [[package]] name = "windmill-parser-wasm" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "getrandom 0.2.17", @@ -6600,7 +6730,7 @@ dependencies = [ [[package]] name = "windmill-parser-yaml" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "lazy_static", @@ -6614,7 +6744,7 @@ dependencies = [ [[package]] name = "windmill-types" -version = "1.827.0" +version = "1.841.0" dependencies = [ "anyhow", "bitflags", diff --git a/backend/parsers/windmill-parser-wasm/Cargo.toml b/backend/parsers/windmill-parser-wasm/Cargo.toml index 9ac7f81c7f..d6c0389840 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.827.0" +version = "1.841.0" edition = "2021" authors = ["Ruben Fiszel "] diff --git a/backend/parsers/windmill-parser-yaml/Cargo.toml b/backend/parsers/windmill-parser-yaml/Cargo.toml index eb2f16fccc..5c3b3e2760 100644 --- a/backend/parsers/windmill-parser-yaml/Cargo.toml +++ b/backend/parsers/windmill-parser-yaml/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_parser_yaml" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [dependencies] yaml-rust.workspace = true diff --git a/backend/parsers/windmill-parser/Cargo.toml b/backend/parsers/windmill-parser/Cargo.toml index 97b6c6da58..842a94d917 100644 --- a/backend/parsers/windmill-parser/Cargo.toml +++ b/backend/parsers/windmill-parser/Cargo.toml @@ -7,6 +7,8 @@ authors.workspace = true [lib] name = "windmill_parser" path = "./src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [dependencies] serde = { version = "1.0", features = ["derive"] } diff --git a/backend/parsers/windmill-sql-datatype-parser-wasm/Cargo.toml b/backend/parsers/windmill-sql-datatype-parser-wasm/Cargo.toml index 7d66d56ade..e4d67e84a7 100644 --- a/backend/parsers/windmill-sql-datatype-parser-wasm/Cargo.toml +++ b/backend/parsers/windmill-sql-datatype-parser-wasm/Cargo.toml @@ -9,6 +9,8 @@ authors.workspace = true crate-type = ["cdylib"] name = "windmill_sql_datatype_parser_wasm" path = "./src/lib.rs" +# src/ has no unit tests: remove this line before adding one, or cargo test never runs it. +test = false [dev-dependencies] wasm-bindgen-test.workspace = true diff --git a/backend/src/db_connect.rs b/backend/src/db_connect.rs index d4dee19f82..ab12ae6f6e 100644 --- a/backend/src/db_connect.rs +++ b/backend/src/db_connect.rs @@ -153,6 +153,9 @@ pub async fn connect( pool_options = pool_options.idle_timeout(Duration::from_secs(60)); } pool_options + .before_acquire(|_, meta| { + Box::pin(async move { Ok(!windmill_common::db::connection_is_retired(meta.age)) }) + }) .after_connect(move |conn, _| { if worker_mode { Box::pin(async move { diff --git a/backend/src/main.rs b/backend/src/main.rs index 81104d6764..ef9961ba57 100644 --- a/backend/src/main.rs +++ b/backend/src/main.rs @@ -44,12 +44,13 @@ use windmill_common::{ CRITICAL_ALERTS_ON_TOKEN_EXPIRY_SETTING, CRITICAL_ALERT_MUTE_UI_SETTING, CRITICAL_ALERT_MUTE_ZOMBIE_JOB_RESTART_SETTING, CRITICAL_ERROR_CHANNELS_SETTING, CUSTOM_TAGS_SETTING, DEFAULT_TAGS_PER_WORKSPACE_SETTING, DEFAULT_TAGS_WORKSPACES_SETTING, - DEPENDENCY_JOB_TAG_SETTING, DISABLE_PASSWORD_LOGIN_SETTING, EMAIL_DOMAIN_SETTING, - ENV_SETTINGS, EXPOSE_DEBUG_METRICS_SETTING, EXPOSE_METRICS_SETTING, - EXTRA_PIP_INDEX_URL_SETTING, FORK_WORKSPACE_TAG_APPEND_FORK_SUFFIX_SETTING, - HTTP_ROUTE_DEFAULT_ALLOWED_ORIGINS_SETTING, HTTP_ROUTE_WORKSPACED_ROUTE_SETTING, - HUB_API_SECRET_SETTING, HUB_BASE_URL_SETTING, INDEXER_SETTING, - INSTANCE_EVENTS_WEBHOOK_SETTING, INSTANCE_PYTHON_VERSION_SETTING, + DEPENDENCY_JOB_TAG_SETTING, DEV_WORKSPACE_ISOLATION_SETTING, + DEV_WORKSPACE_ISOLATION_SKIP_NON_DEV_FORKS_SETTING, DEV_WORKSPACE_TAG_SUFFIX_SETTING, + DISABLE_PASSWORD_LOGIN_SETTING, EMAIL_DOMAIN_SETTING, ENV_SETTINGS, + EXPOSE_DEBUG_METRICS_SETTING, EXPOSE_METRICS_SETTING, EXTRA_PIP_INDEX_URL_SETTING, + FORK_WORKSPACE_TAG_APPEND_FORK_SUFFIX_SETTING, HTTP_ROUTE_DEFAULT_ALLOWED_ORIGINS_SETTING, + HTTP_ROUTE_WORKSPACED_ROUTE_SETTING, HUB_API_SECRET_SETTING, HUB_BASE_URL_SETTING, + INDEXER_SETTING, INSTANCE_EVENTS_WEBHOOK_SETTING, INSTANCE_PYTHON_VERSION_SETTING, JOB_DEFAULT_TIMEOUT_SECS_SETTING, JOB_ISOLATION_SETTING, JWT_SECRET_SETTING, KEEP_JOB_DIR_SETTING, LICENSE_KEY_SETTING, MAVEN_REPOS_SETTING, MAVEN_SETTINGS_XML_SETTING, MCP_DISABLE_TOKEN_QUERY_PARAM_SETTING, MONITOR_LOGS_ON_OBJECT_STORE_SETTING, @@ -63,12 +64,14 @@ use windmill_common::{ SANDBOX_IMAGE_CACHE_MAX_MB_SETTING, SANDBOX_IMAGE_DEFAULT_REGISTRY_SETTING, SANDBOX_IMAGE_MAX_SIZE_MB_SETTING, SANDBOX_IMAGE_PULL_POLICY_SETTING, SANDBOX_REGISTRY_AUTH_SETTING, SCIM_TOKEN_SETTING, SERVICE_LOG_RETENTION_SECS_SETTING, - SMTP_SETTING, STORE_AUDIT_LOGS_S3_SETTING, TEAMS_SETTING, TIMEOUT_WAIT_RESULT_SETTING, - UV_EXCLUDE_NEWER_SETTING, UV_INDEX_STRATEGY_SETTING, UV_PYTHON_INSTALL_MIRROR_SETTING, + SMTP_SETTING, STORE_AUDIT_LOGS_S3_SETTING, SYNC_HUB_RESOURCE_TYPES_DAILY_SETTING, + TEAMS_SETTING, TIMEOUT_WAIT_RESULT_SETTING, UV_EXCLUDE_NEWER_SETTING, + UV_INDEX_STRATEGY_SETTING, UV_PYTHON_INSTALL_MIRROR_SETTING, WORKSPACE_FAIRNESS_DURATION_SECS_SETTING, WORKSPACE_FAIRNESS_ENABLED_SETTING, WORKSPACE_FAIRNESS_MAX_PERCENT_SETTING, WORKSPACE_FAIRNESS_MIN_TOTAL_SETTING, WORKSPACE_MAX_QUEUED_JOBS_SETTING, WORKSPACE_REGISTRIES_SETTING, }, + hub_resource_types, scripts::ScriptLang, stats_oss::schedule_stats, triggers::TriggerKind, @@ -121,12 +124,15 @@ use windmill_worker::{ BUN_BUNDLE_CACHE_DIR, BUN_CACHE_DIR, CSHARP_CACHE_DIR, DENO_CACHE_DIR, DENO_CACHE_DIR_DEPS, DENO_CACHE_DIR_NPM, GO_BIN_CACHE_DIR, GO_CACHE_DIR, JAVA_CACHE_DIR, NU_CACHE_DIR, POWERSHELL_CACHE_DIR, PY310_CACHE_DIR, PY311_CACHE_DIR, PY312_CACHE_DIR, PY313_CACHE_DIR, - RUBY_CACHE_DIR, RUST_CACHE_DIR, R_CACHE_DIR, TAR_JAVA_CACHE_DIR, UV_CACHE_DIR, + PY314_CACHE_DIR, PY315_CACHE_DIR, RUBY_CACHE_DIR, RUST_CACHE_DIR, R_CACHE_DIR, + TAR_JAVA_CACHE_DIR, UV_CACHE_DIR, }; use crate::monitor::{ initial_load, load_concurrency_key_max_queued, load_dependency_job_tag, - load_disable_password_login, load_fork_workspace_tag_append_fork_suffix, load_keep_job_dir, + load_dev_workspace_isolation, load_dev_workspace_isolation_skip_non_dev_forks, + load_dev_workspace_tag_suffix, load_disable_password_login, + load_fork_workspace_tag_append_fork_suffix, load_keep_job_dir, load_mcp_disable_token_query_param, load_metrics_debug_enabled, load_preview_tags_override, load_require_preexisting_user, load_retention_period_overrides, load_tag_per_workspace_enabled, load_tag_per_workspace_workspaces, load_workspace_fairness_duration_secs, @@ -401,111 +407,16 @@ async fn cache_hub_scripts(file_path: Option) -> anyhow::Result<()> { Ok(()) } -/// Raw resource type from hub API (schema is a JSON string) -#[derive(serde::Deserialize)] -struct HubResourceTypeRaw { - pub id: i64, - pub name: String, - pub schema: Option, - pub app: String, - pub description: Option, - /// Absent from hubs predating the column, and from caches written before it. - #[serde(default)] - pub format_extension: Option, - /// Doubly optional, so a hub predating the field (no key) is told apart from a type the - /// hub leaves unnamed (null). - #[serde( - default, - deserialize_with = "windmill_common::more_serde::double_option" - )] - pub display_name: Option>, -} - -/// Processed resource type with parsed schema -#[derive(serde::Deserialize, serde::Serialize, Clone)] -pub struct HubResourceType { - pub id: i64, - pub name: String, - pub schema: Option, - pub app: String, - pub description: Option, - /// Doubly optional on purpose. A cache written before this column has no key at - /// all (`None`) and must leave the stored extension alone; one written since - /// always writes the key, so an explicit null (`Some(None)`) is the hub genuinely - /// dropping it and must clear. A single `Option` conflates the two, and picking - /// either meaning breaks the other — as does plain serde, which folds `null` - /// into the outer `None`, hence the wrapping deserializer. - #[serde( - default, - deserialize_with = "windmill_common::more_serde::double_option", - skip_serializing_if = "Option::is_none" - )] - pub format_extension: Option>, - /// Doubly optional like `format_extension`: a cache written before the field leaves the - /// stored name alone, while a null from the hub clears it. - #[serde( - default, - deserialize_with = "windmill_common::more_serde::double_option", - skip_serializing_if = "Option::is_none" - )] - pub display_name: Option>, -} - -const HUB_RT_CACHE_FILE: &str = "resource_types.json"; - async fn cache_hub_resource_types() -> anyhow::Result<()> { println!("Caching resource types from hub..."); - let response = HTTP_CLIENT - .get(format!("{}/resource_types/list", DEFAULT_HUB_BASE_URL)) - .header("Accept", "application/json") - .send() - .await - .with_context(|| "Failed to fetch resource types from hub")?; - - if !response.status().is_success() { - anyhow::bail!( - "Failed to fetch resource types from hub: {}", - response.status() - ); - } - - let raw_types: Vec = response - .json::>() - .await - .with_context(|| "Failed to parse resource types from hub")?; - - // Parse schema strings into JSON values - let resource_types: Vec = raw_types - .into_iter() - .filter_map(|rt| { - let schema = match rt.schema { - Some(s) => match serde_json::from_str(&s) { - Ok(v) => Some(v), - Err(e) => { - println!("Warning: failed to parse schema for {}: {}", rt.name, e); - return None; - } - }, - None => None, - }; - Some(HubResourceType { - id: rt.id, - name: rt.name, - schema, - app: rt.app, - description: rt.description, - format_extension: Some(rt.format_extension), - display_name: rt.display_name, - }) - }) - .collect(); + let resource_types = hub_resource_types::fetch(DEFAULT_HUB_BASE_URL, None, None).await?; println!("Fetched {} resource types from hub", resource_types.len()); create_dir_all(&*HUB_RT_CACHE_DIR)?; - let cache_path = format!("{}/{}", *HUB_RT_CACHE_DIR, HUB_RT_CACHE_FILE); + let cache_path = hub_resource_types::cache_path(); let content = serde_json::to_string_pretty(&resource_types) .with_context(|| "Failed to serialize resource types")?; @@ -516,147 +427,6 @@ async fn cache_hub_resource_types() -> anyhow::Result<()> { Ok(()) } -pub async fn sync_cached_resource_types(db: &sqlx::Pool) -> anyhow::Result<()> { - let cache_path = format!("{}/{}", *HUB_RT_CACHE_DIR, HUB_RT_CACHE_FILE); - - if tokio::fs::metadata(&cache_path).await.is_err() { - tracing::info!( - "No cached resource types found at {}, skipping sync", - cache_path - ); - return Ok(()); - } - - tracing::info!("Syncing cached resource types to admins workspace..."); - - let content = tokio::fs::read_to_string(&cache_path) - .await - .with_context(|| format!("Failed to read cache file from {}", cache_path))?; - - let cached_types: Vec = - serde_json::from_str(&content).with_context(|| "Failed to parse cached resource types")?; - - tracing::info!("Found {} cached resource types", cached_types.len()); - - // Get existing resource types in admins workspace. `format_extension` is part of - // the comparison below, so a type whose only change is gaining or losing it is - // not mistaken for unchanged; `is_fileset` decides whether it may take one. - let existing_types: Vec<( - String, - Option, - Option, - Option, - bool, - Option, - )> = sqlx::query_as( - "SELECT name, schema, description, format_extension, is_fileset, display_name FROM resource_type WHERE workspace_id = 'admins'", - ) - .fetch_all(db) - .await - .with_context(|| "Failed to fetch existing resource types")?; - - let existing_map: std::collections::HashMap< - String, - ( - Option, - Option, - Option, - bool, - Option, - ), - > = existing_types - .into_iter() - .map( - |(name, schema, desc, format_extension, is_fileset, display_name)| { - ( - name, - (schema, desc, format_extension, is_fileset, display_name), - ) - }, - ) - .collect(); - - let mut synced_count = 0; - let mut skipped_count = 0; - - for rt in cached_types { - let existing = existing_map.get(&rt.name); - let is_fileset = existing.map(|(_, _, _, f, _)| *f).unwrap_or(false); - let stored_extension = existing.and_then(|(_, _, e, _, _)| e.clone()); - let stored_display_name = existing.and_then(|(_, _, _, _, n)| n.clone()); - // A fileset is a set of files, so it cannot also be one file. Create, update - // and the manual sync all reject the pair; this writer would otherwise - // persist it onto a same-named local fileset. - // - // A cache with no key at all leaves the stored value alone, so the target is - // what is already there — which is also what makes the comparison below - // agree with the write instead of re-upserting the row on every boot. - let format_extension = if is_fileset { - None - } else { - match &rt.format_extension { - Some(from_cache) => from_cache.clone(), - None => stored_extension.clone(), - } - }; - // No key in the cache leaves the stored name alone, as for the extension. So does a name - // too long for the column: one bad entry must not fail the upsert and end the sync. - let display_name = match &rt.display_name { - Some(Some(name)) if name.chars().count() > 100 => { - tracing::warn!( - "Ignoring the display_name of resource type {}: longer than 100 characters", - rt.name - ); - stored_display_name.clone() - } - Some(from_cache) => from_cache.clone(), - None => stored_display_name.clone(), - }; - - if let Some((existing_schema, existing_desc, _, _, _)) = existing { - if existing_schema == &rt.schema - && existing_desc == &rt.description - && stored_extension == format_extension - && stored_display_name == display_name - { - skipped_count += 1; - continue; - } - } - - // Insert or update resource type - sqlx::query( - // `format_extension` is resolved above rather than coalesced here: a - // COALESCE could never clear one, so a hub that dropped an extension - // would leave the stale value behind forever. - "INSERT INTO resource_type (workspace_id, name, schema, description, format_extension, display_name, edited_at) - VALUES ('admins', $1, $2, $3, $4, $5, now()) - ON CONFLICT (workspace_id, name) DO UPDATE - SET schema = EXCLUDED.schema, description = EXCLUDED.description, - format_extension = EXCLUDED.format_extension, - display_name = EXCLUDED.display_name, edited_at = now()", - ) - .bind(&rt.name) - .bind(&rt.schema) - .bind(&rt.description) - .bind(&format_extension) - .bind(&display_name) - .execute(db) - .await - .with_context(|| format!("Failed to upsert resource type {}", rt.name))?; - - synced_count += 1; - } - - tracing::info!( - "Synced {} resource types to admins workspace ({} skipped as unchanged)", - synced_count, - skipped_count - ); - - Ok(()) -} - fn print_help() { println!("Windmill - a fast, open-source workflow engine and job runner."); println!(); @@ -670,6 +440,8 @@ fn print_help() { println!(" cache-rt Pre-cache hub resource types"); println!(" sync-config Sync instance config from a YAML file to the database"); println!(" operator Run the Kubernetes operator (watches a ConfigMap)"); + #[cfg(all(feature = "enterprise", feature = "openidconnect", feature = "private"))] + println!(" oidc-signer (ee) Check an external OIDC signer, or run a file-backed one for tests"); println!(); println!("Environment variables (name = default):"); println!(" DATABASE_URL = The Postgres database url."); @@ -696,7 +468,7 @@ fn print_help() { println!(" LICENSE_KEY = None (EE only) Enterprise license key (workers require valid key)"); println!(" RUN_UPDATE_CA_CERTIFICATE_AT_START = false Run system CA update at startup"); println!(" RUN_UPDATE_CA_CERTIFICATE_PATH = /usr/sbin/update-ca-certificates Path to CA update tool"); - println!(" SYNC_CACHED_RT = false Sync cached resource types to admins workspace on server start"); + println!(" SYNC_CACHED_RT = false Sync the image's cached resource types to the admins workspace on server start"); println!(" HUB_BASE_URL = https://hub.windmill.dev Hub to fetch scripts from in `cache` mode (server/worker use the DB setting instead)"); println!(); println!("Notes:"); @@ -704,6 +476,38 @@ fn print_help() { println!("- At startup, Windmill logs currently set configuration keys for visibility."); } +async fn otel_environment(conn: &Connection) -> String { + if let Ok(environment) = std::env::var("OTEL_ENVIRONMENT") { + environment + } else { + load_base_url(conn) + .await + .unwrap_or_else(|_| "local".to_string()) + .trim_start_matches("https://") + .trim_start_matches("http://") + .split(".") + .next() + .unwrap_or_else(|| "local") + .to_string() + } +} + +/// Tracing for a subcommand that writes instance config. It never runs the server startup +/// that loads the OTel settings, and its audit events are exported under them. +/// +/// The subscriber it installs depends on those settings, so `early_logs` is what prints +/// the events of connecting and loading them; it gives way once the real one is in. +async fn init_declarative_writer_tracing( + db: &windmill_common::DB, + service: &str, + early_logs: tracing::subscriber::DefaultGuard, +) { + load_otel(db).await; + let environment = otel_environment(&Connection::Sql(db.clone())).await; + drop(early_logs); + windmill_common::tracing_init::initialize_subcommand_tracing(service, &HOSTNAME, &environment); +} + async fn windmill_main() -> anyhow::Result<()> { let (killpill_tx, mut killpill_rx) = KillpillSender::new(2); let mut monitor_killpill_rx = killpill_tx.subscribe(); @@ -807,7 +611,6 @@ async fn windmill_main() -> anyhow::Result<()> { return Ok(()); } "sync-config" => { - tracing_subscriber::fmt::init(); let path = std::env::args().nth(2).unwrap_or_else(|| { eprintln!("Usage: windmill sync-config "); std::process::exit(1); @@ -821,15 +624,40 @@ async fn windmill_main() -> anyhow::Result<()> { windmill_common::instance_config::resolve_env_refs(&mut config.global_settings) .map_err(|var| anyhow::anyhow!("environment variable '{var}' not found"))?; + let early_logs = tracing::subscriber::set_default(tracing_subscriber::fmt().finish()); tracing::info!("Connecting to database..."); let db = crate::db_connect::initial_connection().await?; - config.sync_to_db(&db).await?; + init_declarative_writer_tracing(&db, "windmill-sync-config", early_logs).await; + + let author = windmill_audit::instance_config::declarative_sync_author(); + let synced = config + .sync_to_db( + &db, + &windmill_audit::instance_config::InstanceConfigAuditor { + db: &db, + author: &author, + source: Some( + windmill_audit::instance_config::DeclarativeSource::SyncConfig, + ), + }, + ) + .await; + // Also on failure: the settings written before it are already audited, and the + // process exits before the exporter's next scheduled batch. + windmill_common::otel_oss::flush_otel_logs().await; + synced?; tracing::info!("Synced instance config from {path}"); return Ok(()); } + #[cfg(all(feature = "enterprise", feature = "openidconnect", feature = "private"))] + "oidc-signer" => { + tracing_subscriber::fmt::init(); + windmill_api::oidc_signer_tools_ee::run_cli(std::env::args().skip(2).collect()).await?; + return Ok(()); + } #[cfg(feature = "operator")] "operator" => { - tracing_subscriber::fmt::init(); + let early_logs = tracing::subscriber::set_default(tracing_subscriber::fmt().finish()); tracing::info!("Starting Windmill Kubernetes operator..."); tracing::info!("Connecting to database..."); @@ -842,6 +670,7 @@ async fn windmill_main() -> anyhow::Result<()> { operator_killpill_rx, ) .await?; + init_declarative_writer_tracing(&db, "windmill-operator", early_logs).await; #[cfg(all(feature = "enterprise", feature = "private"))] tokio::spawn(async move { @@ -857,6 +686,29 @@ async fn windmill_main() -> anyhow::Result<()> { _ => {} } + // Before `num_workers`: it reads `WORKER_GROUP`, which an agent authenticating with a + // workload identity token only learns from the server. + let agent_setup = if mode == Mode::Agent { + let agent_config = match AgentConfig::from_env() { + Ok(config) => config, + Err(e) => { + eprintln!("{e}"); + std::process::exit(1); + } + }; + let suffix = resolve_worker_suffix(&hostname, 1)?; + if let Err(e) = agent_config.resolve_workload_identity(&suffix).await { + eprintln!( + "Agent worker could not authenticate with its workload identity token, check \ + AGENT_IDENTITY_TOKEN_FILE and BASE_INTERNAL_URL (the reason is in the server log): {e:#}" + ); + std::process::exit(1); + } + Some((agent_config, suffix)) + } else { + None + }; + #[allow(unused_mut)] let mut num_workers = if mode == Mode::Server || mode == Mode::Indexer || mode == Mode::MCP { 0 @@ -909,19 +761,11 @@ async fn windmill_main() -> anyhow::Result<()> { .and_then(|x| x.parse().ok()) .unwrap_or(IpAddr::from(default_bind_addr)); - let (conn, first_suffix, agent_config) = if mode == Mode::Agent { - let agent_config = match AgentConfig::from_env() { - Ok(config) => config, - Err(e) => { - tracing::error!("{e}"); - std::process::exit(1); - } - }; + let (conn, first_suffix, agent_config) = if let Some((agent_config, suffix)) = agent_setup { tracing::info!( "Creating http client for cluster using base internal url {}", agent_config.base_internal_url ); - let suffix = resolve_worker_suffix(&hostname, 1)?; ( Connection::Http(agent_config.build_http_client(&suffix)), Some(suffix), @@ -968,19 +812,7 @@ async fn windmill_main() -> anyhow::Result<()> { (Connection::Sql(db), None, None) }; - let environment = if let Ok(environment) = std::env::var("OTEL_ENVIRONMENT") { - environment - } else { - load_base_url(&conn) - .await - .unwrap_or_else(|_| "local".to_string()) - .trim_start_matches("https://") - .trim_start_matches("http://") - .split(".") - .next() - .unwrap_or_else(|| "local") - .to_string() - }; + let environment = otel_environment(&conn).await; let _guard = windmill_common::tracing_init::initialize_tracing(&hostname, &mode, &environment); @@ -1015,8 +847,10 @@ async fn windmill_main() -> anyhow::Result<()> { .map(|v| v.to_lowercase() == "true" || v == "1") .unwrap_or(false) { - if let Err(e) = sync_cached_resource_types(db).await { - tracing::warn!("Failed to sync cached resource types: {:#}", e); + match hub_resource_types::sync_from_image_cache(db).await { + Ok(Some(outcome)) => tracing::info!("{}", outcome.summary()), + Ok(None) => {} + Err(e) => tracing::warn!("Failed to sync cached resource types: {:#}", e), } } } @@ -1030,6 +864,8 @@ async fn windmill_main() -> anyhow::Result<()> { let worker_mode = num_workers > 0; if worker_mode { + windmill_common::worker::warn_secret_shaped_whitelist_envs(); + #[cfg(any(target_os = "linux"))] if let Err(e) = disable_oom_group() { tracing::warn!( @@ -1175,7 +1011,7 @@ Windmill Community Edition {GIT_VERSION} tracing::error!("Failed to reload license key: {err:#}"); if is_agent { tracing::error!( - "Agent worker cannot connect to server. Please check AGENT_TOKEN and BASE_INTERNAL_URL" + "Agent worker cannot connect to server. Please check AGENT_TOKEN (or AGENT_IDENTITY_TOKEN_FILE) and BASE_INTERNAL_URL" ); std::process::exit(1); } @@ -1234,6 +1070,11 @@ Windmill Community Edition {GIT_VERSION} // empty script cache, refilled from the database. windmill_common::cache::script::clear(); + // Before the first load: it can sign a token for instance object storage. + #[cfg(all(feature = "enterprise", feature = "openidconnect", feature = "private"))] + windmill_common::oidc_ee::init_oidc_signing(&conn, server_mode, killpill_rx.resubscribe()) + .await?; + initial_load( &conn, killpill_tx.clone(), @@ -1748,6 +1589,7 @@ Windmill Community Edition {GIT_VERSION} if server_mode { if let Some(db) = conn.as_sql() { schedule_stats(&db, &HTTP_CLIENT).await; + hub_resource_types::spawn_daily_sync(db.clone(), killpill_tx.subscribe()); } } @@ -2055,6 +1897,21 @@ async fn process_notify_event( tracing::error!("Error loading dependency job tag: {e:#}"); } } + DEV_WORKSPACE_ISOLATION_SETTING => { + if let Err(e) = load_dev_workspace_isolation(db).await { + tracing::error!("Error loading dev workspace isolation: {e:#}"); + } + } + DEV_WORKSPACE_ISOLATION_SKIP_NON_DEV_FORKS_SETTING => { + if let Err(e) = load_dev_workspace_isolation_skip_non_dev_forks(db).await { + tracing::error!("Error loading dev workspace isolation of forks: {e:#}"); + } + } + DEV_WORKSPACE_TAG_SUFFIX_SETTING => match load_dev_workspace_tag_suffix(db).await { + Ok(true) if worker_mode => reload_worker_config(db, tx.clone(), true).await, + Ok(_) => (), + Err(e) => tracing::error!("Error loading dev workspace tag suffix: {e:#}"), + }, WORKSPACE_FAIRNESS_ENABLED_SETTING => { if let Err(e) = load_workspace_fairness_enabled(db).await { tracing::error!("Error loading workspace fairness enabled: {e:#}"); @@ -2322,6 +2179,12 @@ async fn process_notify_event( RESTART_COORDINATION_SETTING => { // Internal coordination key for staggered restarts, no action needed } + SYNC_HUB_RESOURCE_TYPES_DAILY_SETTING => { + // Read by the daily resource type sync each time it runs + } + "oidc_external_signer" => { + // Written by servers that sign with an external signer, read when signing + } "plain_emails_telemetry" => { let enabled = sqlx::query_scalar!( "SELECT value FROM global_settings WHERE name = 'plain_emails_telemetry'" @@ -2407,6 +2270,8 @@ pub async fn run_workers( &*PY311_CACHE_DIR, &*PY312_CACHE_DIR, &*PY313_CACHE_DIR, + &*PY314_CACHE_DIR, + &*PY315_CACHE_DIR, &*BUN_BUNDLE_CACHE_DIR, &*GO_CACHE_DIR, &*GO_BIN_CACHE_DIR, diff --git a/backend/src/monitor.rs b/backend/src/monitor.rs index 8d0af4915d..827c092529 100644 --- a/backend/src/monitor.rs +++ b/backend/src/monitor.rs @@ -60,17 +60,19 @@ use windmill_common::{ CRITICAL_ALERTS_ON_DB_OVERSIZE_SETTING, CRITICAL_ALERTS_ON_TOKEN_EXPIRY_SETTING, CRITICAL_ALERT_MUTE_UI_SETTING, CRITICAL_ALERT_MUTE_ZOMBIE_JOB_RESTART_SETTING, CRITICAL_ERROR_CHANNELS_SETTING, CUSTOM_TAGS_SETTING, DEFAULT_TAGS_PER_WORKSPACE_SETTING, - DEFAULT_TAGS_WORKSPACES_SETTING, DEPENDENCY_JOB_TAG_SETTING, DISABLE_PASSWORD_LOGIN, - DISABLE_PASSWORD_LOGIN_SETTING, EXPOSE_DEBUG_METRICS_SETTING, EXPOSE_METRICS_SETTING, - EXTRA_PIP_INDEX_URL_SETTING, FORK_WORKSPACE_TAG_APPEND_FORK_SUFFIX_SETTING, - HUB_API_SECRET_SETTING, HUB_BASE_URL_SETTING, INSTANCE_PYTHON_VERSION_SETTING, - JOB_DEFAULT_TIMEOUT_SECS_SETTING, JOB_ISOLATION_SETTING, JWT_SECRET_SETTING, - KEEP_JOB_DIR_SETTING, LICENSE_KEY_SETTING, MCP_DISABLE_TOKEN_QUERY_PARAM, - MCP_DISABLE_TOKEN_QUERY_PARAM_SETTING, MONITOR_LOGS_ON_OBJECT_STORE_SETTING, NPMRC_SETTING, - NPM_CONFIG_REGISTRY_SETTING, NSJAIL_TMPFS_SIZE_MB_SETTING, NSJAIL_TMP_BACKING_SETTING, - NUGET_CONFIG_SETTING, OTEL_SETTING, OTEL_TRACES_RETENTION_SECS_SETTING, - OTEL_TRACING_PROXY_SETTING, PIP_INDEX_URL_SETTING, POWERSHELL_REPO_PAT_SETTING, - POWERSHELL_REPO_URL_SETTING, PREVIEW_TAGS_OVERRIDE_SETTING, REQUEST_SIZE_LIMIT_SETTING, + DEFAULT_TAGS_WORKSPACES_SETTING, DEPENDENCY_JOB_TAG_SETTING, + DEV_WORKSPACE_ISOLATION_SETTING, DEV_WORKSPACE_ISOLATION_SKIP_NON_DEV_FORKS_SETTING, + DEV_WORKSPACE_TAG_SUFFIX_SETTING, DISABLE_PASSWORD_LOGIN, DISABLE_PASSWORD_LOGIN_SETTING, + EXPOSE_DEBUG_METRICS_SETTING, EXPOSE_METRICS_SETTING, EXTRA_PIP_INDEX_URL_SETTING, + FORK_WORKSPACE_TAG_APPEND_FORK_SUFFIX_SETTING, HUB_API_SECRET_SETTING, + HUB_BASE_URL_SETTING, INSTANCE_PYTHON_VERSION_SETTING, JOB_DEFAULT_TIMEOUT_SECS_SETTING, + JOB_ISOLATION_SETTING, JWT_SECRET_SETTING, KEEP_JOB_DIR_SETTING, LICENSE_KEY_SETTING, + MCP_DISABLE_TOKEN_QUERY_PARAM, MCP_DISABLE_TOKEN_QUERY_PARAM_SETTING, + MONITOR_LOGS_ON_OBJECT_STORE_SETTING, NPMRC_SETTING, NPM_CONFIG_REGISTRY_SETTING, + NSJAIL_TMPFS_SIZE_MB_SETTING, NSJAIL_TMP_BACKING_SETTING, NUGET_CONFIG_SETTING, + OTEL_SETTING, OTEL_TRACES_RETENTION_SECS_SETTING, OTEL_TRACING_PROXY_SETTING, + PIP_INDEX_URL_SETTING, POWERSHELL_REPO_PAT_SETTING, POWERSHELL_REPO_URL_SETTING, + PREVIEW_TAGS_OVERRIDE_SETTING, REQUEST_SIZE_LIMIT_SETTING, REQUIRE_PREEXISTING_USER_FOR_OAUTH_SETTING, RETENTION_PERIOD_SECS_SETTING, SAML_METADATA_SETTING, SANDBOX_IMAGE_CACHE_MAX_MB_SETTING, SANDBOX_IMAGE_DEFAULT_REGISTRY_SETTING, SANDBOX_IMAGE_MAX_SIZE_MB_SETTING, @@ -89,15 +91,18 @@ use windmill_common::{ users::truncate_token, utils::{empty_as_none, now_from_db, report_critical_error, Mode, HUB_API_SECRET}, worker::{ - load_env_vars, load_init_bash_from_env, load_periodic_bash_script_from_env, - load_periodic_bash_script_interval_from_env, load_whitelist_env_vars_from_env, - load_worker_config, store_pull_query, store_suspended_pull_query, Connection, WorkerConfig, - CLOUD_HOSTED, CONCURRENCY_KEY_MAX_QUEUED, CONCURRENCY_KEY_MAX_QUEUED_DEFAULT, - DEFAULT_TAGS_PER_WORKSPACE, DEFAULT_TAGS_WORKSPACES, DEPENDENCY_JOB_TAG, - FORK_WORKSPACE_TAG_APPEND_FORK_SUFFIX, INDEXER_CONFIG, PREVIEW_TAGS_OVERRIDE, SMTP_CONFIG, - WINDMILL_DIR, WORKER_CONFIG, WORKER_GROUP, WORKSPACE_FAIRNESS_DURATION_SECS, - WORKSPACE_FAIRNESS_ENABLED, WORKSPACE_FAIRNESS_MAX_PERCENT, WORKSPACE_FAIRNESS_MIN_TOTAL, - WORKSPACE_MAX_QUEUED_JOBS, WORKSPACE_MAX_QUEUED_JOBS_DEFAULT, + is_valid_dev_workspace_tag_suffix, load_env_vars, load_init_bash_from_env, + load_periodic_bash_script_from_env, load_periodic_bash_script_interval_from_env, + load_whitelist_env_vars_from_env, load_worker_config, store_pull_query, + store_suspended_pull_query, Connection, WorkerConfig, CLOUD_HOSTED, + CONCURRENCY_KEY_MAX_QUEUED, CONCURRENCY_KEY_MAX_QUEUED_DEFAULT, + DEFAULT_DEV_WORKSPACE_TAG_SUFFIX, DEFAULT_TAGS_PER_WORKSPACE, DEFAULT_TAGS_WORKSPACES, + DEPENDENCY_JOB_TAG, DEV_WORKSPACE_ISOLATION, DEV_WORKSPACE_ISOLATION_SKIP_NON_DEV_FORKS, + DEV_WORKSPACE_TAG_SUFFIX, FORK_WORKSPACE_TAG_APPEND_FORK_SUFFIX, INDEXER_CONFIG, + PREVIEW_TAGS_OVERRIDE, SMTP_CONFIG, WINDMILL_DIR, WORKER_CONFIG, WORKER_GROUP, + WORKSPACE_FAIRNESS_DURATION_SECS, WORKSPACE_FAIRNESS_ENABLED, + WORKSPACE_FAIRNESS_MAX_PERCENT, WORKSPACE_FAIRNESS_MIN_TOTAL, WORKSPACE_MAX_QUEUED_JOBS, + WORKSPACE_MAX_QUEUED_JOBS_DEFAULT, }, KillpillSender, AUDIT_LOG_RETENTION_DAYS, BASE_URL, CRITICAL_ALERTS_ON_DB_OVERSIZE, CRITICAL_ALERTS_ON_TOKEN_EXPIRY, CRITICAL_ALERT_MUTE_UI_ENABLED, @@ -321,6 +326,18 @@ pub async fn initial_load( pass.setting(DEPENDENCY_JOB_TAG_SETTING, false, |v| async move { apply_dependency_job_tag(v) }); + // Ahead of the worker config reload below, which expands the tags with it. + pass.setting(DEV_WORKSPACE_TAG_SUFFIX_SETTING, false, |v| async move { + apply_dev_workspace_tag_suffix(v); + }); + pass.setting(DEV_WORKSPACE_ISOLATION_SETTING, false, |v| async move { + apply_dev_workspace_isolation(v) + }); + pass.setting( + DEV_WORKSPACE_ISOLATION_SKIP_NON_DEV_FORKS_SETTING, + false, + |v| async move { apply_dev_workspace_isolation_skip_non_dev_forks(v) }, + ); // Load per-workspace retention overrides before the first cleanup tick so a fresh server // never sweeps globally without honoring configured longer-retention workspaces. @@ -1127,6 +1144,53 @@ pub fn apply_fork_workspace_tag_append_fork_suffix(value: Option error::Result { + let v = load_value_from_global_settings(db, DEV_WORKSPACE_TAG_SUFFIX_SETTING).await?; + Ok(apply_dev_workspace_tag_suffix(v)) +} + +pub fn apply_dev_workspace_tag_suffix(value: Option) -> bool { + let suffix = match value { + Some(serde_json::Value::String(t)) if !t.trim().is_empty() => t.trim().to_string(), + _ => DEFAULT_DEV_WORKSPACE_TAG_SUFFIX.to_string(), + }; + if !is_valid_dev_workspace_tag_suffix(&suffix) { + tracing::error!("Ignoring invalid dev workspace tag suffix {suffix:?}"); + return false; + } + let prev = DEV_WORKSPACE_TAG_SUFFIX.swap(std::sync::Arc::new(suffix.clone())); + *prev != suffix +} + +pub async fn load_dev_workspace_isolation(db: &DB) -> error::Result<()> { + let v = load_value_from_global_settings(db, DEV_WORKSPACE_ISOLATION_SETTING).await?; + apply_dev_workspace_isolation(v); + Ok(()) +} + +pub fn apply_dev_workspace_isolation(value: Option) { + DEV_WORKSPACE_ISOLATION.store( + matches!(value, Some(serde_json::Value::Bool(true))), + Ordering::Relaxed, + ); +} + +pub async fn load_dev_workspace_isolation_skip_non_dev_forks(db: &DB) -> error::Result<()> { + let v = load_value_from_global_settings(db, DEV_WORKSPACE_ISOLATION_SKIP_NON_DEV_FORKS_SETTING) + .await?; + apply_dev_workspace_isolation_skip_non_dev_forks(v); + Ok(()) +} + +pub fn apply_dev_workspace_isolation_skip_non_dev_forks(value: Option) { + DEV_WORKSPACE_ISOLATION_SKIP_NON_DEV_FORKS.store( + matches!(value, Some(serde_json::Value::Bool(true))), + Ordering::Relaxed, + ); +} + pub async fn reload_critical_alert_mute_ui_setting(conn: &Connection) -> error::Result<()> { let v = load_value_from_global_settings_with_conn(conn, CRITICAL_ALERT_MUTE_UI_SETTING, true) .await?; @@ -4136,6 +4200,20 @@ pub async fn monitor_db( } _ => {} } + match windmill_common::runnable_job_stats::cleanup_old_runnable_job_stats( + db, + windmill_common::runnable_job_stats::RETENTION_DAYS, + ) + .await + { + Ok(count) if count > 0 => { + tracing::info!("Deleted {} old runnable job stats rows", count); + } + Err(e) => { + tracing::error!("Error cleaning up runnable job stats: {:?}", e); + } + _ => {} + } } } }; @@ -4435,6 +4513,44 @@ pub async fn monitor_db( } }; + // Drop the data table role set logins nobody has connected with for a month. Every ~40 min, + // spawned for the same reason as the credential maintenance above: it opens a connection per + // managed database for each login it drops. + let datatable_role_set_sweep_f = async { + if server_mode && iteration.is_some() && iteration.as_ref().unwrap().should_run(240) { + if let Some(db) = conn.as_sql() { + let db = db.clone(); + tokio::spawn(async move { + if let Err(e) = + windmill_common::datatable_roles::sweep_unused_role_set_logins(&db).await + { + tracing::error!("Error sweeping unused data table role set logins: {e}"); + } + }); + } + } + }; + + // Re-encrypt the legacy-format secret variables once new values are written in AES-256-GCM. + // Every ~5 min until one pass has gone through every workspace; spawned so a large instance + // does not hold up the join below. The column widening it starts with is tried every + // iteration: a v2 value too long for the narrow column fails to save until it is done. + let legacy_secret_upgrade_f = async { + if server_mode + && iteration.is_some() + && (windmill_common::variables::variable_value_widen_pending() + || (iteration.as_ref().unwrap().should_run(30) + && windmill_common::variables::legacy_secret_upgrade_pending())) + { + if let Some(db) = conn.as_sql() { + let db = db.clone(); + tokio::spawn(async move { + windmill_common::variables::upgrade_legacy_secret_variables(&db).await + }); + } + } + }; + // Delete the AI session backups older than their workspace's retention. Every ~40 min // (240 iterations at the default 10 s, the most a u8 `should_run` counts): the retention // counts in days. Spawned for the same reason as the credential maintenance above, a @@ -4506,7 +4622,9 @@ pub async fn monitor_db( cleanup_scheduled_job_deletions_f, git_auto_pull_f, git_credential_maintenance_f, + datatable_role_set_sweep_f, ai_session_retention_f, + legacy_secret_upgrade_f, pipeline_freshness_watchdog_f, reconcile_unarmed_schedules_f, stranded_jobs_f, diff --git a/backend/summarized_schema.txt b/backend/summarized_schema.txt index 2a518a7cc8..43b3d591ea 100644 --- a/backend/summarized_schema.txt +++ b/backend/summarized_schema.txt @@ -10,7 +10,7 @@ autoscaling_event_type: full_scaleout, scalein, scaleout aws_auth_resource_type: oidc, credentials delivery_mode: push, pull draft_type: script, flow, app -favorite_kind: app, script, flow, raw_app, asset +favorite_kind: app, script, flow, raw_app, asset, agent gcp_subscription_mode: create_update, existing http_method: get, post, put, delete, patch importer_kind: script, flow, app @@ -41,6 +41,7 @@ ai_agent_memory: workspace_id(char), conversation_id(uuid), step_id(char), messa ai_free_token_daily_usage: day(date), cost_nanos(bigint), updated_at(ts) ai_free_token_usage: email(char), cost_nanos(bigint), updated_at(ts) ai_shared_artifact: id(uuid), workspace_id(char), artifact_id(char), email(char), created_by(char), name(char), kind(char), version(int), content(text), shared_at(ts) +ai_shared_session: id(uuid), workspace_id(char), session_id(char), email(char), created_by(char), name(char), is_public(bool), message_count(int), snapshot(text), shared_at(ts) FK: (workspace_id) -> workspace(id) ai_token_usage: workspace_id(char), day(date), email(char), provider(char), model(char), session_id(char), input_tokens(bigint), cache_read_tokens(bigint), cache_write_tokens(bigint), output_tokens(bigint), reported_cost_nano_usd(bigint), requests(bigint), updated_at(ts) FK: (workspace_id) -> workspace(id) @@ -48,7 +49,7 @@ alerts: id(int), alert_type(char), message(text), created_at(ts), acknowledged(b app: id(bigint), workspace_id(char), path(char), summary(char), policy(jsonb), versions(bigint[]), extra_perms(jsonb), draft_only(bool), custom_path(text), labels(text[]) FK: (workspace_id) -> workspace(id) app_bundles: app_version_id(bigint), w_id(char), file_type(char), data(bytes) -app_script: id(bigint), app(bigint), hash(char(64)), lock(text), code(text), code_sha256(char(64)) +app_script: id(bigint), app(bigint), hash(char(64)), lock(text), code(text), code_sha256(char(64)), modules(jsonb) FK: (app) -> app(id) app_version: id(bigint), app_id(bigint), value(json), created_by(char), created_at(ts), raw_app(bool) FK: (app_id) -> app(id) @@ -132,7 +133,7 @@ input: id(uuid), workspace_id(char), runnable_id(char), runnable_type(runnable_t FK: (workspace_id) -> workspace(id) instance_group: name(char), summary(char), id(char), scim_display_name(char), external_id(char) job_logs: job_id(uuid), workspace_id(char), created_at(ts), logs(text), log_offset(int), log_file_index(text[]) -job_perms: job_id(uuid), email(char), username(char), is_admin(bool), is_operator(bool), created_at(ts), workspace_id(char), groups(text[]), folders(jsonb[]), end_user_email(char), job_token_scopes(text[]) +job_perms: job_id(uuid), email(char), username(char), is_admin(bool), is_operator(bool), created_at(ts), workspace_id(char), groups(text[]), folders(jsonb[]), end_user_email(char), job_token_scopes(text[]), viewer_data_access(bool) job_resolution: job_id(uuid), workspace_id(char), resolved_at(ts), resolved_by(char), note(text), automatic(bool) job_result_stream: job_id(uuid), workspace_id(text), stream(text) job_result_stream_v2: job_id(uuid), workspace_id(text), stream(text), idx(int) @@ -180,6 +181,7 @@ resource_type: workspace_id(char), name(char), schema(jsonb), description(text), FK: (workspace_id) -> workspace(id) resume_job: id(uuid), job(uuid), flow(uuid), created_at(ts), value(jsonb), approver(char), resume_id(int), approved(bool) FK: (flow) -> v2_job_queue(id) +runnable_job_stats: hour(bigint), workspace_id(char), runnable_path(char), worker_group(text), job_count(int), total_duration_ms(bigint), max_memory_peak(int), sum_memory_peak(bigint), memory_sample_count(int), total_cpu_ms(bigint) runnable_settings: hash(bigint), debouncing_settings(bigint), concurrency_settings(bigint) schedule: workspace_id(char), path(char), edited_by(char), edited_at(ts), schedule(char), enabled(bool), script_path(char), args(jsonb), extra_perms(jsonb), is_flow(bool), email(char), error(text), timezone(char), on_failure(char), on_recovery(char), on_failure_times(int), on_failure_exact(bool), on_failure_extra_args(jsonb), on_recovery_times(int), on_recovery_extra_args(jsonb), ws_error_handler_muted(bool), retry(jsonb), summary(char), no_flow_overlap(bool), tag(char), paused_until(ts), on_success(char), on_success_extra_args(jsonb), cron_version(text), description(text), dynamic_skip(char), labels(text[]) FK: (workspace_id) -> workspace(id) @@ -219,7 +221,7 @@ websocket_trigger: path(char), url(char), script_path(char), is_flow(bool), work windmill_migrations: name(text), created_at(ts) worker_group_job_stats: hour(bigint), worker_group(text), script_lang(char), workspace_id(char), job_count(int), total_duration_ms(bigint) FK: (workspace_id) -> workspace(id) -worker_ping: worker(char), worker_instance(char), ping_at(ts), started_at(ts), ip(char), jobs_executed(int), custom_tags(text[]), worker_group(char), dedicated_worker(char), wm_version(char), current_job_id(uuid), current_job_workspace_id(char), vcpus(bigint), memory(bigint), occupancy_rate(float), memory_usage(bigint), wm_memory_usage(bigint), occupancy_rate_15s(float), occupancy_rate_5m(float), occupancy_rate_30m(float), job_isolation(text), dedicated_workers(text[]) +worker_ping: worker(char), worker_instance(char), ping_at(ts), started_at(ts), ip(char), jobs_executed(int), custom_tags(text[]), worker_group(char), dedicated_worker(char), wm_version(char), current_job_id(uuid), current_job_workspace_id(char), vcpus(bigint), memory(bigint), occupancy_rate(float), memory_usage(bigint), wm_memory_usage(bigint), occupancy_rate_15s(float), occupancy_rate_5m(float), occupancy_rate_30m(float), job_isolation(text), dedicated_workers(text[]), draining(bool) workspace: id(char), name(char), owner(char), deleted(bool), premium(bool), parent_workspace_id(char), is_dev_workspace(bool) FK: (parent_workspace_id) -> workspace(id) workspace_dependencies: id(bigint), name(char), content(text), language(script_lang), description(text), archived(bool), workspace_id(char), created_at(ts) diff --git a/backend/tests/ai_decision.rs b/backend/tests/ai_decision.rs index 04b310f2c1..d6359c1cea 100644 --- a/backend/tests/ai_decision.rs +++ b/backend/tests/ai_decision.rs @@ -117,7 +117,7 @@ async fn test_ai_decision_answers_route_a_following_branch( "expr": "results.d.output.intent.choice === 'refund'", "modules": [{"id": "r", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main(choice){ return 'handled ' + choice }", "input_transforms": {"choice": { "type": "javascript", diff --git a/backend/tests/ai_sessions.rs b/backend/tests/ai_sessions.rs index 6b33a4141e..b2b8406db3 100644 --- a/backend/tests/ai_sessions.rs +++ b/backend/tests/ai_sessions.rs @@ -1580,3 +1580,163 @@ async fn test_backups_fall_back_to_the_instance_storage(db: Pool) -> a Ok(()) } + +/// Runs its closure when dropped, so process-wide state is put back even when an assertion +/// fails. +struct OnDrop(F); +impl Drop for OnDrop { + fn drop(&mut self) { + (self.0)() + } +} + +/// Once every worker reads AES-256-GCM and this server has been up long enough for any server +/// of the previous release to be gone, objects are written in it: a session backed up as CBC +/// before the switch still restores whole with the GCM pieces added after it, a head at its +/// cap and a push token still read back under the larger ciphertext, and relocated GCM +/// ciphertext does not decrypt for another user. +#[sqlx::test(fixtures("base"))] +async fn test_backups_switch_to_gcm_once_every_worker_reads_it( + db: Pool, +) -> anyhow::Result<()> { + use windmill_common::min_version::{ + MIN_VERSION, MIN_VERSION_SUPPORTS_AEAD_SECRETS, MIN_VERSION_SUPPORTS_JOB_TOKEN_SCOPES, + }; + use windmill_common::workspace_crypt::V2_MAGIC; + + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let base = format!( + "http://localhost:{}/api/w/test-workspace", + server.addr.port() + ); + let storage_dir = tempfile::tempdir()?; + configure_primary_lfs(&db, &storage_dir.path().to_string_lossy()).await?; + let before = MIN_VERSION.load_full(); + let _restore = OnDrop(move || MIN_VERSION.store(before.clone())); + let _uptime = OnDrop(|| windmill_common::db::set_process_uptime_offset(Default::default())); + let is_gcm = |b: &[u8]| b.starts_with(&V2_MAGIC); + let object = |path: &str| -> Vec { + std::fs::read(user_root(storage_dir.path(), "test@windmill.dev").join(path)).unwrap() + }; + + MIN_VERSION.store(std::sync::Arc::new( + MIN_VERSION_SUPPORTS_JOB_TOKEN_SCOPES.version().clone(), + )); + let resp = push( + &base, + "SECRET_TOKEN", + json!({ + "owner": "test@windmill.dev", + "sessions": [{ + "id": "s1", + "whole": true, + "head": { "id": "s1", "workspace_id": "test-workspace", "createdAt": 1, "chatId": "c1" }, + "chats": [{ "id": "c1", "record": { "id": "c1", "title": "BEFORE" } }] + }] + }), + ) + .await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + let cbc_chat = object("sessions/s1/chats/c1.json"); + assert!(!cbc_chat.is_empty() && !is_gcm(&cbc_chat)); + + MIN_VERSION.store(std::sync::Arc::new( + MIN_VERSION_SUPPORTS_AEAD_SECRETS.version().clone(), + )); + // Every worker reads it, but this server was only just started: still CBC. + let resp = push( + &base, + "SECRET_TOKEN", + json!({ + "owner": "test@windmill.dev", + "sessions": [{ "id": "s1", "chats": [{ "id": "c0", "record": { "id": "c0", "title": "FRESH" } }] }] + }), + ) + .await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + let fresh_chat = object("sessions/s1/chats/c0.json"); + assert!(!fresh_chat.is_empty() && !is_gcm(&fresh_chat)); + + windmill_common::db::set_process_uptime_offset( + windmill_common::db::PREVIOUS_RELEASE_ROLLOUT_UPTIME, + ); + let resp = push( + &base, + "SECRET_TOKEN", + json!({ + "owner": "test@windmill.dev", + "sessions": [{ + "id": "s1", + "chats": [{ "id": "c2", "record": { "id": "c2", "title": "AFTER" } }], + "images": [{ "chat_id": "c2", "id": "i1", "data_url": "data:image/png;base64,AAAA" }] + }] + }), + ) + .await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + assert_eq!( + object("sessions/s1/chats/c1.json"), + cbc_chat, + "not rewritten" + ); + assert!(is_gcm(&object("sessions/s1/chats/c2.json"))); + assert!(is_gcm(&object("images/s1/c2/i1"))); + + let pulled = pull(&base, "SECRET_TOKEN", &["s1"]).await?; + let mut titles: Vec = pulled["sessions"][0]["chats"] + .as_array() + .unwrap() + .iter() + .map(|c| c["record"]["title"].as_str().unwrap().to_string()) + .collect(); + titles.sort(); + assert_eq!(titles, ["AFTER", "BEFORE", "FRESH"], "{pulled}"); + assert_eq!( + pulled["sessions"][0]["images"][0]["data_url"], + "data:image/png;base64,AAAA" + ); + + // A head at its cap, pushed in two parts: the second reads back the push token. + let mut head = json!({ "id": "s2", "workspace_id": "test-workspace", "createdAt": 2, "chatId": "c", "pad": "" }); + let pad = 1024 * 1024 - head.to_string().len(); + head["pad"] = json!("x".repeat(pad)); + assert_eq!(head.to_string().len(), 1024 * 1024); + for part in [ + json!({ "id": "s2", "whole": true, "push": "p2", "opens": true, "partial": true, "head": head }), + json!({ "id": "s2", "whole": true, "push": "p2", "chats": [{ "id": "c", "record": { "id": "c" } }] }), + ] { + let resp = push( + &base, + "SECRET_TOKEN", + json!({ "owner": "test@windmill.dev", "sessions": [part] }), + ) + .await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + let pushed: Value = resp.json().await?; + assert_eq!(pushed["results"], json!([{ "id": "s2" }]), "{pushed}"); + } + assert!(is_gcm(&object("sessions/s2/head.json"))); + let pulled = pull(&base, "SECRET_TOKEN", &["s2"]).await?; + assert_eq!( + pulled["sessions"][0]["head"]["pad"].as_str().map(str::len), + Some(pad) + ); + assert_eq!(pulled["sessions"][0]["chats"][0]["id"], "c", "{pulled}"); + + let first = user_root(storage_dir.path(), "test@windmill.dev"); + copy_dir( + &first, + &first + .parent() + .unwrap() + .join(calculate_hash("test2@windmill.dev")), + )?; + assert_eq!( + pull(&base, "SECRET_TOKEN_2", &["s1", "s2"]).await?["sessions"], + json!([]), + "relocated ciphertext must not decrypt for another user" + ); + + Ok(()) +} diff --git a/backend/tests/ai_shared_sessions.rs b/backend/tests/ai_shared_sessions.rs new file mode 100644 index 0000000000..75334a5440 --- /dev/null +++ b/backend/tests/ai_shared_sessions.rs @@ -0,0 +1,120 @@ +//! Shared AI sessions: a private share is served only to members of its workspace, a public +//! one to anyone holding the link, and only its author decides which it is. + +use serde_json::{json, Value}; +use sqlx::{Pool, Postgres}; +use windmill_test_utils::*; + +const ADMIN: &str = "Bearer SECRET_TOKEN"; +const MEMBER: &str = "Bearer SECRET_TOKEN_2"; +const OTHER_MEMBER: &str = "Bearer SECRET_TOKEN_3"; +const OUTSIDER: &str = "Bearer OUTSIDER_TOKEN"; + +#[sqlx::test(fixtures("base"))] +async fn private_share_is_for_members_and_public_share_for_anyone( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + sqlx::raw_sql( + "INSERT INTO password(email, password_hash, login_type, super_admin, verified, name) + VALUES ('outsider@windmill.dev', 'not-a-real-hash', 'password', false, true, 'Outsider'); + INSERT INTO token(token_hash, token_prefix, token, email, label, super_admin) + VALUES (encode(sha256('OUTSIDER_TOKEN'::bytea), 'hex'), 'OUTSIDER_T', 'OUTSIDER_TOKEN', + 'outsider@windmill.dev', 'outsider token', false);", + ) + .execute(&db) + .await?; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let authed = format!("http://localhost:{port}/api/w/test-workspace/ai/shared_sessions"); + let get = |id: &str| { + format!("http://localhost:{port}/api/w/test-workspace/ai_u/shared_sessions/get/{id}") + }; + let client = reqwest::Client::new(); + + let resp = client + .post(format!("{authed}/share")) + .header("Authorization", MEMBER) + .json(&json!({ + "session_id": "session-1", + "name": "Debugging", + "message_count": 1, + "snapshot": { "messages": [{ "role": "user", "content": "hi" }], "artifacts": [] }, + })) + .send() + .await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + let share: Value = resp.json().await?; + assert_eq!(share["is_public"], false, "a new share must start private"); + let id = share["id"].as_str().unwrap().to_string(); + + let status = |token: Option<&'static str>| { + let mut req = client.get(get(&id)); + if let Some(token) = token { + req = req.header("Authorization", token); + } + async move { anyhow::Ok(req.send().await?.status().as_u16()) } + }; + + assert_eq!(status(Some(OTHER_MEMBER)).await?, 200); + assert_eq!( + status(None).await?, + 401, + "a private share was served anonymously" + ); + assert_eq!( + status(Some(OUTSIDER)).await?, + 401, + "a private share was served to a non-member" + ); + + let resp = client + .post(format!("{authed}/set_public/{id}")) + .header("Authorization", OTHER_MEMBER) + .json(&json!({ "is_public": true })) + .send() + .await?; + assert_eq!( + resp.status(), + 404, + "a member who is not the author made the share public" + ); + + let resp = client + .post(format!("{authed}/set_public/{id}")) + .header("Authorization", MEMBER) + .json(&json!({ "is_public": true })) + .send() + .await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + + let resp = client.get(get(&id)).send().await?; + assert_eq!( + resp.status(), + 200, + "a public share was not served anonymously" + ); + let body: Value = resp.json().await?; + assert_eq!(body["snapshot"]["messages"][0]["content"], "hi"); + assert_eq!(body["can_unshare"], false); + + let delete = |token: &'static str| { + client + .delete(format!("{authed}/delete/{id}")) + .header("Authorization", token) + .send() + }; + assert_eq!( + delete(OTHER_MEMBER).await?.status(), + 404, + "a member who is neither the author nor an admin took the share down" + ); + assert_eq!( + delete(ADMIN).await?.status(), + 200, + "an admin could not take the share down" + ); + assert_eq!(status(Some(OTHER_MEMBER)).await?, 404); + + Ok(()) +} diff --git a/backend/tests/app_ctx_inputs.rs b/backend/tests/app_ctx_inputs.rs new file mode 100644 index 0000000000..cf386adc89 --- /dev/null +++ b/backend/tests/app_ctx_inputs.rs @@ -0,0 +1,88 @@ +//! A context input a raw app runnable declares (`fields. = { type: "ctx", .. }`) is +//! filled by the server from the viewer's session. Whatever the request sends under that +//! name is discarded: a runnable filters rows on it, so a viewer who could set it would +//! read someone else's. +//! +//! Users from the `base` fixture: +//! test-user (admin, token SECRET_TOKEN) +//! test-user-2 (developer, token SECRET_TOKEN_2) + +use serde_json::json; +use sqlx::{Pool, Postgres}; +use windmill_test_utils::*; + +const ADMIN_TOKEN: &str = "SECRET_TOKEN"; +const VIEWER_TOKEN: &str = "SECRET_TOKEN_2"; +const APP_PATH: &str = "u/test-user/ctx_app"; +const CONTENT: &str = "export function main(who: string) { return who }"; +// sha256 of CONTENT, the key an inline runnable is pinned under. +const CONTENT_SHA: &str = "6e198199621d57e4fed834510cb0c2692274aa4cbe976e1704fab2806be9d744"; + +fn authed(builder: reqwest::RequestBuilder, token: &str) -> reqwest::RequestBuilder { + builder.header("Authorization", format!("Bearer {}", token)) +} + +#[sqlx::test(fixtures("base"))] +async fn a_declared_ctx_input_ignores_the_value_the_viewer_sends( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let ws = format!("http://localhost:{port}/api/w/test-workspace"); + let client = reqwest::Client::new(); + + let resp = authed(client.post(format!("{ws}/apps/create")), ADMIN_TOKEN) + .json(&json!({ + "path": APP_PATH, + "summary": "ctx inputs", + "value": { + "runnables": { + "whoami": { + "type": "inline", + "inlineScript": { "language": "bun", "content": CONTENT }, + "fields": { "who": { "type": "ctx", "ctx": "username" } } + } + } + }, + // The policy says nothing of context inputs: the server reads the + // declaration from the deployed runnable. + "policy": { + "execution_mode": "anonymous", + "triggerables_v2": { + format!("whoami:rawscript/{CONTENT_SHA}"): { + "static_inputs": {}, + "one_of_inputs": {} + } + } + } + })) + .send() + .await?; + assert!(resp.status().is_success(), "{}", resp.text().await?); + + // Both spellings a viewer could send: a forged literal, and no argument at all. + for args in [json!({ "who": "test-user" }), json!({})] { + let resp = authed( + client.post(format!("{ws}/apps_u/execute_component/{APP_PATH}")), + VIEWER_TOKEN, + ) + .json(&json!({ + "component": "whoami", + "args": args, + "raw_code": { "language": "bun", "content": CONTENT } + })) + .send() + .await?; + assert!(resp.status().is_success(), "{}", resp.text().await?); + let job_id: uuid::Uuid = resp.text().await?.parse()?; + + let queued: serde_json::Value = sqlx::query_scalar("SELECT args FROM v2_job WHERE id = $1") + .bind(job_id) + .fetch_one(&db) + .await?; + assert_eq!(queued["who"], json!("test-user-2"), "sent {args}"); + } + + Ok(()) +} diff --git a/backend/tests/app_preview_auth.rs b/backend/tests/app_preview_auth.rs index cd84e6f278..f8e90ce144 100644 --- a/backend/tests/app_preview_auth.rs +++ b/backend/tests/app_preview_auth.rs @@ -312,13 +312,11 @@ async fn test_app_preview_authorization(db: Pool) -> anyhow::Result<() "run-mode unpinned raw_code must be rejected for any caller, not just operators (got {status}): {body}" ); - // 11. The pin requirement also covers `raw_code` carrying an `app_script` - // `id`. The id resolves to `rawscript/` of any app_script row - // by number (no app scoping), so without the pin a caller could run a - // script belonging to another app against this Viewer app. Here `999777` - // belongs to `u/test-user/private`, not to the targeted `vapp`, and its - // sha is absent from `vapp`'s empty `triggerables_v2` — it must be - // rejected, not fall back to the Viewer default. + // 11. `raw_code` carrying an `app_script` `id` from another app must not run + // against this Viewer app: the row carries its own modules and lock, which + // would run under `vapp`'s identity. Here `999777` belongs to + // `u/test-user/private`, not to the targeted `vapp`, so the id lookup + // (scoped to the app) refuses it before any Viewer default applies. let resp = authed( client().post(format!("{base}/u/test-user/vapp")), "OPERATOR_TOKEN", @@ -338,12 +336,12 @@ async fn test_app_preview_authorization(db: Pool) -> anyhow::Result<() let status = resp.status(); let body = resp.text().await?; assert_eq!( - status, 400, - "run-mode raw_code with an unpinned app_script id must be rejected against a Viewer app (got {status}): {body}" + status, 401, + "run-mode raw_code with another app's app_script id must be rejected against a Viewer app (got {status}): {body}" ); assert!( - body.contains("forbidden by policy"), - "rejection must be the content-hash pin (unpinned app_script sha), got: {body}" + body.contains("does not belong to app u/test-user/vapp"), + "rejection must be the app scoping of the app_script id, got: {body}" ); // 12. Path confinement: the scope picker mints `apps:run:` / diff --git a/backend/tests/app_publisher_permit.rs b/backend/tests/app_publisher_permit.rs new file mode 100644 index 0000000000..e590efaeb2 --- /dev/null +++ b/backend/tests/app_publisher_permit.rs @@ -0,0 +1,40 @@ +//! A refused publisher-mode app run is not remembered: once the caller is granted +//! read access to the app, the very next run in the same process is allowed. + +use serde_json::json; +use sqlx::{Pool, Postgres}; +use windmill_test_utils::*; + +#[sqlx::test(fixtures("base", "app_publisher_permit"))] +async fn test_publisher_app_refusal_is_not_cached(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let url = format!( + "http://localhost:{port}/api/w/test-workspace/apps_u/execute_component/u/test-user/papp" + ); + + let run = || async { + let resp = reqwest::Client::new() + .post(&url) + .header("Authorization", "Bearer SECRET_TOKEN_2") + .json(&json!({ "component": "c", "path": "script/u/test-user/hello", "args": {} })) + .send() + .await?; + let status = resp.status().as_u16(); + anyhow::Ok((status, resp.text().await?)) + }; + + let (status, body) = run().await?; + assert_eq!(status, 401, "unshared app must be refused: {body}"); + assert!(body.contains("Missing read permissions"), "{body}"); + + sqlx::query("UPDATE app SET extra_perms = '{\"u/test-user-2\": false}' WHERE id = 999101") + .execute(&db) + .await?; + let (status, body) = run().await?; + assert_eq!(status, 200, "a grant must apply to the next run: {body}"); + + Ok(()) +} diff --git a/backend/tests/app_run_mode_lock_strip.rs b/backend/tests/app_run_mode_lock_strip.rs index d13d34a6c7..7a1bba75f6 100644 --- a/backend/tests/app_run_mode_lock_strip.rs +++ b/backend/tests/app_run_mode_lock_strip.rs @@ -289,7 +289,10 @@ async fn test_app_script_run_derives_path(db: Pool) -> anyhow::Result< .await?; let status = resp.status(); let body = resp.text().await?; - assert_eq!(status, 200, "deployed app script run must be accepted: {body}"); + assert_eq!( + status, 200, + "deployed app script run must be accepted: {body}" + ); let uuid = uuid::Uuid::parse_str(body.trim())?; let (_, _, _, _, runnable_path) = job_fields(&db, uuid).await?; assert_eq!( @@ -300,3 +303,103 @@ async fn test_app_script_run_derives_path(db: Pool) -> anyhow::Result< Ok(()) } + +/// Once the deployed version has its lite value, a deployed row's code runs only through +/// that row, while id-less SQL the frontend builds at runtime (database studio queries) +/// still runs on its content pin. +#[sqlx::test(fixtures("base"))] +async fn test_run_mode_id_less_code_with_lite(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let ws = format!("http://localhost:{port}/api/w/test-workspace"); + + const RUNTIME_CONTENT: &str = "SELECT 1;\n"; + const DEPLOYED_CONTENT: &str = "SELECT 2;\n"; + let app_path = "u/test-user/lite_id_less"; + let resp = authed(client().post(format!("{ws}/apps/create")), "SECRET_TOKEN") + .json(&json!({ + "path": app_path, + "summary": "", + "value": {}, + "policy": { + "execution_mode": "viewer", + "triggerables_v2": { + format!("comp:{}", rawscript_pin(DEPLOYED_CONTENT)): { "static_inputs": {}, "one_of_inputs": {} }, + format!("comp:{}", rawscript_pin(RUNTIME_CONTENT)): { "static_inputs": {}, "one_of_inputs": {} } + } + } + })) + .send() + .await?; + assert_eq!(resp.status(), 201, "create app: {}", resp.text().await?); + + let sha = rawscript_pin(DEPLOYED_CONTENT) + .trim_start_matches("rawscript/") + .to_string(); + let script_id: i64 = sqlx::query_scalar( + "INSERT INTO app_script (app, hash, code, code_sha256) + SELECT id, $2, $3, $2 FROM app WHERE path = $1 RETURNING id", + ) + .bind(app_path) + .bind(&sha) + .bind(DEPLOYED_CONTENT) + .fetch_one(&db) + .await?; + sqlx::query( + "INSERT INTO app_version_lite (id, value) + SELECT versions[array_upper(versions, 1)], $2 FROM app WHERE path = $1", + ) + .bind(app_path) + .bind( + json!({ "grid": [{ "data": { "componentInput": { "runnable": { + "inlineScript": { "id": script_id, "language": "postgresql" } + } } } }] }), + ) + .execute(&db) + .await?; + + let run = |content: &'static str, language: &'static str| { + authed( + client().post(format!("{ws}/apps_u/execute_component/{app_path}")), + "SECRET_TOKEN_2", + ) + .json(&json!({ + "args": {}, + "component": "comp", + "raw_code": { "language": language, "content": content } + })) + .send() + }; + + let resp = run(RUNTIME_CONTENT, "postgresql").await?; + let status = resp.status(); + assert_eq!( + status, + 200, + "id-less runtime-built code must run: {}", + resp.text().await? + ); + + // The pin covers content only (it also pins frontend scripts), so a pinned content + // must not run id-less in a language the database studio never emits. + let resp = run(RUNTIME_CONTENT, "bash").await?; + let status = resp.status(); + assert_eq!( + status, + 401, + "id-less code must not run as a non-SQL language: {}", + resp.text().await? + ); + + let resp = run(DEPLOYED_CONTENT, "postgresql").await?; + let status = resp.status(); + assert_eq!( + status, + 401, + "a deployed row's code must not run id-less: {}", + resp.text().await? + ); + + Ok(()) +} diff --git a/backend/tests/batch_rerun.rs b/backend/tests/batch_rerun.rs index 58cf27db87..9663eea73b 100644 --- a/backend/tests/batch_rerun.rs +++ b/backend/tests/batch_rerun.rs @@ -29,12 +29,21 @@ const FLOW_VERSION: i64 = 2222222222; /// Mark a queued job as completed with success — needed so it's eligible for /// `list_selected_job_groups` / `batch_rerun_jobs` (both join `v2_job_completed`). async fn complete_job(db: &Pool, job_id: Uuid) -> anyhow::Result<()> { + complete_job_with_status(db, job_id, "success").await +} + +async fn complete_job_with_status( + db: &Pool, + job_id: Uuid, + status: &str, +) -> anyhow::Result<()> { sqlx::query( "INSERT INTO v2_job_completed (workspace_id, id, result, status, duration_ms, started_at, completed_at) - VALUES ($1, $2, '{}'::jsonb, 'success', 0, now(), now())", + VALUES ($1, $2, '{}'::jsonb, $3::job_status, 0, now(), now())", ) .bind(WORKSPACE) .bind(job_id) + .bind(status) .execute(db) .await?; Ok(()) @@ -660,3 +669,56 @@ async fn batch_rerun_denies_invisible_source_job(db: Pool) -> anyhow:: assert_eq!(pushed, 0); Ok(()) } + +/// Re-running a failed or canceled job resolves it, pointing at the re-run, which is what lets +/// "hide resolved" exclude it from the next batch. A success has nothing to resolve. +#[sqlx::test(fixtures("base", "batch_rerun"))] +async fn batch_rerun_resolves_failed_and_canceled_sources( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let client = windmill_api_client::create_client( + &format!("http://localhost:{}", server.addr.port()), + "SECRET_TOKEN".to_string(), + ); + + let mut sources = vec![]; + for status in ["success", "failure", "canceled"] { + let id = RunJob::from(script_payload()) + .arg("name".to_string(), json!(status)) + .push(&db) + .await; + complete_job_with_status(&db, id, status).await?; + sources.push(id); + } + + let results = batch_rerun( + &client, + json!({ + "job_ids": sources, + "script_options_by_path": {}, + "flow_options_by_path": {}, + }), + ) + .await?; + assert!(results.iter().all(|r| r.is_ok()), "{results:?}"); + + let resolved: Vec<(String, String)> = sqlx::query_as( + "SELECT o.args->>'name', n.args->>'name' + FROM job_resolution r + JOIN v2_job o ON o.id = r.job_id + JOIN v2_job n ON r.note = 'Re-run as ' || n.id + ORDER BY 1", + ) + .fetch_all(&db) + .await?; + assert_eq!( + resolved, + vec![ + ("canceled".to_string(), "canceled".to_string()), + ("failure".to_string(), "failure".to_string()), + ] + ); + Ok(()) +} diff --git a/backend/tests/datatable_fork_migrations.rs b/backend/tests/datatable_fork_migrations.rs new file mode 100644 index 0000000000..50f4d89705 --- /dev/null +++ b/backend/tests/datatable_fork_migrations.rs @@ -0,0 +1,148 @@ +//! A fork's copy of a data table must report the migrations its schema already holds as applied. +//! +//! A schema-only copy restores `_wm_migrations` without its rows, and no copy carries the source's +//! `ALTER DATABASE ... SET search_path`, through which the bookkeeping table is found. Either one +//! alone makes the fork list every applied migration as pending, and running them fails on +//! objects that already exist. The source's `DateStyle` differs from the copy's while the rows +//! are written, so they must not travel in its text form. + +use serde_json::{json, Value}; +use sqlx::{Pool, Postgres}; + +use windmill_test_utils::*; + +const ROLE: &str = "wm_dtfork_test_role"; +const ROLE_PASSWORD: &str = "wm_dtfork_test_pwd"; + +fn authed(b: reqwest::RequestBuilder) -> reqwest::RequestBuilder { + b.header("Authorization", "Bearer DTMIG_ADMIN_TOKEN") +} + +#[sqlx::test(fixtures("datatable_migrations_grants"))] +async fn a_forked_copy_keeps_its_applied_migrations(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let opts = (*db.connect_options()).clone(); + // The copy takes its settings locks on a connection of its own, opened from `DATABASE_URL` + // rather than the pool: point that at this test's database, not the one sqlx creates it from. + // Only this test runs in the binary, and before anything has read the variable. + let base_url = std::env::var("DATABASE_URL")?; + let (prefix, rest) = base_url + .rsplit_once('/') + .expect("DATABASE_URL names a database"); + let query = rest + .split_once('?') + .map(|(_, q)| format!("?{q}")) + .unwrap_or_default(); + let test_db = opts.get_database().expect("test database name"); + std::env::set_var("DATABASE_URL", format!("{prefix}/{test_db}{query}")); + // Databases are cluster-wide, so both are named for this run alone. + let suffix = format!( + "{:x}", + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH)? + .as_nanos() + ); + let source = format!("wm_dtfork_src_{suffix}"); + let fork_id = format!("wm-fork-dtfork-{suffix}"); + let copy = format!("wm_fork_dtfork_{suffix}__main"); + + sqlx::query(&format!( + "DO $$ BEGIN \ + CREATE ROLE {ROLE} LOGIN CREATEDB PASSWORD '{ROLE_PASSWORD}'; \ + EXCEPTION WHEN duplicate_object OR unique_violation THEN NULL; \ + END $$" + )) + .execute(&db) + .await?; + sqlx::query(&format!("CREATE DATABASE {source} OWNER {ROLE}")) + .execute(&db) + .await?; + + let result = async { + let source_pool = sqlx::PgPool::connect_with(opts.clone().database(&source)).await?; + sqlx::raw_sql(&format!( + "SET ROLE {ROLE}; \ + CREATE SCHEMA app; \ + CREATE TABLE app.foo (id int); \ + CREATE TABLE app._wm_migrations (datatable TEXT NOT NULL, version BIGINT NOT NULL, \ + installed_at TIMESTAMPTZ NOT NULL DEFAULT now(), PRIMARY KEY (datatable, version)); \ + INSERT INTO app._wm_migrations (datatable, version, installed_at) \ + VALUES ('main', 1, '2026-01-31 10:00:00+00'); \ + ALTER DATABASE {source} SET search_path = app; \ + ALTER DATABASE {source} SET datestyle = 'SQL, DMY';" + )) + .execute(&source_pool) + .await?; + source_pool.close().await; + + sqlx::query( + "INSERT INTO resource (workspace_id, path, value, resource_type, created_by) \ + VALUES ('dtmig-ws', 'u/dtmig-admin/pg', $1, 'postgresql', 'dtmig-admin')", + ) + .bind(json!({ + "host": opts.get_host(), + "port": opts.get_port(), + "dbname": source, + "user": ROLE, + "password": ROLE_PASSWORD, + "sslmode": "disable", + })) + .execute(&db) + .await?; + sqlx::query( + "INSERT INTO datatable_migrations (workspace_id, datatable, timestamp, name, code_up) \ + VALUES ('dtmig-ws', 'main', 1, 'create_foo', 'CREATE TABLE foo (id int)')", + ) + .execute(&db) + .await?; + + let server = ApiServer::start(db.clone()).await?; + let base = format!("http://localhost:{}/api", server.addr.port()); + let client = reqwest::Client::new(); + + let resp = authed(client.post(format!("{base}/w/dtmig-ws/workspaces/create_fork"))) + .json(&json!({ + "id": fork_id, + "name": "fork", + "forked_datatables": [ + {"name": "main", "new_dbname": copy, "fork_behavior": "schema_only"} + ], + })) + .send() + .await?; + // `ensure!` rather than `assert!`: a panic would skip dropping the databases below. + let fork_status = resp.status(); + anyhow::ensure!(fork_status == 200, "{}", resp.text().await?); + + let status: Value = authed(client.get(format!( + "{base}/w/{fork_id}/workspaces/datatable_migrations_status/main" + ))) + .send() + .await? + .json() + .await?; + anyhow::ensure!(status["migrations"][0]["status"] == "ran", "{status}"); + + let copied: Vec = sqlx::query_scalar( + "SELECT unnest(setconfig) FROM pg_db_role_setting \ + WHERE setrole = 0 AND setdatabase = (SELECT oid FROM pg_database WHERE datname = $1) \ + ORDER BY 1", + ) + .bind(©) + .fetch_all(&db) + .await?; + anyhow::ensure!( + copied == ["DateStyle=SQL, DMY", "search_path=app"], + "{copied:?}" + ); + anyhow::Ok(()) + } + .await; + + for name in [©, &source] { + sqlx::query(&format!("DROP DATABASE IF EXISTS {name} WITH (FORCE)")) + .execute(&db) + .await?; + } + result +} diff --git a/backend/tests/datatable_migration_add_down.rs b/backend/tests/datatable_migration_add_down.rs index 47ea4c253b..1259628068 100644 --- a/backend/tests/datatable_migration_add_down.rs +++ b/backend/tests/datatable_migration_add_down.rs @@ -174,3 +174,34 @@ async fn test_add_down_to_a_migration_whose_comment_predates_role_annotations( assert_eq!(resp.status(), 200, "{}", resp.text().await?); Ok(()) } + +/// Likewise for `-- schemas`: the scope annotation is held only to up SQL being written, so a +/// definition whose stored up opens with prose starting with the word still accepts its down. +#[sqlx::test(fixtures("datatable_migrations_grants"))] +async fn test_add_down_to_a_migration_whose_comment_predates_scope_annotations( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + setup_applied_migration_without_down(&db).await?; + let code_up = format!("-- Schemas: changes for the widgets feature\n{CODE_UP}"); + sqlx::query("UPDATE datatable_migrations SET code_up = $1 WHERE workspace_id = 'dtmig-ws'") + .bind(&code_up) + .execute(&db) + .await?; + + let server = ApiServer::start(db.clone()).await?; + let resp = authed(reqwest::Client::new().post(format!( + "http://localhost:{}/api/w/dtmig-ws/workspaces/upsert_datatable_migration/main", + server.addr.port() + ))) + .json(&json!({ + "timestamp": VERSION, + "name": "create_widgets", + "code_up": code_up, + "code_down": CODE_DOWN, + })) + .send() + .await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + Ok(()) +} diff --git a/backend/tests/debounce_e2e.rs b/backend/tests/debounce_e2e.rs index 9a2351f135..709629d825 100644 --- a/backend/tests/debounce_e2e.rs +++ b/backend/tests/debounce_e2e.rs @@ -33,7 +33,7 @@ mod debounce_e2e { "id": "a", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export async function main(items: any[]) { return items }", "input_transforms": { "items": { "type": "javascript", "expr": "flow_input.items" } diff --git a/backend/tests/dedicated_workers.rs b/backend/tests/dedicated_workers.rs index 5e9c371f90..d0ba3e5e63 100644 --- a/backend/tests/dedicated_workers.rs +++ b/backend/tests/dedicated_workers.rs @@ -23,6 +23,20 @@ mod dedicated_worker_tests { WorkspacedPath { workspace_id: workspace.to_string(), path: path.to_string() } } + /// Waits on one listener for every job: the jobs may complete in any order, and a listener + /// opened after one completes never sees that notification. + async fn wait_for_all( + mut listener: impl futures::Stream + Unpin, + jobs: &[uuid::Uuid], + ) { + use futures::StreamExt; + let mut pending: std::collections::HashSet<_> = jobs.iter().copied().collect(); + while !pending.is_empty() { + let id = listener.next().await.expect("completed job listener ended"); + pending.remove(&id); + } + } + /// Assert that a completed job (or any descendant job) was executed /// by a dedicated worker process with the expected mode by checking job logs /// for the "dedicated worker {mode}:" prefix. @@ -280,10 +294,7 @@ mod dedicated_worker_tests { in_test_worker_dedicated( db.clone(), async { - // Wait for both jobs to complete - listener.find(&uuid_a).await; - let listener2 = listen_for_completed_jobs(&db).await; - listener2.find(&uuid_b).await; + wait_for_all(listener, &[uuid_a, uuid_b]).await; }, port, vec![ @@ -533,9 +544,7 @@ mod dedicated_worker_tests { in_test_worker_dedicated( db.clone(), async { - listener.find(&uuid_a).await; - let listener2 = listen_for_completed_jobs(&db).await; - listener2.find(&uuid_b).await; + wait_for_all(listener, &[uuid_a, uuid_b]).await; }, port, vec![ @@ -659,9 +668,7 @@ mod dedicated_worker_tests { in_test_worker_dedicated( db.clone(), async { - listener.find(&uuid_standalone).await; - let listener2 = listen_for_completed_jobs(&db).await; - listener2.find(&uuid_flow).await; + wait_for_all(listener, &[uuid_standalone, uuid_flow]).await; }, port, vec![ @@ -824,9 +831,7 @@ mod dedicated_worker_tests { in_test_worker_dedicated( db.clone(), async { - listener.find(&uuid_a).await; - let listener2 = listen_for_completed_jobs(&db).await; - listener2.find(&uuid_b).await; + wait_for_all(listener, &[uuid_a, uuid_b]).await; }, port, vec![ @@ -898,9 +903,7 @@ mod dedicated_worker_tests { in_test_worker_dedicated( db.clone(), async { - listener.find(&uuid_pre).await; - let listener2 = listen_for_completed_jobs(&db).await; - listener2.find(&uuid_other).await; + wait_for_all(listener, &[uuid_pre, uuid_other]).await; }, port, vec![ @@ -971,9 +974,7 @@ mod dedicated_worker_tests { in_test_worker_dedicated( db.clone(), async { - listener.find(&uuid_branch).await; - let listener2 = listen_for_completed_jobs(&db).await; - listener2.find(&uuid_default).await; + wait_for_all(listener, &[uuid_branch, uuid_default]).await; }, port, vec![wp("test-workspace", "flow/f/system/dedicated_branch_flow")], @@ -1198,9 +1199,7 @@ mod dedicated_worker_tests { in_test_worker_dedicated( db.clone(), async { - listener.find(&uuid_pre).await; - let listener2 = listen_for_completed_jobs(&db).await; - listener2.find(&uuid_other).await; + wait_for_all(listener, &[uuid_pre, uuid_other]).await; }, port, vec![ @@ -1281,9 +1280,7 @@ mod dedicated_worker_tests { in_test_worker_dedicated( db.clone(), async { - listener.find(&uuid_ws1).await; - let listener2 = listen_for_completed_jobs(&db).await; - listener2.find(&uuid_ws2).await; + wait_for_all(listener, &[uuid_ws1, uuid_ws2]).await; }, port, vec![ diff --git a/backend/tests/dev_workspace_tag_suffix.rs b/backend/tests/dev_workspace_tag_suffix.rs new file mode 100644 index 0000000000..1a61bee8aa --- /dev/null +++ b/backend/tests/dev_workspace_tag_suffix.rs @@ -0,0 +1,208 @@ +//! Sets the process-wide `DEV_WORKSPACE_ISOLATION`, so it lives in its own test binary: any other +//! test pushing a job in the same process would land on a suffixed tag. + +use std::collections::HashMap; + +use sqlx::{Pool, Postgres}; +use windmill_common::{ + jobs::{JobPayload, RawCode}, + runnable_settings::{ConcurrencySettings, DebouncingSettings}, + scripts::{ScriptHash, ScriptLang}, + worker::{DEV_WORKSPACE_ISOLATION, DEV_WORKSPACE_ISOLATION_SKIP_NON_DEV_FORKS}, +}; +use windmill_queue::{PushArgs, PushIsolationLevel}; + +async fn pushed_tag( + db: &Pool, + workspace_id: &str, + payload: JobPayload, + tag: Option<&str>, +) -> String { + try_pushed_tag(db, workspace_id, payload, tag) + .await + .expect("push must succeed") +} + +async fn try_pushed_tag( + db: &Pool, + workspace_id: &str, + payload: JobPayload, + tag: Option<&str>, +) -> Result { + let args = HashMap::new(); + let (id, tx) = windmill_queue::push( + db, + PushIsolationLevel::IsolatedRoot(db.clone()), + workspace_id, + payload, + PushArgs::from(&args), + "test-user", + "test@windmill.dev", + "u/test-user".to_string(), + None, + None, + None, + None, + None, + None, + None, + None, + false, + false, + None, + true, + tag.map(str::to_string), + None, + None, + None, + None, + false, + None, + None, + None, + None, + ) + .await?; + tx.commit().await.unwrap(); + Ok(sqlx::query_scalar("SELECT tag FROM v2_job WHERE id = $1") + .bind(id) + .fetch_one(db) + .await + .unwrap()) +} + +fn preview() -> JobPayload { + JobPayload::Code(RawCode { + hash: None, + content: "echo hi".to_string(), + path: None, + language: ScriptLang::Bash, + lock: None, + concurrency_settings: ConcurrencySettings::default().into(), + debouncing_settings: DebouncingSettings::default(), + cache_ttl: None, + cache_ignore_s3_path: None, + dedicated_worker: None, + modules: None, + tag: None, + }) +} + +#[sqlx::test(fixtures("base"))] +async fn dev_workspace_and_fork_jobs_run_on_suffixed_tags(db: Pool) { + DEV_WORKSPACE_ISOLATION.store(true, std::sync::atomic::Ordering::Relaxed); + + // A dev workspace, a fork of it, a fork whose parent was deleted (`ON DELETE SET NULL`), and a + // fork of the root with a fork of its own. + sqlx::query( + "INSERT INTO workspace (id, name, owner, parent_workspace_id, is_dev_workspace) VALUES + ('staging', 'staging', 'test-user', 'test-workspace', true), + ('wm-fork-a', 'fork', 'test-user', 'staging', false), + ('wm-fork-orphan', 'orphan', 'test-user', NULL, false), + ('wm-fork-root', 'root fork', 'test-user', 'test-workspace', false), + ('wm-fork-root-2', 'root fork 2', 'test-user', 'wm-fork-root', false), + ('archived-dev', 'archived dev', 'test-user', 'test-workspace', false), + ('wm-fork-of-archived', 'fork of archived dev', 'test-user', 'archived-dev', false)", + ) + .execute(&db) + .await + .unwrap(); + sqlx::query( + "INSERT INTO workspace_settings (workspace_id) VALUES + ('staging'), ('wm-fork-a'), ('wm-fork-orphan'), ('wm-fork-root'), ('wm-fork-root-2'), + ('archived-dev'), ('wm-fork-of-archived')", + ) + .execute(&db) + .await + .unwrap(); + + for (workspace, tag, expected) in [ + ("test-workspace", None, "bash"), + ("test-workspace", Some("gpu"), "gpu"), + ("staging", None, "bash-dev"), + ("staging", Some("gpu"), "gpu-dev"), + // A tag inherited from a dev job (a flow step, an agent's tool) is not suffixed twice. + ("staging", Some("gpu-dev"), "gpu-dev"), + ("wm-fork-a", None, "bash-dev"), + ("wm-fork-orphan", None, "bash-dev"), + ("wm-fork-root", None, "bash-dev"), + ] { + assert_eq!( + pushed_tag(&db, workspace, preview(), tag).await, + expected, + "{workspace} with tag {tag:?}" + ); + } + + // Only the forks whose lineage holds no dev workspace leave isolation. An orphaned fork's + // lineage is unknown, and so is that of a fork of an archived dev workspace (archiving clears + // `is_dev_workspace`), so both stay. + sqlx::query("UPDATE workspace SET deleted = true WHERE id = 'archived-dev'") + .execute(&db) + .await + .unwrap(); + DEV_WORKSPACE_ISOLATION_SKIP_NON_DEV_FORKS.store(true, std::sync::atomic::Ordering::Relaxed); + for (workspace, expected) in [ + ("wm-fork-root", "bash"), + ("wm-fork-root-2", "bash"), + ("staging", "bash-dev"), + ("wm-fork-a", "bash-dev"), + ("wm-fork-orphan", "bash-dev"), + ("wm-fork-of-archived", "bash-dev"), + ] { + assert_eq!( + pushed_tag(&db, workspace, preview(), None).await, + expected, + "{workspace} with non-dev forks not isolated" + ); + } + DEV_WORKSPACE_ISOLATION_SKIP_NON_DEV_FORKS.store(false, std::sync::atomic::Ordering::Relaxed); + + // A dedicated worker tag already names the workspace, and its worker is placed by hand. + let dedicated = JobPayload::ScriptHash { + hash: ScriptHash(123412), + path: "f/system/hello".to_string(), + cache_ttl: None, + cache_ignore_s3_path: None, + dedicated_worker: Some(true), + language: ScriptLang::Bun, + priority: None, + apply_preprocessor: false, + concurrency_settings: ConcurrencySettings::default(), + debouncing_settings: DebouncingSettings::default(), + labels: None, + job_token_scopes: None, + }; + assert_eq!( + pushed_tag(&db, "staging", dedicated, None).await, + "staging:f/system/hello" + ); + + // A hashed dedicated tag keeps only a prefix of its workspace id: a dev workspace sharing that + // prefix does not get to use another workspace's dedicated worker. + let root = "a".repeat(40); + let dev = format!("{root}-dev"); + sqlx::query( + "INSERT INTO workspace (id, name, owner, parent_workspace_id, is_dev_workspace) + VALUES ($1, 'root', 'test-user', NULL, false), ($2, 'dev', 'test-user', $1, true)", + ) + .bind(&root) + .bind(&dev) + .execute(&db) + .await + .unwrap(); + sqlx::query("INSERT INTO workspace_settings (workspace_id) VALUES ($1), ($2)") + .bind(&root) + .bind(&dev) + .execute(&db) + .await + .unwrap(); + let root_dedicated = + windmill_common::worker::dedicated_worker_tag(&root, "f/some/long/script/path"); + assert!( + try_pushed_tag(&db, &dev, preview(), Some(&root_dedicated)) + .await + .is_err(), + "{root_dedicated} must not stay unsuffixed, and suffixed it no longer fits a job tag" + ); +} diff --git a/backend/tests/drafts_delete_for_user.rs b/backend/tests/drafts_delete_for_user.rs new file mode 100644 index 0000000000..9c48f8828c --- /dev/null +++ b/backend/tests/drafts_delete_for_user.rs @@ -0,0 +1,85 @@ +//! Only a workspace admin can delete a draft that belongs to another user. +//! +//! A discard through `drafts/update` is scoped to the caller's own row, so it +//! never reaches someone else's draft. `drafts/delete_for_user` is the admin +//! route for that, and it must stay closed to everyone else. + +use serde_json::{json, Value}; +use sqlx::{Pool, Postgres}; + +use windmill_test_utils::*; + +#[sqlx::test(fixtures("base"))] +async fn test_only_admin_deletes_another_users_draft(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let base = format!("http://localhost:{port}/api/w/test-workspace/drafts"); + let client = reqwest::Client::new(); + let path = "script/u/test-user-2/theirs"; + + let save = |token: &'static str| { + client + .post(format!("{base}/update/{path}")) + .header("Authorization", format!("Bearer {token}")) + .json(&json!({ "value": { "path": "u/test-user-2/theirs", "content": "" } })) + .send() + }; + let resp = save("SECRET_TOKEN_2").await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + + let delete = |token: &'static str| { + client + .post(format!( + "{base}/delete_for_user/{path}?username=test-user-2" + )) + .header("Authorization", format!("Bearer {token}")) + .send() + }; + let own_draft = || async { + client + .get(format!("{base}/get_own/{path}")) + .header("Authorization", "Bearer SECRET_TOKEN_2") + .send() + .await? + .json::() + .await + }; + + let resp = delete("SECRET_TOKEN_3").await?; + assert_eq!(resp.status(), 403, "{}", resp.text().await?); + assert!( + !own_draft().await?.is_null(), + "a non-admin deleted the draft" + ); + + let resp = delete("SECRET_TOKEN").await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + assert!(own_draft().await?.is_null(), "the draft is still there"); + + let resp = delete("SECRET_TOKEN").await?; + assert_eq!(resp.status(), 404, "{}", resp.text().await?); + + // Without a username the delete takes every draft at the path. + for token in ["SECRET_TOKEN_2", "SECRET_TOKEN"] { + let resp = save(token).await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + } + let delete_all = |token: &'static str| { + client + .post(format!("{base}/delete_for_user/{path}")) + .header("Authorization", format!("Bearer {token}")) + .send() + }; + let resp = delete_all("SECRET_TOKEN_3").await?; + assert_eq!(resp.status(), 403, "{}", resp.text().await?); + let resp = delete_all("SECRET_TOKEN").await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + let left: i64 = sqlx::query_scalar( + "SELECT count(*) FROM draft WHERE workspace_id = 'test-workspace' AND path = 'u/test-user-2/theirs'", + ) + .fetch_one(&db) + .await?; + assert_eq!(left, 0, "drafts survived a path-wide delete"); + Ok(()) +} diff --git a/backend/tests/end_user_email.rs b/backend/tests/end_user_email.rs index 366c220c62..7fad5ab5ef 100644 --- a/backend/tests/end_user_email.rs +++ b/backend/tests/end_user_email.rs @@ -1,10 +1,8 @@ //! Tests for WM_END_USER_EMAIL environment variable. //! //! These tests verify that WM_END_USER_EMAIL is populated with the authenticated -//! user's email when executing app components. -//! -//! TODO: Add tests for scripts and flows once public execution endpoints are identified. -//! Currently only apps support non-workspace-member execution via OptAuthed + token lookup. +//! user's email when executing app components and when running scripts and flows directly. +//! Only apps support non-workspace-member execution via OptAuthed + token lookup. use serde_json::json; use sqlx::{Pool, Postgres}; @@ -19,6 +17,9 @@ const SAME_WS_EMAIL: &str = "test@windmill.dev"; const OTHER_WS_EMAIL: &str = "other-ws@windmill.dev"; const NO_WS_EMAIL: &str = "no-ws@windmill.dev"; +const GET_EMAIL_CONTENT: &str = + "export function main() { return process.env.WM_END_USER_EMAIL || \"\"; }"; + fn client() -> reqwest::Client { reqwest::Client::new() } @@ -27,40 +28,6 @@ fn authed(builder: reqwest::RequestBuilder, token: &str) -> reqwest::RequestBuil builder.header("Authorization", format!("Bearer {}", token)) } -// TODO: Script tests - need to identify public execution endpoints for non-workspace-members -// async fn run_script(port: u16, token: &str) -> anyhow::Result { -// let url = format!( -// "http://localhost:{}/api/w/test-workspace/jobs/run_wait_result/p/f/test/get_end_user_email", -// port -// ); -// let resp = authed(client().post(&url), token) -// .json(&json!({})) -// .send() -// .await?; -// if !resp.status().is_success() { -// anyhow::bail!("script run failed: {} - {}", resp.status(), resp.text().await?); -// } -// Ok(resp.json::().await? -// .as_str().unwrap_or("").to_string()) -// } - -// TODO: Flow tests - need to identify public execution endpoints for non-workspace-members -// async fn run_flow(port: u16, token: &str) -> anyhow::Result { -// let url = format!( -// "http://localhost:{}/api/w/test-workspace/jobs/run_wait_result/f/f/test/get_end_user_email_flow", -// port -// ); -// let resp = authed(client().post(&url), token) -// .json(&json!({})) -// .send() -// .await?; -// if !resp.status().is_success() { -// anyhow::bail!("flow run failed: {} - {}", resp.status(), resp.text().await?); -// } -// Ok(resp.json::().await? -// .as_str().unwrap_or("").to_string()) -// } - /// Create an app with inline script via API async fn create_app_with_inline_script(port: u16, path: &str) -> anyhow::Result<()> { let url = format!("http://localhost:{}/api/w/test-workspace/apps/create", port); @@ -74,9 +41,11 @@ async fn create_app_with_inline_script(port: u16, path: &str) -> anyhow::Result< "subgrids": {}, "hiddenInlineScripts": [{ "name": "get_email", - "language": "deno", - "content": "export function main() { return Deno.env.get(\"WM_END_USER_EMAIL\") || \"\"; }", - "path": "f/test/email_app/get_email" + "inlineScript": { + "language": "bun", + "content": GET_EMAIL_CONTENT, + "path": "f/test/email_app/get_email" + } }] }, "policy": { @@ -89,7 +58,7 @@ async fn create_app_with_inline_script(port: u16, path: &str) -> anyhow::Result< "one_of_inputs": {} }, // SHA256 hash of raw_code content for anonymous execution - "rawscript/6428aba5aa2d3ea8e1215bfdccbedd3718b18da7a239e3778a9787bb9a0ea606": { + "rawscript/894d2f85ea2411e777e7d5787366c9fec4c1a7a5f83482748f1d129196c9f54f": { "static_inputs": {}, "one_of_inputs": {} } @@ -118,11 +87,13 @@ async fn create_raw_app_with_inline_script(port: u16, path: &str) -> anyhow::Res "value": { "type": "rawapp", "css": "", - "inlineScripts": [{ - "name": "get_email", - "language": "deno", - "content": "export function main() { return Deno.env.get(\"WM_END_USER_EMAIL\") || \"\"; }" - }] + "runnables": { + "get_email": { + "name": "get_email", + "type": "inline", + "inlineScript": { "language": "bun", "content": GET_EMAIL_CONTENT } + } + } }, "policy": { "execution_mode": "anonymous", @@ -134,7 +105,7 @@ async fn create_raw_app_with_inline_script(port: u16, path: &str) -> anyhow::Res "one_of_inputs": {} }, // SHA256 hash of raw_code content for anonymous execution - "rawscript/6428aba5aa2d3ea8e1215bfdccbedd3718b18da7a239e3778a9787bb9a0ea606": { + "rawscript/894d2f85ea2411e777e7d5787366c9fec4c1a7a5f83482748f1d129196c9f54f": { "static_inputs": {}, "one_of_inputs": {} } @@ -219,7 +190,39 @@ async fn run_app_flow( wait_for_job_result(port, token, &job_id).await } -async fn run_app_inline_script( +fn find_inline_script_id(value: &serde_json::Value) -> Option { + match value { + serde_json::Value::Object(m) => m + .get("inlineScript") + .and_then(|s| s.get("id")) + .and_then(|id| id.as_i64()) + .or_else(|| m.values().find_map(find_inline_script_id)), + serde_json::Value::Array(a) => a.iter().find_map(find_inline_script_id), + _ => None, + } +} + +/// Once the app's dependency job writes the deployed lite value, inline code runs only through +/// the `app_script` rows it references, so the run must carry that row's id. +async fn deployed_inline_script_id(port: u16, app_path: &str) -> anyhow::Result { + let url = format!( + "http://localhost:{}/api/w/test-workspace/apps/get/lite/{}", + port, app_path + ); + for _ in 0..300 { + let resp = authed(client().get(&url), SAME_WS_TOKEN).send().await?; + if resp.status().is_success() { + let app = resp.json::().await?; + if let Some(id) = find_inline_script_id(&app["value"]) { + return Ok(id); + } + } + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + } + anyhow::bail!("timeout waiting for the deployed app_script id of {app_path}") +} + +async fn run_inline_script( port: u16, token: &str, app_path: &str, @@ -232,9 +235,10 @@ async fn run_app_inline_script( let mut payload = json!({ "args": {}, "component": "get_email", + "id": deployed_inline_script_id(port, app_path).await?, "raw_code": { - "language": "deno", - "content": "export function main() { return Deno.env.get(\"WM_END_USER_EMAIL\") || \"\"; }", + "language": "bun", + "content": GET_EMAIL_CONTENT, "path": format!("{}/get_email", app_path) } }); @@ -256,42 +260,6 @@ async fn run_app_inline_script( wait_for_job_result(port, token, &job_id).await } -async fn run_raw_app_inline_script( - port: u16, - token: &str, - app_path: &str, - force_viewer: bool, -) -> anyhow::Result { - let url = format!( - "http://localhost:{}/api/w/test-workspace/apps_u/execute_component/{}", - port, app_path - ); - let mut payload = json!({ - "args": {}, - "component": "get_email", - "raw_code": { - "language": "deno", - "content": "export function main() { return Deno.env.get(\"WM_END_USER_EMAIL\") || \"\"; }" - } - }); - if force_viewer { - payload["force_viewer_static_fields"] = json!({}); - } - let resp = authed(client().post(&url), token) - .json(&payload) - .send() - .await?; - if !resp.status().is_success() { - anyhow::bail!( - "raw app inline script run failed: {} - {}", - resp.status(), - resp.text().await? - ); - } - let job_id = resp.text().await?; - wait_for_job_result(port, token, &job_id).await -} - async fn wait_for_job_result(port: u16, token: &str, job_id: &str) -> anyhow::Result { let url = format!( "http://localhost:{}/api/w/test-workspace/jobs_u/completed/get_result/{}", @@ -312,41 +280,111 @@ async fn wait_for_job_result(port: u16, token: &str, job_id: &str) -> anyhow::Re anyhow::bail!("timeout waiting for job result") } -// TODO: Script tests - need to identify public execution endpoints for non-workspace-members -// #[cfg(feature = "deno_core")] -// #[sqlx::test(fixtures("base", "end_user_email"))] -// async fn test_script_wm_end_user_email(db: Pool) -> anyhow::Result<()> { -// initialize_tracing().await; -// set_jwt_secret().await; -// let server = ApiServer::start(db.clone()).await?; -// let port = server.addr.port(); -// -// in_test_worker(Connection::Sql(db.clone()), async move { -// let result = run_script(port, SAME_WS_TOKEN).await?; -// assert_eq!(result, SAME_WS_EMAIL, "same workspace user should get their email"); -// Ok::<(), anyhow::Error>(()) -// }, port).await?; -// -// Ok(()) -// } +async fn run_direct(port: u16, token: &str, route: &str) -> anyhow::Result { + let url = format!( + "http://localhost:{}/api/w/test-workspace/jobs/run/{}", + port, route + ); + let resp = authed(client().post(&url), token) + .json(&json!({})) + .send() + .await?; + if !resp.status().is_success() { + anyhow::bail!( + "run {route} failed: {} - {}", + resp.status(), + resp.text().await? + ); + } + let job_id = resp.text().await?; + wait_for_job_result(port, token, &job_id).await +} -// TODO: Flow tests - need to identify public execution endpoints for non-workspace-members -// #[cfg(feature = "deno_core")] -// #[sqlx::test(fixtures("base", "end_user_email"))] -// async fn test_flow_wm_end_user_email(db: Pool) -> anyhow::Result<()> { -// initialize_tracing().await; -// set_jwt_secret().await; -// let server = ApiServer::start(db.clone()).await?; -// let port = server.addr.port(); -// -// in_test_worker(Connection::Sql(db.clone()), async move { -// let result = run_flow(port, SAME_WS_TOKEN).await?; -// assert_eq!(result, SAME_WS_EMAIL, "same workspace user should get their email"); -// Ok::<(), anyhow::Error>(()) -// }, port).await?; -// -// Ok(()) -// } +#[cfg(feature = "deno_core")] +#[sqlx::test(fixtures("base", "end_user_email"))] +async fn test_direct_run_wm_end_user_email(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + set_jwt_secret().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + in_test_worker( + Connection::Sql(db.clone()), + async move { + let result = run_direct(port, SAME_WS_TOKEN, "p/f/test/get_end_user_email").await?; + assert_eq!(result, SAME_WS_EMAIL, "a script run should see its caller"); + + let result = + run_direct(port, SAME_WS_TOKEN, "f/f/test/get_end_user_email_flow").await?; + assert_eq!( + result, SAME_WS_EMAIL, + "every flow step should see the flow's caller" + ); + + Ok::<(), anyhow::Error>(()) + }, + port, + ) + .await?; + + Ok(()) +} + +/// A job's `WM_TOKEN` names the identity the job runs as, which differs from its end user when +/// the job runs on behalf of another account. A run it starts must keep the job's end user. +#[cfg(feature = "deno_core")] +#[sqlx::test(fixtures("base", "end_user_email"))] +async fn test_job_token_run_keeps_end_user_email(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + set_jwt_secret().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + let calling_job = uuid::Uuid::new_v4(); + sqlx::query( + "INSERT INTO job_perms (job_id, email, username, is_admin, is_operator, folders, groups, workspace_id, end_user_email) + VALUES ($1, 'test2@windmill.dev', 'test-user-2', false, false, '{}', '{}', 'test-workspace', $2)", + ) + .bind(calling_job) + .bind(SAME_WS_EMAIL) + .execute(&db) + .await?; + let wm_token = windmill_common::auth::create_jwt_token( + windmill_common::db::Authed { + email: "test2@windmill.dev".to_string(), + username: "test-user-2".to_string(), + is_admin: false, + is_operator: false, + groups: vec!["all".to_string()], + folders: vec![], + scopes: None, + token_prefix: None, + }, + "test-workspace", + 3600, + Some(calling_job), + None, + None, + None, + ) + .await?; + + in_test_worker( + Connection::Sql(db.clone()), + async move { + let result = run_direct(port, &wm_token, "p/f/test/get_end_user_email").await?; + assert_eq!( + result, SAME_WS_EMAIL, + "the calling job's end user, not its run-as identity" + ); + Ok::<(), anyhow::Error>(()) + }, + port, + ) + .await?; + + Ok(()) +} #[cfg(feature = "deno_core")] #[sqlx::test(fixtures("base", "end_user_email"))] @@ -365,21 +403,21 @@ async fn test_app_wm_end_user_email(db: Pool) -> anyhow::Result<()> { create_app_with_inline_script(port, app_path).await?; // Same workspace user (force_viewer mode works for workspace members) - let result = run_app_inline_script(port, SAME_WS_TOKEN, app_path, true).await?; + let result = run_inline_script(port, SAME_WS_TOKEN, app_path, true).await?; assert_eq!( result, SAME_WS_EMAIL, "same workspace user should get their email" ); // Other workspace user (uses app's anonymous policy + token lookup) - let result = run_app_inline_script(port, OTHER_WS_TOKEN, app_path, false).await?; + let result = run_inline_script(port, OTHER_WS_TOKEN, app_path, false).await?; assert_eq!( result, OTHER_WS_EMAIL, "other workspace user should get their email" ); // No workspace user (uses app's anonymous policy + token lookup) - let result = run_app_inline_script(port, NO_WS_TOKEN, app_path, false).await?; + let result = run_inline_script(port, NO_WS_TOKEN, app_path, false).await?; assert_eq!( result, NO_WS_EMAIL, "no workspace user should get their email" @@ -447,21 +485,21 @@ async fn test_raw_app_wm_end_user_email(db: Pool) -> anyhow::Result<() create_raw_app_with_inline_script(port, app_path).await?; // Same workspace user (force_viewer mode works for workspace members) - let result = run_raw_app_inline_script(port, SAME_WS_TOKEN, app_path, true).await?; + let result = run_inline_script(port, SAME_WS_TOKEN, app_path, true).await?; assert_eq!( result, SAME_WS_EMAIL, "same workspace user should get their email" ); // Other workspace user (uses app's anonymous policy + token lookup) - let result = run_raw_app_inline_script(port, OTHER_WS_TOKEN, app_path, false).await?; + let result = run_inline_script(port, OTHER_WS_TOKEN, app_path, false).await?; assert_eq!( result, OTHER_WS_EMAIL, "other workspace user should get their email" ); // No workspace user (uses app's anonymous policy + token lookup) - let result = run_raw_app_inline_script(port, NO_WS_TOKEN, app_path, false).await?; + let result = run_inline_script(port, NO_WS_TOKEN, app_path, false).await?; assert_eq!( result, NO_WS_EMAIL, "no workspace user should get their email" @@ -475,3 +513,98 @@ async fn test_raw_app_wm_end_user_email(db: Pool) -> anyhow::Result<() Ok(()) } + +/// Connecting to data tables as the viewer is honored on inline runnables only: a path runnable +/// is someone else's script, which must not read with the viewer's roles because the app's +/// policy entry for it says so. +#[sqlx::test(fixtures("base", "end_user_email"))] +async fn test_app_viewer_data_access_is_stamped_on_inline_runnables_only( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + set_jwt_secret().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let app_path = "f/test/viewer_data_access_app"; + let script_path = "script/f/test/get_end_user_email"; + + let resp = authed( + client().post(format!( + "http://localhost:{port}/api/w/test-workspace/apps/create" + )), + SAME_WS_TOKEN, + ) + .json(&json!({ + "path": app_path, + "summary": "", + "value": { "type": "app", "grid": [], "subgrids": {}, "hiddenInlineScripts": [] }, + "policy": { + "execution_mode": "anonymous", + "on_behalf_of": null, + "on_behalf_of_email": null, + "triggerables_v2": { + "rawscript/894d2f85ea2411e777e7d5787366c9fec4c1a7a5f83482748f1d129196c9f54f": { + "static_inputs": {}, "one_of_inputs": {}, "viewer_data_access": true + }, + (script_path): { + "static_inputs": {}, "one_of_inputs": {}, "viewer_data_access": true + } + } + } + })) + .send() + .await?; + anyhow::ensure!( + resp.status().is_success(), + "create app: {}", + resp.text().await? + ); + + let execute = |payload: serde_json::Value| async move { + let resp = authed( + client().post(format!( + "http://localhost:{port}/api/w/test-workspace/apps_u/execute_component/{app_path}" + )), + SAME_WS_TOKEN, + ) + .json(&payload) + .send() + .await?; + anyhow::ensure!( + resp.status().is_success(), + "execute: {}", + resp.text().await? + ); + Ok::<_, anyhow::Error>(resp.text().await?.trim_matches('"').parse::()?) + }; + let as_viewer = |job_id: uuid::Uuid| { + let db = db.clone(); + async move { + sqlx::query_scalar::<_, bool>( + "SELECT viewer_data_access FROM job_perms WHERE job_id = $1", + ) + .bind(job_id) + .fetch_one(&db) + .await + } + }; + + let inline = execute(json!({ + "args": {}, + "component": "get_email", + "raw_code": { + "language": "bun", + "content": "export function main() { return process.env.WM_END_USER_EMAIL || \"\"; }" + } + })) + .await?; + assert!(as_viewer(inline).await?); + + let path = + execute(json!({ "args": {}, "component": "run_script", "path": script_path })).await?; + assert!( + !as_viewer(path).await?, + "a path runnable connected as the viewer because its policy entry said so" + ); + Ok(()) +} diff --git a/backend/tests/error_handler.rs b/backend/tests/error_handler.rs deleted file mode 100644 index 4f58685221..0000000000 --- a/backend/tests/error_handler.rs +++ /dev/null @@ -1,413 +0,0 @@ -use sqlx::{Pool, Postgres}; - -use windmill_test_utils::*; - -/// Test that workspace error handler can be set and removed via database operations -#[cfg(feature = "deno_core")] -#[sqlx::test(fixtures("base"))] -async fn test_error_handler_settings(db: Pool) -> anyhow::Result<()> { - initialize_tracing().await; - - let _server = ApiServer::start(db.clone()).await?; - - // Initially error_handler should be NULL - let initial = sqlx::query_scalar!( - r#"SELECT error_handler->>'path' FROM workspace_settings WHERE workspace_id = 'test-workspace'"# - ) - .fetch_one(&db) - .await?; - assert!(initial.is_none()); - - // Set error handler with all options - sqlx::query!( - r#" - UPDATE workspace_settings - SET error_handler = '{"path": "script/f/test/error_handler", "extra_args": {"notify": true}, "muted_on_cancel": true, "muted_on_user_path": false}'::jsonb - WHERE workspace_id = 'test-workspace' - "# - ) - .execute(&db) - .await?; - - let after_set = sqlx::query_scalar!( - r#"SELECT error_handler->>'path' FROM workspace_settings WHERE workspace_id = 'test-workspace'"# - ) - .fetch_one(&db) - .await?; - assert_eq!(after_set, Some("script/f/test/error_handler".to_string())); - - // Verify extra_args - let extra_args = sqlx::query_scalar!( - r#"SELECT error_handler->'extra_args' FROM workspace_settings WHERE workspace_id = 'test-workspace'"# - ) - .fetch_one(&db) - .await?; - assert!(extra_args.is_some()); - - // Verify muted_on_cancel - let muted_on_cancel = sqlx::query_scalar!( - r#"SELECT (error_handler->>'muted_on_cancel')::boolean FROM workspace_settings WHERE workspace_id = 'test-workspace'"# - ) - .fetch_one(&db) - .await?; - assert_eq!(muted_on_cancel, Some(true)); - - // Verify muted_on_user_path - let muted_on_user_path = sqlx::query_scalar!( - r#"SELECT (error_handler->>'muted_on_user_path')::boolean FROM workspace_settings WHERE workspace_id = 'test-workspace'"# - ) - .fetch_one(&db) - .await?; - assert_eq!(muted_on_user_path, Some(false)); - - // Remove error handler - sqlx::query!( - r#" - UPDATE workspace_settings - SET error_handler = NULL - WHERE workspace_id = 'test-workspace' - "# - ) - .execute(&db) - .await?; - - let after_remove = sqlx::query_scalar!( - r#"SELECT error_handler->>'path' FROM workspace_settings WHERE workspace_id = 'test-workspace'"# - ) - .fetch_one(&db) - .await?; - assert!(after_remove.is_none()); - - Ok(()) -} - -/// Test that a failed job triggers the workspace error handler -#[cfg(all(feature = "deno_core", feature = "enterprise", feature = "private"))] -#[sqlx::test(fixtures("base"))] -async fn test_error_handler_triggered_on_failure(db: Pool) -> anyhow::Result<()> { - use windmill_common::jobs::JobPayload; - use windmill_common::runnable_settings::{ConcurrencySettings, DebouncingSettings}; - use windmill_common::scripts::{ScriptHash, ScriptLang}; - - initialize_tracing().await; - - let server = ApiServer::start(db.clone()).await?; - - // Create the error handler script - let error_handler_code = r#" -export async function main(path: string, email: string, job_id: string, is_flow: boolean, workspace_id: string, error: any) { - console.log("Error handler called for job:", job_id); - return { handled: true, original_path: path }; -} -"#; - - sqlx::query!( - r#" - INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock) - VALUES ('test-workspace', 1111111111, 'f/test/error_handler', $1, 'deno', 'script', 'test-user', '{}', 'Error handler script', 'Handles failed job completions', '') - "#, - error_handler_code - ) - .execute(&db) - .await?; - - // Create a script that will fail - let failing_script_code = "export function main() { throw new Error('intentional failure'); }"; - let failing_script_hash: i64 = 2222222222; - - sqlx::query!( - r#" - INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock) - VALUES ('test-workspace', $1, 'f/test/failing_script', $2, 'deno', 'script', 'test-user', '{}', 'Failing test script', 'A script that always fails', '') - "#, - failing_script_hash, - failing_script_code - ) - .execute(&db) - .await?; - - // Set up the error handler in workspace_settings - sqlx::query!( - r#" - UPDATE workspace_settings - SET error_handler = '{"path": "script/f/test/error_handler"}'::jsonb - WHERE workspace_id = 'test-workspace' - "# - ) - .execute(&db) - .await?; - - // Create the error_handler group - sqlx::query!( - r#" - INSERT INTO group_ (workspace_id, name, summary, extra_perms) - VALUES ('test-workspace', 'error_handler', 'The group the error handler acts on behalf of', '{"u/test-user": true}') - ON CONFLICT DO NOTHING - "# - ) - .execute(&db) - .await?; - - // Run the failing script - let completed_job = RunJob::from(JobPayload::ScriptHash { - hash: ScriptHash(failing_script_hash), - path: "f/test/failing_script".to_string(), - cache_ttl: None, - cache_ignore_s3_path: None, - dedicated_worker: None, - language: ScriptLang::Deno, - priority: None, - apply_preprocessor: false, - concurrency_settings: ConcurrencySettings::default(), - debouncing_settings: DebouncingSettings::default(), - labels: None, - job_token_scopes: None, - }) - .run_until_complete(&db, false, server.addr.port()) - .await; - - // Verify the job actually failed - assert!(!completed_job.success, "Job should have failed"); - - let main_job_id = completed_job.id; - - // Wait for the error handler job to be created - tokio::time::sleep(tokio::time::Duration::from_millis(500)).await; - - // Verify the error handler job was created - let error_handler_job = sqlx::query!( - r#" - SELECT - id, - runnable_path, - permissioned_as_email, - parent_job - FROM v2_job - WHERE workspace_id = 'test-workspace' - AND permissioned_as_email = 'error_handler@windmill.dev' - ORDER BY created_at DESC - LIMIT 1 - "# - ) - .fetch_optional(&db) - .await?; - - assert!( - error_handler_job.is_some(), - "Error handler job should have been created" - ); - - let handler_job = error_handler_job.unwrap(); - - assert_eq!( - handler_job.runnable_path.as_deref(), - Some("f/test/error_handler"), - "Error handler should run the configured script" - ); - assert_eq!( - handler_job.permissioned_as_email.as_str(), - "error_handler@windmill.dev", - "Error handler should run as error_handler user" - ); - assert_eq!( - handler_job.parent_job, - Some(main_job_id), - "Error handler should have the failed job as parent" - ); - - Ok(()) -} - -/// Test that error handler is NOT triggered when ws_error_handler_muted is set on the script -#[cfg(all(feature = "deno_core", feature = "enterprise", feature = "private"))] -#[sqlx::test(fixtures("base"))] -async fn test_error_handler_muted_on_script(db: Pool) -> anyhow::Result<()> { - use windmill_common::jobs::JobPayload; - use windmill_common::runnable_settings::{ConcurrencySettings, DebouncingSettings}; - use windmill_common::scripts::{ScriptHash, ScriptLang}; - - initialize_tracing().await; - - let server = ApiServer::start(db.clone()).await?; - - // Create the error handler script - sqlx::query!( - r#" - INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock) - VALUES ('test-workspace', 3333333333, 'f/test/error_handler', 'export function main() { return "handled"; }', 'deno', 'script', 'test-user', '{}', '', '', '') - "#, - ) - .execute(&db) - .await?; - - // Create a failing script with ws_error_handler_muted = true - let failing_script_hash: i64 = 4444444444; - sqlx::query!( - r#" - INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock, ws_error_handler_muted) - VALUES ('test-workspace', $1, 'f/test/muted_failing_script', 'export function main() { throw new Error("fail"); }', 'deno', 'script', 'test-user', '{}', '', '', '', true) - "#, - failing_script_hash, - ) - .execute(&db) - .await?; - - // Set up the error handler - sqlx::query!( - r#" - UPDATE workspace_settings - SET error_handler = '{"path": "script/f/test/error_handler"}'::jsonb - WHERE workspace_id = 'test-workspace' - "# - ) - .execute(&db) - .await?; - - sqlx::query!( - r#" - INSERT INTO group_ (workspace_id, name, summary, extra_perms) - VALUES ('test-workspace', 'error_handler', 'Error handler group', '{"u/test-user": true}') - ON CONFLICT DO NOTHING - "# - ) - .execute(&db) - .await?; - - // Run the muted failing script - let completed_job = RunJob::from(JobPayload::ScriptHash { - hash: ScriptHash(failing_script_hash), - path: "f/test/muted_failing_script".to_string(), - cache_ttl: None, - cache_ignore_s3_path: None, - dedicated_worker: None, - language: ScriptLang::Deno, - priority: None, - apply_preprocessor: false, - concurrency_settings: ConcurrencySettings::default(), - debouncing_settings: DebouncingSettings::default(), - labels: None, - job_token_scopes: None, - }) - .run_until_complete(&db, false, server.addr.port()) - .await; - - assert!(!completed_job.success, "Job should have failed"); - - // Wait and check that NO error handler job was created - tokio::time::sleep(tokio::time::Duration::from_millis(500)).await; - - let error_handler_job = sqlx::query_scalar!( - r#" - SELECT id - FROM v2_job - WHERE workspace_id = 'test-workspace' - AND permissioned_as_email = 'error_handler@windmill.dev' - "# - ) - .fetch_optional(&db) - .await?; - - assert!( - error_handler_job.is_none(), - "Error handler should NOT have been triggered for a muted script" - ); - - Ok(()) -} - -/// Test that error handler is NOT triggered on successful job completion -#[cfg(all(feature = "deno_core", feature = "enterprise", feature = "private"))] -#[sqlx::test(fixtures("base"))] -async fn test_error_handler_not_triggered_on_success(db: Pool) -> anyhow::Result<()> { - use windmill_common::jobs::JobPayload; - use windmill_common::runnable_settings::{ConcurrencySettings, DebouncingSettings}; - use windmill_common::scripts::{ScriptHash, ScriptLang}; - - initialize_tracing().await; - - let server = ApiServer::start(db.clone()).await?; - - // Create the error handler script - sqlx::query!( - r#" - INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock) - VALUES ('test-workspace', 5555555555, 'f/test/error_handler', 'export function main() { return "handled"; }', 'deno', 'script', 'test-user', '{}', '', '', '') - "#, - ) - .execute(&db) - .await?; - - // Create a successful script - let success_script_hash: i64 = 6666666666; - sqlx::query!( - r#" - INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock) - VALUES ('test-workspace', $1, 'f/test/success_script', 'export function main() { return "ok"; }', 'deno', 'script', 'test-user', '{}', '', '', '') - "#, - success_script_hash, - ) - .execute(&db) - .await?; - - // Set up the error handler - sqlx::query!( - r#" - UPDATE workspace_settings - SET error_handler = '{"path": "script/f/test/error_handler"}'::jsonb - WHERE workspace_id = 'test-workspace' - "# - ) - .execute(&db) - .await?; - - sqlx::query!( - r#" - INSERT INTO group_ (workspace_id, name, summary, extra_perms) - VALUES ('test-workspace', 'error_handler', 'Error handler group', '{"u/test-user": true}') - ON CONFLICT DO NOTHING - "# - ) - .execute(&db) - .await?; - - // Run the successful script - let completed_job = RunJob::from(JobPayload::ScriptHash { - hash: ScriptHash(success_script_hash), - path: "f/test/success_script".to_string(), - cache_ttl: None, - cache_ignore_s3_path: None, - dedicated_worker: None, - language: ScriptLang::Deno, - priority: None, - apply_preprocessor: false, - concurrency_settings: ConcurrencySettings::default(), - debouncing_settings: DebouncingSettings::default(), - labels: None, - job_token_scopes: None, - }) - .run_until_complete(&db, false, server.addr.port()) - .await; - - assert!(completed_job.success, "Job should have succeeded"); - - // Wait and check that NO error handler job was created - tokio::time::sleep(tokio::time::Duration::from_millis(500)).await; - - let error_handler_job = sqlx::query_scalar!( - r#" - SELECT id - FROM v2_job - WHERE workspace_id = 'test-workspace' - AND permissioned_as_email = 'error_handler@windmill.dev' - "# - ) - .fetch_optional(&db) - .await?; - - assert!( - error_handler_job.is_none(), - "Error handler should NOT have been triggered for a successful job" - ); - - Ok(()) -} diff --git a/backend/tests/fixtures/app_publisher_permit.sql b/backend/tests/fixtures/app_publisher_permit.sql new file mode 100644 index 0000000000..c169e53ec5 --- /dev/null +++ b/backend/tests/fixtures/app_publisher_permit.sql @@ -0,0 +1,10 @@ +-- A publisher-mode app owned by `test-user`, not shared with anyone, whose one +-- runnable is a deployed script. + +INSERT INTO script (workspace_id, created_by, content, schema, summary, description, path, hash, language, lock) VALUES + ('test-workspace', 'test-user', 'export async function main() { return "ok" }', '{}', '', '', 'u/test-user/hello', 7788101, 'deno', ''); + +INSERT INTO app (id, workspace_id, path, summary, policy, versions) VALUES + (999101, 'test-workspace', 'u/test-user/papp', 'publisher app', + '{"execution_mode": "publisher", "on_behalf_of": "u/test-user", "on_behalf_of_email": "test@windmill.dev", + "triggerables_v2": {"c:script/u/test-user/hello": {"static_inputs": {}, "one_of_inputs": {}}}}'::jsonb, '{}'); diff --git a/backend/tests/fixtures/end_user_email.sql b/backend/tests/fixtures/end_user_email.sql index 596d34e3e3..3b376525a4 100644 --- a/backend/tests/fixtures/end_user_email.sql +++ b/backend/tests/fixtures/end_user_email.sql @@ -40,9 +40,9 @@ VALUES (encode(sha256('NO_WS_TOKEN'::bytea), 'hex'), 'NO_WS_TOKE', 'NO_WS_TOKEN' INSERT INTO script (workspace_id, created_by, content, schema, summary, description, path, hash, language, lock, kind, extra_perms) VALUES ( 'test-workspace', 'test-user', - 'export function main() { return Deno.env.get("WM_END_USER_EMAIL") || ""; }', + 'export function main() { return process.env.WM_END_USER_EMAIL || ""; }', '{"$schema":"https://json-schema.org/draft/2020-12/schema","properties":{},"required":[],"type":"object"}', - 'Returns WM_END_USER_EMAIL', '', 'f/test/get_end_user_email', 900001, 'deno', '', 'script', + 'Returns WM_END_USER_EMAIL', '', 'f/test/get_end_user_email', 900001, 'bun', E'{}\n//bun.lock\n', 'script', '{"g/all": true}' ); @@ -51,7 +51,7 @@ INSERT INTO flow (workspace_id, summary, description, path, versions, schema, va VALUES ( 'test-workspace', 'Returns WM_END_USER_EMAIL', '', 'f/test/get_end_user_email_flow', '{900002}', '{"$schema":"https://json-schema.org/draft/2020-12/schema","properties":{},"required":[],"type":"object"}', - '{"modules": [{"id": "a", "value": {"type": "rawscript", "language": "deno", "content": "export function main() { return Deno.env.get(\"WM_END_USER_EMAIL\") || \"\"; }", "input_transforms": {}}}, {"id": "b", "value": {"type": "rawscript", "language": "deno", "content": "export function main() { return Deno.env.get(\"WM_END_USER_EMAIL\") || \"\"; }", "input_transforms": {}}}]}', + '{"modules": [{"id": "a", "value": {"type": "rawscript", "language": "bun", "content": "export function main() { return process.env.WM_END_USER_EMAIL || \"\"; }", "input_transforms": {}}}, {"id": "b", "value": {"type": "rawscript", "language": "bun", "content": "export function main() { return process.env.WM_END_USER_EMAIL || \"\"; }", "input_transforms": {}}}]}', 'test-user', '{"g/all": true}' ); @@ -60,6 +60,6 @@ INSERT INTO flow_version (id, workspace_id, path, schema, value, created_by) VALUES ( 900002, 'test-workspace', 'f/test/get_end_user_email_flow', '{"$schema":"https://json-schema.org/draft/2020-12/schema","properties":{},"required":[],"type":"object"}', - '{"modules": [{"id": "a", "value": {"type": "rawscript", "language": "deno", "content": "export function main() { return Deno.env.get(\"WM_END_USER_EMAIL\") || \"\"; }", "input_transforms": {}}}, {"id": "b", "value": {"type": "rawscript", "language": "deno", "content": "export function main() { return Deno.env.get(\"WM_END_USER_EMAIL\") || \"\"; }", "input_transforms": {}}}]}', + '{"modules": [{"id": "a", "value": {"type": "rawscript", "language": "bun", "content": "export function main() { return process.env.WM_END_USER_EMAIL || \"\"; }", "input_transforms": {}}}, {"id": "b", "value": {"type": "rawscript", "language": "bun", "content": "export function main() { return process.env.WM_END_USER_EMAIL || \"\"; }", "input_transforms": {}}}]}', 'test-user' ); diff --git a/backend/tests/fixtures/hello.sql b/backend/tests/fixtures/hello.sql index 962f6441d9..4c40ac3290 100644 --- a/backend/tests/fixtures/hello.sql +++ b/backend/tests/fixtures/hello.sql @@ -11,7 +11,7 @@ export function main(world: string) { '{"$schema":"https://json-schema.org/draft/2020-12/schema","properties":{"world":{"default":"world","description":"","type":"string"}},"required":[],"type":"object"}', '', '', -'f/system/hello', 123412, 'deno', ''); +'f/system/hello', 123412, 'bun', E'{}\n//bun.lock\n'); INSERT INTO public.script(workspace_id, created_by, content, schema, summary, description, path, hash, language, lock) VALUES ( 'test-workspace', @@ -28,7 +28,7 @@ export async function main(foo: string, bar: string) { '{"$schema":"https://json-schema.org/draft/2020-12/schema","properties":{"foo":{"default":null,"description":"","originalType":"string","type":"string"},"bar":{"default":null,"description":"","originalType":"string","type":"string"}},"required":["foo","bar"],"type":"object"}', '', '', -'f/system/hello_with_preprocessor', 123413, 'deno', ''); +'f/system/hello_with_preprocessor', 123413, 'bun', E'{}\n//bun.lock\n'); INSERT INTO public.script(workspace_id, created_by, content, schema, summary, description, path, hash, language, lock) VALUES ( 'test-workspace', @@ -140,7 +140,7 @@ INSERT INTO public.flow(workspace_id, summary, description, path, versions, sche 'f/system/hello_with_nodes_flow', '{1443253234253454}', '{"$schema":"https://json-schema.org/draft/2020-12/schema","properties":{"world":{"default":"world","description":"","type":"string"}},"required":[],"type":"object"}', -E'{"modules":[{"id":"a","value":{"type":"forloopflow","modules":[{"id":"b","value":{"type":"rawscript","content":"export function main(world: string) {\\n const greet = `Hello ${world}!`;\\n console.log(greet)\\n return greet\\n}\\n","language":"deno","input_transforms":{"world":{"type":"javascript","expr":"flow_input.iter.value"}},"is_trigger":false}},{"id":"c","value":{"type":"rawscript","content":"export function main(hello: string) {\\n const dareyou = `Did you just say \\"${hello}\\"??!`;\\n console.log(dareyou)\\n return dareyou\\n}","language":"deno","input_transforms":{"hello":{"type":"javascript","value":"${results.b}","expr":"`${results.b}`"}},"is_trigger":false}}],"iterator":{"type":"javascript","expr":"[''foo'', ''bar'', ''baz'']"},"skip_failures":true,"parallel":false}}],"same_worker":false}', +E'{"modules":[{"id":"a","value":{"type":"forloopflow","modules":[{"id":"b","value":{"type":"rawscript","content":"export function main(world: string) {\\n const greet = `Hello ${world}!`;\\n console.log(greet)\\n return greet\\n}\\n","language":"bun","input_transforms":{"world":{"type":"javascript","expr":"flow_input.iter.value"}},"is_trigger":false}},{"id":"c","value":{"type":"rawscript","content":"export function main(hello: string) {\\n const dareyou = `Did you just say \\"${hello}\\"??!`;\\n console.log(dareyou)\\n return dareyou\\n}","language":"bun","input_transforms":{"hello":{"type":"javascript","value":"${results.b}","expr":"`${results.b}`"}},"is_trigger":false}}],"iterator":{"type":"javascript","expr":"[''foo'', ''bar'', ''baz'']"},"skip_failures":true,"parallel":false}}],"same_worker":false}', 'system' ); @@ -149,7 +149,7 @@ INSERT INTO public.flow_version(id, workspace_id, path, schema, value, created_b 'test-workspace', 'f/system/hello_with_nodes_flow', '{"$schema":"https://json-schema.org/draft/2020-12/schema","properties":{"world":{"default":"world","description":"","type":"string"}},"required":[],"type":"object"}', -E'{"modules":[{"id":"a","value":{"type":"forloopflow","modules":[{"id":"b","value":{"type":"rawscript","content":"export function main(world: string) {\\n const greet = `Hello ${world}!`;\\n console.log(greet)\\n return greet\\n}\\n","language":"deno","input_transforms":{"world":{"type":"javascript","expr":"flow_input.iter.value"}},"is_trigger":false}},{"id":"c","value":{"type":"rawscript","content":"export function main(hello: string) {\\n const dareyou = `Did you just say \\"${hello}\\"??!`;\\n console.log(dareyou)\\n return dareyou\\n}","language":"deno","input_transforms":{"hello":{"type":"javascript","value":"${results.b}","expr":"`${results.b}`"}},"is_trigger":false}}],"iterator":{"type":"javascript","expr":"[''foo'', ''bar'', ''baz'']"},"skip_failures":true,"parallel":false}}],"same_worker":false}', +E'{"modules":[{"id":"a","value":{"type":"forloopflow","modules":[{"id":"b","value":{"type":"rawscript","content":"export function main(world: string) {\\n const greet = `Hello ${world}!`;\\n console.log(greet)\\n return greet\\n}\\n","language":"bun","input_transforms":{"world":{"type":"javascript","expr":"flow_input.iter.value"}},"is_trigger":false}},{"id":"c","value":{"type":"rawscript","content":"export function main(hello: string) {\\n const dareyou = `Did you just say \\"${hello}\\"??!`;\\n console.log(dareyou)\\n return dareyou\\n}","language":"bun","input_transforms":{"hello":{"type":"javascript","value":"${results.b}","expr":"`${results.b}`"}},"is_trigger":false}}],"iterator":{"type":"javascript","expr":"[''foo'', ''bar'', ''baz'']"},"skip_failures":true,"parallel":false}}],"same_worker":false}', 'system' ); @@ -160,7 +160,7 @@ INSERT INTO public.flow(workspace_id, summary, description, path, versions, sche 'f/system/hello_with_preprocessor', '{1443253234253456}', '{"$schema":"https://json-schema.org/draft/2020-12/schema","properties":{"foo":{"type":"string","description":"","default":""},"bar":{"type":"string","description":"","default":""}},"required":[],"type":"object","order":["foo","bar"]}', -E'{"modules":[{"id":"a","value":{"type":"rawscript","content":"export async function main(foo: string, bar: string) {\\n return ''Hello '' + foo + ''-'' + bar\\n}\\n","language":"deno","is_trigger":false,"input_transforms":{"bar":{"expr":"flow_input.bar","type":"javascript"},"foo":{"expr":"flow_input.foo","type":"javascript"}}}}],"preprocessor_module":{"id":"preprocessor","value":{"type":"rawscript","content":"export async function preprocessor(\\n\\twm_trigger: {\\n\\t\\tkind: ''http'' | ''email'' | ''webhook'' | ''websocket'' | ''kafka'' | ''nats'',\\n\\t\\thttp?: {\\n\\t\\t\\troute: string\\n\\t\\t\\tpath: string\\n\\t\\t\\tmethod: string\\n\\t\\t\\tparams: Record\\n\\t\\t\\tquery: Record\\n\\t\\t\\theaders: Record\\n\\t\\t},\\n\\t\\twebsocket?: {\\n\\t\\t\\turl: string\\n\\t\\t},\\n\\t\\tkafka?: {\\n\\t\\t\\tbrokers: string[]\\n\\t\\t\\ttopic: string\\n\\t\\t\\tgroup_id: string\\n\\t\\t},\\n\\t\\tnats?: {\\n\\t\\t\\tservers: string[]\\n\\t\\t\\tsubject: string\\n\\t\\t\\theaders?: Record\\n\\t\\t\\tstatus?: number\\n\\t\\t\\tdescription?: string\\n\\t\\t\\tlength: number\\n\\t\\t}\\n\\t},\\n) {\\n\\treturn {\\n\\t\\tfoo: ''bar'',\\n\\t\\tbar: ''baz''\\n\\t}\\n}","language":"deno","is_trigger":false,"input_transforms":{"wm_trigger":{"type":"static"}}}}}', +E'{"modules":[{"id":"a","value":{"type":"rawscript","content":"export async function main(foo: string, bar: string) {\\n return ''Hello '' + foo + ''-'' + bar\\n}\\n","language":"bun","is_trigger":false,"input_transforms":{"bar":{"expr":"flow_input.bar","type":"javascript"},"foo":{"expr":"flow_input.foo","type":"javascript"}}}}],"preprocessor_module":{"id":"preprocessor","value":{"type":"rawscript","content":"export async function preprocessor(\\n\\twm_trigger: {\\n\\t\\tkind: ''http'' | ''email'' | ''webhook'' | ''websocket'' | ''kafka'' | ''nats'',\\n\\t\\thttp?: {\\n\\t\\t\\troute: string\\n\\t\\t\\tpath: string\\n\\t\\t\\tmethod: string\\n\\t\\t\\tparams: Record\\n\\t\\t\\tquery: Record\\n\\t\\t\\theaders: Record\\n\\t\\t},\\n\\t\\twebsocket?: {\\n\\t\\t\\turl: string\\n\\t\\t},\\n\\t\\tkafka?: {\\n\\t\\t\\tbrokers: string[]\\n\\t\\t\\ttopic: string\\n\\t\\t\\tgroup_id: string\\n\\t\\t},\\n\\t\\tnats?: {\\n\\t\\t\\tservers: string[]\\n\\t\\t\\tsubject: string\\n\\t\\t\\theaders?: Record\\n\\t\\t\\tstatus?: number\\n\\t\\t\\tdescription?: string\\n\\t\\t\\tlength: number\\n\\t\\t}\\n\\t},\\n) {\\n\\treturn {\\n\\t\\tfoo: ''bar'',\\n\\t\\tbar: ''baz''\\n\\t}\\n}","language":"bun","is_trigger":false,"input_transforms":{"wm_trigger":{"type":"static"}}}}}', 'system' ); @@ -169,6 +169,6 @@ INSERT INTO public.flow_version(id, workspace_id, path, schema, value, created_b 'test-workspace', 'f/system/hello_with_preprocessor', '{"$schema":"https://json-schema.org/draft/2020-12/schema","properties":{"foo":{"type":"string","description":"","default":""},"bar":{"type":"string","description":"","default":""}},"required":[],"type":"object","order":["foo","bar"]}', -E'{"modules":[{"id":"a","value":{"type":"rawscript","content":"export async function main(foo: string, bar: string) {\\n return ''Hello '' + foo + ''-'' + bar\\n}\\n","language":"deno","is_trigger":false,"input_transforms":{"bar":{"expr":"flow_input.bar","type":"javascript"},"foo":{"expr":"flow_input.foo","type":"javascript"}}}}],"preprocessor_module":{"id":"preprocessor","value":{"type":"rawscript","content":"export async function preprocessor(\\n\\twm_trigger: {\\n\\t\\tkind: ''http'' | ''email'' | ''webhook'' | ''websocket'' | ''kafka'' | ''nats'',\\n\\t\\thttp?: {\\n\\t\\t\\troute: string\\n\\t\\t\\tpath: string\\n\\t\\t\\tmethod: string\\n\\t\\t\\tparams: Record\\n\\t\\t\\tquery: Record\\n\\t\\t\\theaders: Record\\n\\t\\t},\\n\\t\\twebsocket?: {\\n\\t\\t\\turl: string\\n\\t\\t},\\n\\t\\tkafka?: {\\n\\t\\t\\tbrokers: string[]\\n\\t\\t\\ttopic: string\\n\\t\\t\\tgroup_id: string\\n\\t\\t},\\n\\t\\tnats?: {\\n\\t\\t\\tservers: string[]\\n\\t\\t\\tsubject: string\\n\\t\\t\\theaders?: Record\\n\\t\\t\\tstatus?: number\\n\\t\\t\\tdescription?: string\\n\\t\\t\\tlength: number\\n\\t\\t}\\n\\t},\\n) {\\n\\treturn {\\n\\t\\tfoo: ''bar'',\\n\\t\\tbar: ''baz''\\n\\t}\\n}","language":"deno","is_trigger":false,"input_transforms":{"wm_trigger":{"type":"static"}}}}}', +E'{"modules":[{"id":"a","value":{"type":"rawscript","content":"export async function main(foo: string, bar: string) {\\n return ''Hello '' + foo + ''-'' + bar\\n}\\n","language":"bun","is_trigger":false,"input_transforms":{"bar":{"expr":"flow_input.bar","type":"javascript"},"foo":{"expr":"flow_input.foo","type":"javascript"}}}}],"preprocessor_module":{"id":"preprocessor","value":{"type":"rawscript","content":"export async function preprocessor(\\n\\twm_trigger: {\\n\\t\\tkind: ''http'' | ''email'' | ''webhook'' | ''websocket'' | ''kafka'' | ''nats'',\\n\\t\\thttp?: {\\n\\t\\t\\troute: string\\n\\t\\t\\tpath: string\\n\\t\\t\\tmethod: string\\n\\t\\t\\tparams: Record\\n\\t\\t\\tquery: Record\\n\\t\\t\\theaders: Record\\n\\t\\t},\\n\\t\\twebsocket?: {\\n\\t\\t\\turl: string\\n\\t\\t},\\n\\t\\tkafka?: {\\n\\t\\t\\tbrokers: string[]\\n\\t\\t\\ttopic: string\\n\\t\\t\\tgroup_id: string\\n\\t\\t},\\n\\t\\tnats?: {\\n\\t\\t\\tservers: string[]\\n\\t\\t\\tsubject: string\\n\\t\\t\\theaders?: Record\\n\\t\\t\\tstatus?: number\\n\\t\\t\\tdescription?: string\\n\\t\\t\\tlength: number\\n\\t\\t}\\n\\t},\\n) {\\n\\treturn {\\n\\t\\tfoo: ''bar'',\\n\\t\\tbar: ''baz''\\n\\t}\\n}","language":"bun","is_trigger":false,"input_transforms":{"wm_trigger":{"type":"static"}}}}}', 'system' ); diff --git a/backend/tests/fixtures/jobs_read_auth.sql b/backend/tests/fixtures/jobs_read_auth.sql index e32b777a74..e175a9c065 100644 --- a/backend/tests/fixtures/jobs_read_auth.sql +++ b/backend/tests/fixtures/jobs_read_auth.sql @@ -98,6 +98,32 @@ INSERT INTO public.v2_job_completed (id, workspace_id, duration_ms, status, resu ('18181818-1818-1818-1818-181818181818', 'test-workspace', 1000, 'success'::job_status, '{"agent": "AGENT_CHAT_RESULT"}'); +-- A lock job for flow `f/shared/flow1`, as `wmill generate-metadata` queues it, and the +-- token CI would lock with. +INSERT INTO token(token_hash, token_prefix, token, email, label, super_admin, scopes) VALUES ( + encode(sha256('RUN_SCOPED_DEPS_TOKEN'::bytea), 'hex'), 'RUN_DEPS_', 'RUN_SCOPED_DEPS_TOKEN', + 'test2@windmill.dev', 'lock token', false, + ARRAY['jobs:run:dependencies:f/shared/*'] +); +INSERT INTO public.v2_job ( + id, workspace_id, created_by, created_at, permissioned_as, permissioned_as_email, + kind, runnable_path, tag, visible_to_owner +) VALUES ( + '19191919-1919-1919-1919-191919191919', 'test-workspace', 'test-user-2', + '2023-01-01 00:00:00', 'u/test-user-2', 'test2@windmill.dev', + 'flowdependencies', 'f/shared/flow1', 'dependency', true +), ( + -- Queued by a broader token with `*` as its path, which the request body allows. + '20202020-2020-2020-2020-202020202020', 'test-workspace', 'test-user-2', + '2023-01-01 00:00:00', 'u/test-user-2', 'test2@windmill.dev', + 'dependencies', '*', 'dependency', true +); +INSERT INTO public.v2_job_completed (id, workspace_id, duration_ms, status, result) VALUES + ('19191919-1919-1919-1919-191919191919', 'test-workspace', 1000, 'success'::job_status, + '{"lock": "DEPS_RESULT"}'), + ('20202020-2020-2020-2020-202020202020', 'test-workspace', 1000, 'success'::job_status, + '{"lock": "WILDCARD_DEPS_RESULT"}'); + -- A token pairing an app scope with a run scope, as someone driving an app's components -- programmatically would build. `APP_INLINE_JOB` is an inline-script component run: no -- `jobs:run` scope can name its kind, so only the `apps:run` half puts it in reach. diff --git a/backend/tests/fixtures/mcp_resource_authz.sql b/backend/tests/fixtures/mcp_resource_authz.sql index ecf3f01dc3..17fcc553b9 100644 --- a/backend/tests/fixtures/mcp_resource_authz.sql +++ b/backend/tests/fixtures/mcp_resource_authz.sql @@ -23,3 +23,19 @@ VALUES ( '{}', 'test-user' ); + +-- MCP resource whose URL lives in a variable. The host only appears in the +-- variable, so an error naming it proves the reference was resolved. +INSERT INTO variable (workspace_id, path, value, is_secret, description, extra_perms) +VALUES ('test-workspace', 'u/test-user/mcp_url', 'https://mcp-from-var.invalid.windmill.test/key', false, '', '{}'); + +INSERT INTO resource (workspace_id, path, value, description, resource_type, extra_perms, created_by) +VALUES ( + 'test-workspace', + 'u/test-user/var_mcp', + '{"name": "var_mcp", "url": "$var:u/test-user/mcp_url"}', + 'MCP resource with its URL in a variable', + 'mcp', + '{}', + 'test-user' +); diff --git a/backend/tests/fixtures/schedule.sql b/backend/tests/fixtures/schedule.sql index 8d851369b0..999aa4770f 100644 --- a/backend/tests/fixtures/schedule.sql +++ b/backend/tests/fixtures/schedule.sql @@ -13,7 +13,7 @@ export async function main(fail: boolean = true) { '{"$schema":"https://json-schema.org/draft/2020-12/schema","properties":{"fail":{"default":true,"description":"","type":"boolean"}},"required":[],"type":"object"}', '', '', -'f/system/failing_script', 12349, 'deno', ''); +'f/system/failing_script', 12349, 'bun', E'{}\n//bun.lock\n'); INSERT INTO public.script(workspace_id, created_by, content, schema, summary, description, path, hash, language, lock) VALUES ( 'test-workspace', @@ -26,7 +26,7 @@ export async function main() { '{"$schema":"https://json-schema.org/draft/2020-12/schema","properties":{"path":{"default":null,"description":"","type":"string"},"schedule_path":{"default":null,"description":"","type":"string"},"error":{"default":null,"description":"","properties":{},"type":"object"}},"required":["path","schedule_path","error"],"type":"object"}', '', '', -'f/system/schedule_error_handler', 123410, 'deno', ''); +'f/system/schedule_error_handler', 123410, 'bun', E'{}\n//bun.lock\n'); INSERT INTO public.script(workspace_id, created_by, content, schema, summary, description, path, hash, language, lock) VALUES ( 'test-workspace', @@ -39,7 +39,7 @@ export async function main() { '{"$schema":"https://json-schema.org/draft/2020-12/schema","properties":{"path":{"default":null,"description":"","type":"string"},"schedule_path":{"default":null,"description":"","type":"string"},"previous_job_error":{"default":null,"description":"","type":"string"},"result":{"default":null,"description":"","type":"string"}},"required":["path","schedule_path","previous_job_error","result"],"type":"object"}', '', '', -'f/system/schedule_recovery_handler', 123411, 'deno', ''); +'f/system/schedule_recovery_handler', 123411, 'bun', E'{}\n//bun.lock\n'); INSERT INTO public.flow(workspace_id, summary, description, path, versions, schema, value, edited_by) VALUES ( 'test-workspace', diff --git a/backend/tests/fixtures/workspace_dependencies.sql b/backend/tests/fixtures/workspace_dependencies.sql deleted file mode 100644 index 9491f62e7c..0000000000 --- a/backend/tests/fixtures/workspace_dependencies.sql +++ /dev/null @@ -1,33 +0,0 @@ --- NOTE: Applied after workspace_dependencies_leafs.sql --- Python script that uses relative imports -INSERT INTO public.script(workspace_id, created_by, content, schema, summary, description, path, hash, language, lock) VALUES ( -'test-workspace', -'test-user', -' -from f.leafs.python import main as python_leaf - -def main(): - return {"python_import": python_leaf()}', -'{"$schema":"https://json-schema.org/draft/2020-12/schema","properties":{},"required":[],"type":"object"}', -'', -'', -'f/python_importer', 500005, 'python3', ''); - --- TypeScript script that uses relative imports -INSERT INTO public.script(workspace_id, created_by, content, schema, summary, description, path, hash, language, lock) VALUES ( -'test-workspace', -'test-user', -' -import { main as tsLeaf } from "./leafs/ts"; - -export async function main() { - return { ts_import: await tsLeaf() }; -}', -'{"$schema":"https://json-schema.org/draft/2020-12/schema","properties":{},"required":[],"type":"object"}', -'', -'', -'f/ts_importer', 500006, 'nativets', ''); - --- Dependency map entries -INSERT INTO dependency_map (workspace_id, importer_path, importer_kind, imported_path, importer_node_id) VALUES ('test-workspace', 'f/python_importer', 'script', 'f/leafs/python', ''); -INSERT INTO dependency_map (workspace_id, importer_path, importer_kind, imported_path, importer_node_id) VALUES ('test-workspace', 'f/ts_importer', 'script', 'f/leafs/ts', ''); diff --git a/backend/tests/fixtures/workspace_dependencies_leafs.sql b/backend/tests/fixtures/workspace_dependencies_leafs.sql deleted file mode 100644 index 3896cb4b00..0000000000 --- a/backend/tests/fixtures/workspace_dependencies_leafs.sql +++ /dev/null @@ -1,54 +0,0 @@ --- Basic leaf scripts in different languages -INSERT INTO public.script(workspace_id, created_by, content, schema, summary, description, path, hash, language, lock) VALUES ( -'test-workspace', -'test-user', -' -export async function main() { - return "TypeScript leaf"; -}', -'{"$schema":"https://json-schema.org/draft/2020-12/schema","properties":{},"required":[],"type":"object"}', -'', -'', -'f/leafs/ts', 500001, 'nativets', ''); - -INSERT INTO public.script(workspace_id, created_by, content, schema, summary, description, path, hash, language, lock) VALUES ( -'test-workspace', -'test-user', -' -package main - -import "fmt" - -func main() { - fmt.Println("Go leaf") -}', -'{"$schema":"https://json-schema.org/draft/2020-12/schema","properties":{},"required":[],"type":"object"}', -'', -'', -'f/leafs/go', 500002, 'go', ''); - -INSERT INTO public.script(workspace_id, created_by, content, schema, summary, description, path, hash, language, lock) VALUES ( -'test-workspace', -'test-user', -' -def main(): - return "Python leaf"', -'{"$schema":"https://json-schema.org/draft/2020-12/schema","properties":{},"required":[],"type":"object"}', -'', -'', -'f/leafs/python', 500003, 'python3', ''); - -INSERT INTO public.script(workspace_id, created_by, content, schema, summary, description, path, hash, language, lock) VALUES ( -'test-workspace', -'test-user', -' -', -'{"$schema":"https://json-schema.org/draft/2020-12/schema","properties":{},"required":[],"type":"object"}', -'', -'', -'f/leafs/php', 500004, 'php', ''); - diff --git a/backend/tests/flow_conversation_running_turn.rs b/backend/tests/flow_conversation_running_turn.rs index 392ff6f5cf..db8cf4d956 100644 --- a/backend/tests/flow_conversation_running_turn.rs +++ b/backend/tests/flow_conversation_running_turn.rs @@ -16,9 +16,17 @@ const CONV: Uuid = Uuid::from_u128(0x5eed); /// Takes the conversation for a turn, as a run does, without keeping what it writes. async fn take_conversation(db: &Pool) -> windmill_common::error::Result { let mut tx = db.begin().await?; - let result = - get_or_create_conversation_with_id(&mut tx, WS, "f/flow", "test-user", "t", CONV, false) - .await; + let result = get_or_create_conversation_with_id( + &mut tx, + WS, + "f/flow", + "test-user", + false, + "t", + CONV, + false, + ) + .await; tx.rollback().await?; result.map(|c| c.id) } diff --git a/backend/tests/flow_engine_parity.rs b/backend/tests/flow_engine_parity.rs index 3806bb2886..2d4f72f336 100644 --- a/backend/tests/flow_engine_parity.rs +++ b/backend/tests/flow_engine_parity.rs @@ -85,7 +85,7 @@ async fn test_flow_linear_input_transforms(db: Pool) -> anyhow::Result modules: vec![ flow_module("a", FlowModuleValue::RawScript { input_transforms: [static_input("x", 10), static_input("y", 5)].into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main(x: number, y: number) { return {sum: x + y, product: x * y, items: [1, 2, 3, 4, 5]}; @@ -105,7 +105,7 @@ export function main(x: number, y: number) { js_input("filtered", "results.a.items.filter(x => x > 2)"), js_input("from_flow_input", "flow_input.multiplier * results.a.sum"), ].into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main(total: number, doubled_items: number[], filtered: number[], from_flow_input: number) { return {total, doubled_items, filtered, from_flow_input}; @@ -157,7 +157,7 @@ async fn test_flow_forloop_complex_expressions(db: Pool) -> anyhow::Re "a", FlowModuleValue::RawScript { input_transforms: Default::default(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main() { return { @@ -199,7 +199,7 @@ export function main() { js_input("index", "flow_input.iter.index"), ] .into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main(user_name: string, user_score: number, bonus: number, index: number) { return {name: user_name, final_score: user_score + bonus, position: index}; @@ -261,7 +261,7 @@ async fn test_flow_branchone_conditions(db: Pool) -> anyhow::Result<() "a", FlowModuleValue::RawScript { input_transforms: Default::default(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main() { return {status: "premium", score: 95, items: [1, 2, 3]}; @@ -293,7 +293,7 @@ export function main() { js_input("score_from_a", "results.a.score"), ] .into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main(discount: number, score_from_a: number) { return {branch: "premium_high", discount, score_from_a}; @@ -320,7 +320,7 @@ export function main(discount: number, score_from_a: number) { "premium_low", FlowModuleValue::RawScript { input_transforms: Default::default(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main() { return {branch: "premium_low", discount: 10}; @@ -344,7 +344,7 @@ export function main() { "default_branch", FlowModuleValue::RawScript { input_transforms: Default::default(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main() { return {branch: "default", discount: 0}; @@ -398,7 +398,7 @@ async fn test_flow_previous_result_aggregation(db: Pool) -> anyhow::Re "a", FlowModuleValue::RawScript { input_transforms: Default::default(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main() { return {value: 10, items: [1, 2, 3]}; @@ -424,7 +424,7 @@ export function main() { ), ] .into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main(prev_value: number, prev_items_sum: number) { return {value: prev_value * 2, sum: prev_items_sum}; @@ -452,7 +452,7 @@ export function main(prev_value: number, prev_items_sum: number) { ), ] .into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main(a_value: number, b_value: number, b_sum: number, combined: number) { return {a_value, b_value, b_sum, combined}; @@ -504,7 +504,7 @@ async fn test_flow_nested_complexity(db: Pool) -> anyhow::Result<()> { modules: vec![ flow_module("data", FlowModuleValue::RawScript { input_transforms: Default::default(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main() { return { @@ -541,7 +541,7 @@ export function main() { js_input("values", "results.data.base_values.map(v => v * flow_input.iter.value.multiplier)"), js_input("sum", "results.data.base_values.reduce((a, b) => a + b, 0) * flow_input.iter.value.multiplier"), ].into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main(cat_name: string, multiplier: number, values: number[], sum: number) { return {category: cat_name, multiplier, computed_values: values, total: sum}; @@ -602,7 +602,7 @@ async fn test_flow_object_transformations(db: Pool) -> anyhow::Result< modules: vec![ flow_module("source", FlowModuleValue::RawScript { input_transforms: Default::default(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main() { return { @@ -633,7 +633,7 @@ export function main() { js_input("active_bonus", "results.source.config.activeBonus"), js_input("all_users", "results.source.users"), ].into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main(admins: string[], active_count: number, admin_bonus: number, active_bonus: number, all_users: any[]) { // Compute user_summary and total_bonus in the script since complex expressions in input_transforms @@ -702,7 +702,7 @@ async fn test_flow_skip_if_expressions(db: Pool) -> anyhow::Result<()> "check", FlowModuleValue::RawScript { input_transforms: Default::default(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main() { return {should_skip: true, value: 100}; @@ -722,7 +722,7 @@ export function main() { "maybe_skipped", FlowModuleValue::RawScript { input_transforms: [js_input("input_val", "results.check.value * 2")].into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main(input_val: number) { return {processed: input_val, was_run: true}; @@ -750,7 +750,7 @@ export function main(input_val: number) { js_input("prev", "previous_result"), ] .into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main(check_val: number, prev: any) { return {check_val, previous: prev}; @@ -799,7 +799,7 @@ async fn test_flow_template_literals(db: Pool) -> anyhow::Result<()> { modules: vec![ flow_module("data", FlowModuleValue::RawScript { input_transforms: Default::default(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main() { return { @@ -825,7 +825,7 @@ export function main() { js_input("upper_name", "results.data.firstName.toUpperCase()"), js_input("items_formatted", "`Items: ${results.data.items.map(i => i.charAt(0).toUpperCase() + i.slice(1)).join(', ')}`"), ].into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main(full_name: string, greeting: string, items_str: string, upper_name: string, items_formatted: string) { return {full_name, greeting, items_str, upper_name, items_formatted}; @@ -873,7 +873,7 @@ async fn test_flow_optional_chaining(db: Pool) -> anyhow::Result<()> { modules: vec![ flow_module("data", FlowModuleValue::RawScript { input_transforms: Default::default(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main() { return { @@ -905,7 +905,7 @@ export function main() { js_input("default_city", "results.data.partial_user?.address?.city ?? 'Unknown'"), js_input("default_country", "results.data.user?.address?.country ?? 'USA'"), ].into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main(city: string, missing_city: any, null_user_name: any, default_city: string, default_country: string) { return {city, missing_city, null_user_name, default_city, default_country}; @@ -955,7 +955,7 @@ async fn test_flow_parallel_forloop(db: Pool) -> anyhow::Result<()> { "data", FlowModuleValue::RawScript { input_transforms: Default::default(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main() { return {items: [1, 2, 3, 4, 5]}; @@ -990,7 +990,7 @@ export function main() { js_input("cubed", "flow_input.iter.value.value ** 3"), ] .into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main(original: number, squared: number, cubed: number) { return {original, squared, cubed}; @@ -1089,7 +1089,7 @@ async fn test_flow_env_access(db: Pool) -> anyhow::Result<()> { js_input("retry_count", "flow_env.CONFIG.retries"), js_input("has_auth", "flow_env.CONFIG.features.includes('auth')"), ].into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main(env_name: string, is_debug: boolean, timeout_val: number, api_url: string, retry_count: number, has_auth: boolean) { return {env_name, is_debug, timeout_val, api_url, retry_count, has_auth}; @@ -1158,7 +1158,7 @@ async fn test_flow_input_and_env_combined(db: Pool) -> anyhow::Result< // Conditional based on both js_input("multiplier", "flow_env.ENV === 'production' ? flow_input.prod_mult : 1"), ].into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main(effective_limit: number, env_prefix: string, is_prod: boolean, doubled_input: number, multiplier: number) { return {effective_limit, env_prefix, is_prod, doubled_input, final_value: doubled_input * multiplier}; @@ -1215,7 +1215,7 @@ async fn test_flow_results_optional_chaining(db: Pool) -> anyhow::Resu "a", FlowModuleValue::RawScript { input_transforms: Default::default(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main() { return { @@ -1287,7 +1287,7 @@ export function main() { ), ] .into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main( user_name: string, @@ -1361,7 +1361,7 @@ async fn test_flow_large_integers(db: Pool) -> anyhow::Result<()> { "a", FlowModuleValue::RawScript { input_transforms: Default::default(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main() { return { @@ -1401,7 +1401,7 @@ export function main() { ), ] .into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main( small: number, i32_max: number, over_i32: number, @@ -1459,7 +1459,7 @@ async fn test_flow_unicode_emoji(db: Pool) -> anyhow::Result<()> { modules: vec![ flow_module("a", FlowModuleValue::RawScript { input_transforms: Default::default(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main() { return { @@ -1489,7 +1489,7 @@ export function main() { js_input("mixed_upper", "results.a.mixed.toUpperCase()"), js_input("template", "`Welcome: ${results.a.greeting}`"), ].into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main( greeting: string, greeting_len: number, simple_str: string, has_world: boolean, @@ -1544,7 +1544,7 @@ async fn test_flow_complex_array_operations(db: Pool) -> anyhow::Resul modules: vec![ flow_module("a", FlowModuleValue::RawScript { input_transforms: Default::default(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main() { return { @@ -1585,7 +1585,7 @@ export function main() { js_input("first_three", "results.a.numbers.slice(0, 3)"), js_input("last_two", "results.a.numbers.slice(-2)"), ].into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main( sorted_asc: number[], sorted_desc: number[], active_names: string[], @@ -1651,7 +1651,7 @@ async fn test_flow_multiline_expressions(db: Pool) -> anyhow::Result<( modules: vec![ flow_module("a", FlowModuleValue::RawScript { input_transforms: Default::default(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main() { return { @@ -1710,7 +1710,7 @@ export function main() { } "#), ].into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main( subtotal: number, discounted_total: number, @@ -1768,7 +1768,7 @@ async fn test_flow_spread_with_results(db: Pool) -> anyhow::Result<()> modules: vec![ flow_module("a", FlowModuleValue::RawScript { input_transforms: Default::default(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main() { return { @@ -1803,7 +1803,7 @@ export function main() { // Combining multiple spreads js_input("combined", "{config: {...results.a.config}, tags: [...results.a.tags], source: 'flow'}"), ].into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main( merged_config: any, all_tags: string[], full_user: any, @@ -1869,7 +1869,7 @@ async fn test_flow_nested_forloop_results_access(db: Pool) -> anyhow:: "a", FlowModuleValue::RawScript { input_transforms: Default::default(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main() { return { @@ -1908,7 +1908,7 @@ export function main() { js_input("multiplier", "results.a.multiplier"), // Access outer step from inside for-loop ] .into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main(category: string, multiplier: number) { return { @@ -1939,7 +1939,7 @@ export function main(category: string, multiplier: number) { js_input("original_mult", "results.a.multiplier"), // Access outer step ] .into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main(items: any[], category: string, original_mult: number) { return { @@ -2013,7 +2013,7 @@ async fn test_flow_results_non_existent_step(db: Pool) -> anyhow::Resu "a", FlowModuleValue::RawScript { input_transforms: Default::default(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main() { return { value: 42 }; @@ -2050,7 +2050,7 @@ export function main() { ), ] .into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main( existing: number, @@ -2126,7 +2126,7 @@ async fn test_flow_env_skip_if_inside_branchone(db: Pool) -> anyhow::R "inner", FlowModuleValue::RawScript { input_transforms: Default::default(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main() { return {ran: true}; @@ -2156,7 +2156,7 @@ export function main() { "branch_marker", FlowModuleValue::RawScript { input_transforms: Default::default(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main() { return {marker: "branch-marker"}; @@ -2193,7 +2193,7 @@ export function main() { "after", FlowModuleValue::RawScript { input_transforms: [js_input("prev", "previous_result")].into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main(prev: any) { return {prev}; @@ -2258,7 +2258,7 @@ async fn test_flow_env_skip_if_nested_branchone(db: Pool) -> anyhow::R "leaf", FlowModuleValue::RawScript { input_transforms: Default::default(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main() { return {ran: true}; @@ -2282,7 +2282,7 @@ export function main() { "inner_marker", FlowModuleValue::RawScript { input_transforms: Default::default(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main() { return {marker: "inner"}; @@ -2337,7 +2337,7 @@ export function main() { "after", FlowModuleValue::RawScript { input_transforms: [js_input("prev", "previous_result")].into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main(prev: any) { return {prev}; @@ -2414,7 +2414,7 @@ async fn test_flow_env_complex_input_transform_in_branch(db: Pool) -> "Math.min(flow_env.LIMIT, 10) + flow_env.OFFSET", )] .into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main(value: number) { return {value}; @@ -2487,7 +2487,7 @@ async fn test_flow_env_skip_if_in_parallel_forloop(db: Pool) -> anyhow "marker", FlowModuleValue::RawScript { input_transforms: [js_input("i", "flow_input.iter.value")].into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main(i: number) { return {marker: i}; @@ -2508,7 +2508,7 @@ export function main(i: number) { "leaf", FlowModuleValue::RawScript { input_transforms: Default::default(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main() { return {ran: true}; @@ -2594,7 +2594,7 @@ async fn test_flow_env_imported_flow_uses_own_env(db: Pool) -> anyhow: "id": "leaf", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main(key: string) { return {key}; }", "input_transforms": { "key": { "type": "javascript", "expr": "flow_env.KEY" } @@ -2679,7 +2679,7 @@ async fn test_flow_env_imported_flow_inherits_when_unset(db: Pool) -> "id": "marker", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main() { return {marker: \"from-imported\"}; }", "input_transforms": {} } @@ -2688,7 +2688,7 @@ async fn test_flow_env_imported_flow_inherits_when_unset(db: Pool) -> "id": "leaf", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main() { return {ran: true}; }", "input_transforms": {} }, @@ -2791,7 +2791,7 @@ async fn test_flow_env_imported_flow_with_nested_branch(db: Pool) -> a "id": "marker", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main() { return {marker: \"from-imported-branch\"}; }", "input_transforms": {} } @@ -2800,7 +2800,7 @@ async fn test_flow_env_imported_flow_with_nested_branch(db: Pool) -> a "id": "leaf", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main() { return {ran: true}; }", "input_transforms": {} }, @@ -2932,13 +2932,13 @@ async fn test_flow_env_marks_sub_flows_only_without_ancestor_env( "parallel": true, "modules": [{ "id": "leaf", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main(key: any) { return key ?? null; }", "input_transforms": { "key": { "type": "javascript", "expr": "flow_env.KEY" } } }}, { "id": "tail", "value": { // A single simple step is inlined rather than stored as a flow node. "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main(prev: any) { return prev; }", "input_transforms": { "prev": { "type": "javascript", "expr": "results.leaf" } } }}] @@ -3024,7 +3024,7 @@ async fn test_flow_env_in_stop_after_if(db: Pool) -> anyhow::Result<() "first", FlowModuleValue::RawScript { input_transforms: Default::default(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main() { return {stage: "first"}; @@ -3052,7 +3052,7 @@ export function main() { "second", FlowModuleValue::RawScript { input_transforms: Default::default(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main() { return {stage: "second"}; @@ -3110,7 +3110,7 @@ async fn test_stop_after_if_error_include_result(db: Pool) -> anyhow:: "step", FlowModuleValue::RawScript { input_transforms: Default::default(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main() { return { userErrors: ["email taken"], ok: false }; @@ -3200,7 +3200,7 @@ async fn test_flow_env_in_retry_if(db: Pool) -> anyhow::Result<()> { "fails", FlowModuleValue::RawScript { input_transforms: Default::default(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main() { throw new Error("nope"); @@ -3274,7 +3274,7 @@ async fn test_flow_env_in_stop_after_all_iters_if(db: Pool) -> anyhow: "iter_step", FlowModuleValue::RawScript { input_transforms: [js_input("i", "flow_input.iter.value")].into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main(i: number) { return {iter: i}; @@ -3316,7 +3316,7 @@ export function main(i: number) { "after", FlowModuleValue::RawScript { input_transforms: Default::default(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main() { return {stage: "after-loop"}; @@ -3375,7 +3375,7 @@ async fn test_stop_after_all_iters_if_error_includes_result( "iter_step", FlowModuleValue::RawScript { input_transforms: [js_input("i", "flow_input.iter.value")].into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#" export function main(i: number) { return { iter: i }; @@ -3453,8 +3453,8 @@ async fn test_flow_expr_step_tag(db: Pool) -> anyhow::Result<()> { id, FlowModuleValue::RawScript { input_transforms: Default::default(), - language: ScriptLang::Deno, - content: "export function main() { return { lang: 'bun' } }".to_string(), + language: ScriptLang::Bun, + content: "export function main() { return { lang: 'python3' } }".to_string(), path: None, lock: None, tag: tag.map(str::to_string), @@ -3484,7 +3484,7 @@ async fn test_flow_expr_step_tag(db: Pool) -> anyhow::Result<()> { .bind(job.id) .fetch_one(&db) .await?; - assert_eq!(b_tag, "bun"); + assert_eq!(b_tag, "python3"); assert!(!job.success); let result = job.json_result().unwrap(); diff --git a/backend/tests/folder_default_permissioned_as.rs b/backend/tests/folder_default_permissioned_as.rs index 238d7cdb32..94d1d2fad5 100644 --- a/backend/tests/folder_default_permissioned_as.rs +++ b/backend/tests/folder_default_permissioned_as.rs @@ -680,6 +680,17 @@ async fn test_folder_default_permissioned_as(db: Pool) -> anyhow::Resu // 8. Stale rule — rule resolves to a user that does not exist // ======================================================================== + let resp = authed( + client().post(format!("{base}/scripts/create")), + "SECRET_TOKEN", + ) + .json(&new_script("f/prodfolder/stale/existing")) + .send() + .await?; + let status = resp.status(); + let existing_hash = resp.text().await?; + assert_eq!(status, 201, "script before the stale rule: {existing_hash}"); + let resp = authed( client().post(format!("{base}/folders/update/prodfolder")), "SECRET_TOKEN", @@ -719,6 +730,33 @@ async fn test_folder_default_permissioned_as(db: Pool) -> anyhow::Resu "error should identify the stale user: {body}" ); + // The default applies only to a first deploy, so it cannot fail a redeploy... + let mut redeploy = new_script("f/prodfolder/stale/existing"); + redeploy["content"] = json!("export async function main() { return 43; }"); + redeploy["parent_hash"] = json!(existing_hash); + let resp = authed( + client().post(format!("{base}/scripts/create")), + "SECRET_TOKEN", + ) + .json(&redeploy) + .send() + .await?; + assert_eq!( + resp.status(), + 201, + "stale rule must not block a redeploy: {}", + resp.text().await? + ); + // ...while a first deploy it would apply to still reports it. + let resp = authed( + client().post(format!("{base}/scripts/create")), + "SECRET_TOKEN", + ) + .json(&new_script("f/prodfolder/stale/new_script")) + .send() + .await?; + assert_eq!(resp.status(), 400, "stale rule should refuse a new script"); + // Non-matching paths in the same folder still work fine. let resp = authed( client().post(format!("{base}/schedules/create")), diff --git a/backend/tests/instance_config.rs b/backend/tests/instance_config.rs index 52ebbee7e7..18a7466637 100644 --- a/backend/tests/instance_config.rs +++ b/backend/tests/instance_config.rs @@ -237,7 +237,7 @@ async fn test_diff_global_settings_empty_string_routes_to_delete(db: Pool) { ..Default::default() }; - apply_settings_diff(&db, &diff).await.unwrap(); + apply_settings_diff(&db, &diff, &()).await.unwrap(); assert_eq!( get_global_setting(&db, "key_a").await, @@ -468,7 +468,7 @@ async fn test_apply_settings_diff_deletes_only(db: Pool) { ..Default::default() }; - apply_settings_diff(&db, &diff).await.unwrap(); + apply_settings_diff(&db, &diff, &()).await.unwrap(); assert!(get_global_setting(&db, "to_delete_1").await.is_none()); assert!(get_global_setting(&db, "to_delete_2").await.is_none()); @@ -489,7 +489,7 @@ async fn test_apply_settings_diff_upserts_and_deletes(db: Pool) { ..Default::default() }; - apply_settings_diff(&db, &diff).await.unwrap(); + apply_settings_diff(&db, &diff, &()).await.unwrap(); assert!(get_global_setting(&db, "old_key").await.is_none()); assert_eq!( @@ -503,7 +503,7 @@ async fn test_apply_settings_diff_empty_noop(db: Pool) { insert_global_setting(&db, "preexisting", serde_json::json!("value")).await; let diff = SettingsDiff::default(); - apply_settings_diff(&db, &diff).await.unwrap(); + apply_settings_diff(&db, &diff, &()).await.unwrap(); assert_eq!( get_global_setting(&db, "preexisting").await, @@ -525,7 +525,7 @@ async fn test_apply_settings_diff_upsert_overwrites(db: Pool) { ..Default::default() }; - apply_settings_diff(&db, &diff).await.unwrap(); + apply_settings_diff(&db, &diff, &()).await.unwrap(); assert_eq!( get_global_setting(&db, "overwrite_me").await, @@ -553,7 +553,7 @@ async fn test_apply_settings_diff_complex_json(db: Pool) { ..Default::default() }; - apply_settings_diff(&db, &diff).await.unwrap(); + apply_settings_diff(&db, &diff, &()).await.unwrap(); let stored = get_global_setting(&db, "complex_setting").await.unwrap(); assert_eq!(stored, complex_value); @@ -568,7 +568,7 @@ async fn test_apply_settings_diff_delete_nonexistent_is_noop(db: Pool) }; // Should not error - apply_settings_diff(&db, &diff).await.unwrap(); + apply_settings_diff(&db, &diff, &()).await.unwrap(); } // ======================================================================== @@ -589,7 +589,7 @@ async fn test_apply_configs_diff_upserts_with_prefix(db: Pool) { deletes: vec![], }; - apply_configs_diff(&db, &diff).await.unwrap(); + apply_configs_diff(&db, &diff, &()).await.unwrap(); let stored = get_config(&db, "worker__mygroup").await.unwrap(); assert_eq!(stored["init_bash"], "echo hi"); @@ -601,7 +601,7 @@ async fn test_apply_configs_diff_deletes_with_prefix(db: Pool) { let diff = ConfigsDiff { upserts: BTreeMap::new(), deletes: vec!["to_remove".to_string()] }; - apply_configs_diff(&db, &diff).await.unwrap(); + apply_configs_diff(&db, &diff, &()).await.unwrap(); assert!(get_config(&db, "worker__to_remove").await.is_none()); } @@ -619,7 +619,7 @@ async fn test_apply_configs_diff_upsert_overwrites(db: Pool) { deletes: vec![], }; - apply_configs_diff(&db, &diff).await.unwrap(); + apply_configs_diff(&db, &diff, &()).await.unwrap(); let stored = get_config(&db, "worker__grp").await.unwrap(); assert_eq!(stored, serde_json::json!({"new": true})); @@ -630,7 +630,7 @@ async fn test_apply_configs_diff_empty_noop(db: Pool) { insert_config(&db, "worker__keep", serde_json::json!({"keep": true})).await; let diff = ConfigsDiff::default(); - apply_configs_diff(&db, &diff).await.unwrap(); + apply_configs_diff(&db, &diff, &()).await.unwrap(); assert!(get_config(&db, "worker__keep").await.is_some()); } @@ -641,7 +641,7 @@ async fn test_apply_configs_diff_does_not_touch_non_worker_configs(db: Pool) { assert!(diff.upserts.contains_key("expose_metrics")); assert!(diff.deletes.is_empty()); - apply_settings_diff(&db, &diff).await.unwrap(); + apply_settings_diff(&db, &diff, &()).await.unwrap(); // Step 5: Read back and verify let config2 = InstanceConfig::from_db(&db).await.unwrap(); @@ -729,7 +729,7 @@ async fn test_roundtrip_replace_mode_deletes(db: Pool) { assert!(diff.deletes.contains(&"retention_period_secs".to_string())); assert!(diff.deletes.contains(&"expose_metrics".to_string())); - apply_settings_diff(&db, &diff).await.unwrap(); + apply_settings_diff(&db, &diff, &()).await.unwrap(); assert!(get_global_setting(&db, "retention_period_secs") .await @@ -782,7 +782,7 @@ async fn test_roundtrip_worker_configs(db: Pool) { assert!(diff.upserts.contains_key("gpu")); // new assert_eq!(diff.deletes, vec!["legacy".to_string()]); - apply_configs_diff(&db, &diff).await.unwrap(); + apply_configs_diff(&db, &diff, &()).await.unwrap(); // Verify let config2 = InstanceConfig::from_db(&db).await.unwrap(); @@ -820,7 +820,7 @@ async fn test_roundtrip_to_settings_map_from_db_consistency(db: Pool) let diff = SettingsDiff { upserts: map.into_iter().collect(), deletes: vec![], ..Default::default() }; - apply_settings_diff(&db, &diff).await.unwrap(); + apply_settings_diff(&db, &diff, &()).await.unwrap(); let config = InstanceConfig::from_db(&db).await.unwrap(); assert_eq!(config.global_settings.base_url, original.base_url); @@ -868,8 +868,8 @@ async fn test_idempotent_apply(db: Pool) { }; // Apply twice - apply_settings_diff(&db, &diff).await.unwrap(); - apply_settings_diff(&db, &diff).await.unwrap(); + apply_settings_diff(&db, &diff, &()).await.unwrap(); + apply_settings_diff(&db, &diff, &()).await.unwrap(); assert_eq!( get_global_setting(&db, "idem_key").await, @@ -1069,7 +1069,7 @@ async fn test_diff_apply_only_touches_changed_rows(db: Pool) { assert!(!diff.upserts.contains_key("unchanged_1")); assert!(!diff.upserts.contains_key("unchanged_2")); - apply_settings_diff(&db, &diff).await.unwrap(); + apply_settings_diff(&db, &diff, &()).await.unwrap(); // Verify all 4 settings present assert_eq!(count_global_settings(&db).await, 4); @@ -1148,7 +1148,7 @@ async fn test_replace_mode_protects_settings_in_integration(db: Pool) // But normal_setting should be deleted assert!(diff.deletes.contains(&"normal_setting".to_string())); - apply_settings_diff(&db, &diff).await.unwrap(); + apply_settings_diff(&db, &diff, &()).await.unwrap(); // Verify protected settings survived assert!(get_global_setting(&db, "ducklake_settings").await.is_some()); @@ -1196,7 +1196,7 @@ async fn test_jwt_secret_roundtrip_as_string_or_secret_ref(db: Pool) { let diff = SettingsDiff { upserts: map.into_iter().collect(), deletes: vec![], ..Default::default() }; - apply_settings_diff(&db, &diff).await.unwrap(); + apply_settings_diff(&db, &diff, &()).await.unwrap(); // Read back from DB — jwt_secret should survive the roundtrip let config = InstanceConfig::from_db(&db).await.unwrap(); @@ -1239,7 +1239,7 @@ async fn test_rsa_keys_roundtrip_via_extra(db: Pool) { let map = settings.to_settings_map(); let diff = SettingsDiff { upserts: map.into_iter().collect(), deletes: vec![], ..Default::default() }; - apply_settings_diff(&db, &diff).await.unwrap(); + apply_settings_diff(&db, &diff, &()).await.unwrap(); // Read back from DB let config = InstanceConfig::from_db(&db).await.unwrap(); @@ -1296,7 +1296,7 @@ async fn test_replace_mode_protects_jwt_secret_and_rsa_keys(db: Pool) "normal_setting should be deleted" ); - apply_settings_diff(&db, &diff).await.unwrap(); + apply_settings_diff(&db, &diff, &()).await.unwrap(); // Both protected settings survive assert_eq!( @@ -1371,7 +1371,7 @@ async fn test_alert_config_in_global_settings_roundtrip(db: Pool) { "alert_config change should be detected in diff" ); - apply_settings_diff(&db, &diff).await.unwrap(); + apply_settings_diff(&db, &diff, &()).await.unwrap(); // Re-read and verify the update let config2 = InstanceConfig::from_db(&db).await.unwrap(); @@ -1455,6 +1455,7 @@ async fn declarative_sync_rejects_an_unusable_webhook_base_url(db: Pool &db, &BTreeMap::new(), &desired, + &(), ) .await .expect_err("a javascript: banner link must fail the sync"); @@ -1530,6 +1533,32 @@ async fn declarative_sync_rejects_an_unusable_instance_banner(db: Pool ); } +#[sqlx::test(fixtures("base"))] +async fn declarative_sync_rejects_an_unusable_dev_workspace_tag_suffix(db: Pool) { + clear_settings_and_configs(&db).await; + let before = count_global_settings(&db).await; + + let mut desired = BTreeMap::new(); + desired.insert( + "dev_workspace_tag_suffix".to_string(), + serde_json::json!("-dev' OR '1'='1"), + ); + + let err = windmill_common::instance_config::sync_global_settings_declarative( + &db, + &BTreeMap::new(), + &desired, + &(), + ) + .await + .expect_err("a suffix the workers would ignore must fail the sync"); + assert!( + err.to_string().contains("dev_workspace_tag_suffix"), + "the error should name the offending setting, got: {err}" + ); + assert_eq!(count_global_settings(&db).await, before); +} + #[sqlx::test(fixtures("base"))] async fn declarative_sync_rejects_a_malformed_max_token_expiration(db: Pool) { clear_settings_and_configs(&db).await; @@ -1545,6 +1574,7 @@ async fn declarative_sync_rejects_a_malformed_max_token_expiration(db: Pool) { &db, &BTreeMap::new(), &desired, + &(), ) .await .expect_err("a non-hex accent color must fail the sync"); @@ -1681,7 +1717,109 @@ async fn declarative_sync_rejects_a_non_hex_accent_color(db: Pool) { &db, &BTreeMap::new(), &desired, + &(), ) .await .expect("a hex accent color must sync"); } + +/// A declarative sync has no user request behind it, so its observer is the only thing +/// that audits it: one entry per setting or worker config it actually writes, values +/// recorded under the API path's rule, and none for what it leaves as is. +#[cfg(all(feature = "enterprise", feature = "private"))] +#[sqlx::test(fixtures("base"))] +async fn test_declarative_sync_audits_only_what_it_writes(db: Pool) { + use windmill_audit::instance_config::{ + declarative_sync_author, DeclarativeSource, InstanceConfigAuditor, + }; + + insert_global_setting(&db, "retention_period_secs", serde_json::json!(100)).await; + insert_global_setting(&db, "expose_metrics", serde_json::json!(true)).await; + insert_global_setting(&db, "scim_token", serde_json::json!("old-scim-secret")).await; + insert_global_setting( + &db, + "npm_config_registry", + serde_json::json!("https://u:p@npm"), + ) + .await; + insert_config( + &db, + "worker__kept", + serde_json::json!({"worker_tags": ["a"]}), + ) + .await; + insert_config( + &db, + "worker__dropped", + serde_json::json!({"worker_tags": ["b"]}), + ) + .await; + + let config: windmill_common::instance_config::InstanceConfig = + serde_json::from_value(serde_json::json!({ + "global_settings": { + "retention_period_secs": 200, + "expose_metrics": true, + "scim_token": "new-scim-secret", + }, + "worker_configs": { + "kept": {"worker_tags": ["a"]}, + "added": {"init_bash": "export TOKEN=init-secret"}, + }, + })) + .unwrap(); + let author = declarative_sync_author(); + config + .sync_to_db( + &db, + &InstanceConfigAuditor { + db: &db, + author: &author, + source: Some(DeclarativeSource::SyncConfig), + }, + ) + .await + .unwrap(); + + let entries: Vec<(String, String, serde_json::Value)> = sqlx::query_as( + "SELECT operation, resource, parameters FROM audit_partitioned \ + WHERE workspace_id = 'global' AND username = $1 AND resource = ANY($2) \ + ORDER BY resource", + ) + .bind(&author.username) + .bind(vec![ + "retention_period_secs", + "expose_metrics", + "scim_token", + "npm_config_registry", + "worker__kept", + "worker__dropped", + "worker__added", + ]) + .fetch_all(&db) + .await + .unwrap(); + + let source = serde_json::json!({"source": "sync-config"}); + let entry = |operation: &str, resource: &str, parameters: &serde_json::Value| { + ( + operation.to_string(), + resource.to_string(), + parameters.clone(), + ) + }; + assert_eq!( + entries, + vec![ + entry("global_settings.delete", "npm_config_registry", &source), + entry( + "global_settings.update", + "retention_period_secs", + &serde_json::json!({"source": "sync-config", "value": "200"}), + ), + entry("global_settings.update", "scim_token", &source), + entry("worker_config.update", "worker__added", &source), + entry("worker_config.delete", "worker__dropped", &source), + ] + ); +} diff --git a/backend/tests/job_payload.rs b/backend/tests/job_payload.rs index 0038effc78..c40feb1650 100644 --- a/backend/tests/job_payload.rs +++ b/backend/tests/job_payload.rs @@ -54,7 +54,7 @@ mod job_payload { cache_ttl: None, cache_ignore_s3_path: None, dedicated_worker: None, - language: ScriptLang::Deno, + language: ScriptLang::Bun, priority: None, apply_preprocessor: false, job_token_scopes: None, @@ -85,7 +85,7 @@ mod job_payload { cache_ttl: None, cache_ignore_s3_path: None, dedicated_worker: None, - language: ScriptLang::Deno, + language: ScriptLang::Bun, priority: None, apply_preprocessor: true, concurrency_settings: @@ -165,7 +165,7 @@ mod job_payload { let test = || async { let result = RunJob::from(JobPayload::FlowScript { id: flow_scripts[0], - language: ScriptLang::Deno, + language: ScriptLang::Bun, concurrency_settings: windmill_common::runnable_settings::ConcurrencySettings::default(), cache_ttl: None, @@ -185,7 +185,7 @@ mod job_payload { let test = || async { let result = RunJob::from(JobPayload::FlowScript { id: flow_scripts[1], - language: ScriptLang::Deno, + language: ScriptLang::Bun, concurrency_settings: windmill_common::runnable_settings::ConcurrencySettings::default(), cache_ttl: None, @@ -263,7 +263,7 @@ mod job_payload { let result = RunJob::from(JobPayload::Dependencies { path: "f/system/hello".to_string(), hash: ScriptHash(123412), - language: ScriptLang::Deno, + language: ScriptLang::Bun, debouncing_settings: Default::default(), dedicated_worker: None, }) @@ -351,7 +351,7 @@ mod job_payload { console.log(greet) return greet }"#, - "language": "deno", + "language": "bun", "input_transforms": { "world": { "type": "javascript", "expr": "flow_input.world" } } @@ -407,7 +407,7 @@ mod job_payload { return greet }"# .into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, }) .run_until_complete(&db, false, port) .await @@ -416,7 +416,10 @@ mod job_payload { assert_eq!( result, - json!({ "lock": "", "status": "Successful lock file generation" }) + json!({ + "lock": "{\n \"dependencies\": {}\n}\n//bun.lock\n", + "status": "Successful lock file generation" + }) ); }; test_for_versions(VERSION_FLAGS.iter().copied(), test).await; @@ -626,7 +629,7 @@ mod job_payload { console.log(greet) return greet }"#, - "language": "deno", + "language": "bun", "input_transforms": { "world": { "type": "javascript", "expr": "flow_input.world" } } @@ -673,7 +676,7 @@ mod job_payload { "content": r#"export function main(world: string) { return `Hello ${world}!`; }"#, - "language": "deno", + "language": "bun", "input_transforms": { "world": { "type": "javascript", "expr": "flow_input.world" } } @@ -685,7 +688,7 @@ mod job_payload { "content": r#"export function main(world: string, a: string) { return `${a} ${world}!`; }"#, - "language": "deno", + "language": "bun", "input_transforms": { "world": { "type": "javascript", "expr": "flow_input.world" }, "a": { "type": "javascript", "expr": "results.a" } @@ -704,7 +707,7 @@ mod job_payload { "x": { "type": "javascript", "expr": "flow_input.iter.value" } }, "type": "rawscript", - "language": "deno", + "language": "bun", "content": r#"export function main(world: string, b: string, x: string) { return `${x}: ${b} ${world}!`; }"#, @@ -857,7 +860,7 @@ mod job_payload { "id": "a", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "input_transforms": { "world": { "type": "javascript", "expr": "flow_input.world" } }, @@ -874,7 +877,7 @@ mod job_payload { "id": "inner_first", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "input_transforms": { "world": { "type": "javascript", "expr": "flow_input.world" } }, @@ -884,7 +887,7 @@ mod job_payload { "id": "inner_second", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "input_transforms": { "world": { "type": "javascript", "expr": "flow_input.world" }, "first": { "type": "javascript", "expr": "results.inner_first" } @@ -1045,7 +1048,7 @@ mod job_payload { "id": "inner", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "input_transforms": { "iter_val": { "type": "javascript", "expr": "flow_input.iter.value" }, "tag": { "type": "javascript", "expr": "flow_input.tag" } @@ -1244,7 +1247,7 @@ mod job_payload { "id": "leaf", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "input_transforms": { "tag": { "type": "javascript", "expr": "flow_input.tag" }, "iv": { "type": "javascript", "expr": "flow_input.iter.value" } @@ -1388,7 +1391,7 @@ mod job_payload { "id": "leaf", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "input_transforms": { "tag": { "type": "javascript", "expr": "flow_input.tag" } }, diff --git a/backend/tests/job_s3_viewer_data_access.rs b/backend/tests/job_s3_viewer_data_access.rs new file mode 100644 index 0000000000..a68b695259 --- /dev/null +++ b/backend/tests/job_s3_viewer_data_access.rs @@ -0,0 +1,112 @@ +//! A job whose `job_perms.viewer_data_access` is set reads workspace object storage as its viewer: +//! the advanced permission rules are checked against the viewer, not the job's own identity, and +//! such a job with no viewer is refused rather than checked as itself. +//! +//! Advanced S3 permissions are an enterprise feature. +#![cfg(all(feature = "enterprise", feature = "private", feature = "parquet"))] + +use serde_json::json; +use sqlx::{Pool, Postgres}; +use uuid::Uuid; +use windmill_test_utils::*; + +/// A job of `test-user-3`, run for `viewer`, reading data as that viewer or not. +async fn job_token( + db: &Pool, + viewer: Option<&str>, + viewer_data_access: bool, +) -> anyhow::Result { + let id = Uuid::new_v4(); + sqlx::query( + "INSERT INTO v2_job (id, workspace_id, created_by, permissioned_as, permissioned_as_email, + kind, script_lang, runnable_path, tag) + VALUES ($1, 'test-workspace', 'test-user-3', 'u/test-user-3', 'test3@windmill.dev', + 'script', 'deno', 'u/test-user-3/app_runnable', 'deno')", + ) + .bind(id) + .execute(db) + .await?; + sqlx::query( + "INSERT INTO job_perms (job_id, email, username, is_admin, is_operator, folders, groups, + workspace_id, end_user_email, viewer_data_access) + VALUES ($1, 'test3@windmill.dev', 'test-user-3', false, false, '{}', '{}', + 'test-workspace', $2, $3)", + ) + .bind(id) + .bind(viewer) + .bind(viewer_data_access) + .execute(db) + .await?; + Ok(windmill_common::auth::create_token_for_owner( + db, + "test-workspace", + "u/test-user-3", + "ephemeral-script", + 300, + "test3@windmill.dev", + &id, + None, + None, + ) + .await?) +} + +#[sqlx::test(fixtures("base"))] +async fn a_job_reading_data_as_its_viewer_gets_the_viewers_storage_paths( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + set_jwt_secret().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + let storage_dir = tempfile::tempdir()?; + for user in ["test-user-2", "test-user-3"] { + let dir = storage_dir.path().join("u").join(user); + std::fs::create_dir_all(&dir)?; + std::fs::write(dir.join("file.txt"), user)?; + } + sqlx::query("UPDATE workspace_settings SET large_file_storage = $1 WHERE workspace_id = $2") + .bind(json!({ + "type": "FilesystemStorage", + "root_path": storage_dir.path().to_string_lossy(), + "public_resource": null, + "advanced_permissions": [{ "pattern": "u/{username}/**", "allow": "read" }] + })) + .bind("test-workspace") + .execute(&db) + .await?; + + let read = |token: String, user: &'static str| async move { + let resp = reqwest::Client::new() + .get(format!( + "http://localhost:{port}/api/w/test-workspace/job_helpers/download_s3_file" + )) + .query(&[("file_key", format!("u/{user}/file.txt"))]) + .bearer_auth(token) + .send() + .await?; + Ok::<_, anyhow::Error>(resp.status().is_success()) + }; + + let own = job_token(&db, Some("test2@windmill.dev"), false).await?; + assert!(read(own.clone(), "test-user-3").await?); + assert!( + !read(own, "test-user-2").await?, + "a job not reading as its viewer reached the viewer's paths" + ); + + let as_viewer = job_token(&db, Some("test2@windmill.dev"), true).await?; + assert!(read(as_viewer.clone(), "test-user-2").await?); + assert!( + !read(as_viewer, "test-user-3").await?, + "a job reading as its viewer kept its own identity's paths" + ); + + let no_viewer = job_token(&db, None, true).await?; + assert!( + !read(no_viewer, "test-user-3").await?, + "a job reading as a viewer it does not have was checked as itself" + ); + Ok(()) +} diff --git a/backend/tests/job_token_scopes.rs b/backend/tests/job_token_scopes.rs index f805168bfa..71ecaa444e 100644 --- a/backend/tests/job_token_scopes.rs +++ b/backend/tests/job_token_scopes.rs @@ -363,7 +363,8 @@ async fn test_deploy_without_the_field_keeps_the_restriction( Ok(()) } -/// The OIDC `job_token_scopes` claim states the scopes of the token that asked for it. +/// The OIDC `job_token_scopes` claim states the scopes of the token that asked for it, in a +/// payload that strict JSON parsers accept (no duplicate `email` key). #[cfg(all(feature = "enterprise", feature = "private", feature = "openidconnect"))] #[sqlx::test(fixtures("base"))] async fn test_oidc_claim_carries_the_presented_scopes(db: Pool) -> anyhow::Result<()> { @@ -404,10 +405,12 @@ async fn test_oidc_claim_carries_the_presented_scopes(db: Pool) -> any let status = resp.status(); let id_token = resp.text().await?; assert_eq!(status, StatusCode::OK, "{id_token}"); - let payload = id_token.split('.').nth(1).expect("a JWT payload"); - let claims: serde_json::Value = serde_json::from_slice( - &base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(payload)?, - )?; + let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD + .decode(id_token.split('.').nth(1).expect("a JWT payload"))?; + // serde_json keeps the last of duplicate keys, so count them on the raw payload. + let raw = String::from_utf8(payload.clone())?; + assert_eq!(raw.matches("\"email\":").count(), 1, "{raw}"); + let claims: serde_json::Value = serde_json::from_slice(&payload)?; assert_eq!(claims["job_token_scopes"], expected, "{job}"); } diff --git a/backend/tests/jobs_read_auth.rs b/backend/tests/jobs_read_auth.rs index 6a101200a1..bffacfbaf0 100644 --- a/backend/tests/jobs_read_auth.rs +++ b/backend/tests/jobs_read_auth.rs @@ -476,6 +476,44 @@ async fn test_single_job_read_authorization(db: Pool) -> anyhow::Resul ); } + // A lock job belongs to `jobs:run:dependencies`: its path is whatever the caller sent, + // so a token scoped to run the flow at that path must not read it. + let path = "completed/get_result/19191919-1919-1919-1919-191919191919"; + let (status, body) = get(&base, path, Some("RUN_SCOPED_DEPS_TOKEN")).await; + assert!( + status.is_success() && body.contains("DEPS_RESULT"), + "dependencies-scoped token must read its lock job (got {status}): {body}" + ); + let (status, body) = get(&base, path, Some("RUN_SCOPED_TOKEN")).await; + assert_eq!( + status, + reqwest::StatusCode::NOT_FOUND, + "a flow-scoped token must not read a lock job (got {status}): {body}" + ); + let (status, body) = get( + &base, + &format!("completed/get_result/{FLOW_JOB}"), + Some("RUN_SCOPED_DEPS_TOKEN"), + ) + .await; + assert_eq!( + status, + reqwest::StatusCode::NOT_FOUND, + "dependencies-scoped token must not read a flow run at its path (got {status}): {body}" + ); + // A lock job filed at `*` matches no path-scoped grant: the stored path is not a pattern. + let (status, body) = get( + &base, + "completed/get_result/20202020-2020-2020-2020-202020202020", + Some("RUN_SCOPED_DEPS_TOKEN"), + ) + .await; + assert_eq!( + status, + reqwest::StatusCode::NOT_FOUND, + "a path-scoped token must not read a lock job filed at `*` (got {status}): {body}" + ); + // An `apps:run:` scope is a start grant too: the inline-script component run it // launched — a kind no `jobs:run` scope can name — stays readable to a token scoped // to that app, and stays out of reach for one that is only scoped to run jobs. diff --git a/backend/tests/mcp_header_var_refs.rs b/backend/tests/mcp_header_var_refs.rs new file mode 100644 index 0000000000..270ae35449 --- /dev/null +++ b/backend/tests/mcp_header_var_refs.rs @@ -0,0 +1,146 @@ +//! An MCP resource header whose value is a `$var:` reference reaches the MCP +//! server as the variable's value, and only for a caller allowed to read it. +#![cfg(feature = "mcp")] + +use sqlx::{Pool, Postgres}; +use tokio::io::AsyncReadExt; +use windmill_common::client::AuthedClient; +use windmill_test_utils::*; +use windmill_worker::{load_mcp_tools, McpResourceConfig}; + +const SECRET_VALUE: &str = "S3CRET-MCP-HEADER-VALUE"; + +/// A secret variable and an MCP resource at `url` sending it as a header. +async fn seed(db: &Pool, url: &str) -> anyhow::Result<()> { + let mc = windmill_common::variables::build_crypt(db, "test-workspace").await?; + sqlx::query( + "INSERT INTO variable (workspace_id, path, value, is_secret, description, extra_perms) + VALUES ('test-workspace', 'u/test-user/header_secret', $1, true, '', '{}')", + ) + .bind(windmill_common::variables::encrypt(&mc, SECRET_VALUE)) + .execute(db) + .await?; + sqlx::query( + "INSERT INTO resource (workspace_id, path, value, resource_type, extra_perms, created_by) + VALUES ('test-workspace', 'u/test-user/mcp', $1, 'mcp', '{}', 'test-user')", + ) + .bind(serde_json::json!({ + "name": "mcp", + "url": url, + "headers": { "X-Api-Key": "$var:u/test-user/header_secret", "X-Plain": "plain" } + })) + .execute(db) + .await?; + Ok(()) +} + +#[sqlx::test(fixtures("base"))] +async fn test_mcp_header_var_ref_is_resolved(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + std::env::set_var("ALLOW_PRIVATE_MCP_SERVER_URLS", "true"); + + // Not an MCP server: it captures the first request and hangs up, so loading + // fails at the connect step after the headers were sent. + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; + let mcp_port = listener.local_addr()?.port(); + let first_request = tokio::spawn(async move { + let (mut socket, _) = listener.accept().await?; + let mut buf = vec![0u8; 16 * 1024]; + let n = socket.read(&mut buf).await?; + anyhow::Ok(String::from_utf8_lossy(&buf[..n]).to_lowercase()) + }); + seed(&db, &format!("http://127.0.0.1:{mcp_port}/mcp")).await?; + + let server = ApiServer::start(db.clone()).await?; + let client = AuthedClient::new( + format!("http://localhost:{}", server.addr.port()), + "test-workspace".to_string(), + "SECRET_TOKEN".to_string(), + None, + ); + let config = vec![McpResourceConfig { + resource_path: "$res:u/test-user/mcp".to_string(), + include_tools: None, + exclude_tools: None, + }]; + let _ = load_mcp_tools(&db, "test-workspace", config, &client).await; + + let request = first_request.await??; + assert!( + request.contains(&format!("x-api-key: {}", SECRET_VALUE.to_lowercase())), + "the header must carry the variable's value, not the reference: {request}" + ); + assert!(request.contains("x-plain: plain"), "{request}"); + + Ok(()) +} + +/// A token scoped to the resource alone must not have the API read the +/// variable a header points at. +#[sqlx::test(fixtures("base"))] +async fn test_mcp_header_var_ref_requires_variable_scope(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + seed(&db, "https://mcp.invalid.windmill.test").await?; + sqlx::query( + "INSERT INTO token (token_hash, token_prefix, token, email, label, super_admin, scopes) + VALUES (encode(sha256('RES_ONLY_TOKEN'::bytea), 'hex'), 'RES_ONLY_T', 'RES_ONLY_TOKEN', + 'test@windmill.dev', 'resources only', false, '{resources:read}')", + ) + .execute(&db) + .await?; + + let server = ApiServer::start(db.clone()).await?; + let resp = reqwest::Client::new() + .get(format!( + "http://localhost:{}/api/w/test-workspace/resources/mcp_tools/u/test-user/mcp", + server.addr.port() + )) + .header("Authorization", "Bearer RES_ONLY_TOKEN") + .send() + .await?; + let status = resp.status(); + let body = resp.text().await?; + assert_eq!(status, reqwest::StatusCode::FORBIDDEN, "{body}"); + assert!( + body.contains("variables:read:u/test-user/header_secret"), + "{body}" + ); + + // The token is held to the same scope, and a wildcard resource scope covers both. + sqlx::query( + "UPDATE resource SET value = jsonb_build_object('name', 'mcp', 'url', value->>'url', + 'token', '$var:u/test-user/header_secret') WHERE path = 'u/test-user/mcp'", + ) + .execute(&db) + .await?; + for (token, scope, denied) in [ + ("EXACT_TOKEN", "resources:read:u/test-user/mcp", true), + ("WILDCARD_TOKEN", "resources:read:u/test-user/*", false), + ] { + sqlx::query( + "INSERT INTO token (token_hash, token_prefix, token, email, label, super_admin, scopes) + VALUES (encode(sha256($1::bytea), 'hex'), left($1, 10), $1, + 'test@windmill.dev', 'scoped', false, ARRAY[$2])", + ) + .bind(token) + .bind(scope) + .execute(&db) + .await?; + let resp = reqwest::Client::new() + .get(format!( + "http://localhost:{}/api/w/test-workspace/resources/mcp_tools/u/test-user/mcp", + server.addr.port() + )) + .bearer_auth(token) + .send() + .await?; + let body = resp.text().await?; + assert_eq!( + body.contains("variables:read:u/test-user/header_secret"), + denied, + "{scope}: {body}" + ); + } + + Ok(()) +} diff --git a/backend/tests/mcp_resource_authz.rs b/backend/tests/mcp_resource_authz.rs index 0fa35933f4..6ccf5f4f2d 100644 --- a/backend/tests/mcp_resource_authz.rs +++ b/backend/tests/mcp_resource_authz.rs @@ -23,9 +23,9 @@ use windmill_common::client::AuthedClient; use windmill_test_utils::*; use windmill_worker::{load_mcp_tools, McpResourceConfig}; -fn config() -> Vec { +fn config(resource_path: &str) -> Vec { vec![McpResourceConfig { - resource_path: "$res:f/private/admin_mcp".to_string(), + resource_path: resource_path.to_string(), include_tools: None, exclude_tools: None, }] @@ -34,7 +34,16 @@ fn config() -> Vec { // The Ok variant ((HashMap<_, Arc>, Vec)) does not implement // Debug, so `expect_err` is unavailable — extract the error explicitly. async fn load_err(db: &Pool, client: &AuthedClient, ctx: &str) -> String { - match load_mcp_tools(db, "test-workspace", config(), client).await { + load_err_for(db, client, "$res:f/private/admin_mcp", ctx).await +} + +async fn load_err_for( + db: &Pool, + client: &AuthedClient, + resource_path: &str, + ctx: &str, +) -> String { + match load_mcp_tools(db, "test-workspace", config(resource_path), client).await { Ok(_) => panic!("{ctx}"), Err(e) => e.to_string(), } @@ -100,3 +109,31 @@ async fn test_mcp_resource_not_loaded_without_authorization( Ok(()) } + +/// A `$var:` in the resource's `url` is resolved before connecting, rather than +/// being handed to the client as a literal (and rejected as a relative URL). +#[sqlx::test(fixtures("base", "mcp_resource_authz"))] +async fn test_mcp_resource_url_variable_is_resolved(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + + let server = ApiServer::start(db.clone()).await?; + let client = AuthedClient::new( + format!("http://localhost:{}", server.addr.port()), + "test-workspace".to_string(), + "SECRET_TOKEN".to_string(), + None, + ); + let msg = load_err_for( + &db, + &client, + "$res:u/test-user/var_mcp", + "the variable's URL is non-resolvable, so the connect step must fail", + ) + .await; + assert!( + msg.contains("mcp-from-var.invalid.windmill.test"), + "the URL should come from the variable: {msg}" + ); + + Ok(()) +} diff --git a/backend/tests/otel.rs b/backend/tests/otel.rs index f1e042037f..30585c08a1 100644 --- a/backend/tests/otel.rs +++ b/backend/tests/otel.rs @@ -176,6 +176,10 @@ async fn test_all_metrics_e2e() { otel_set_worker_uptime("w-uptime", 3600.0); otel_set_health_status_phase("healthy"); otel_set_health_db_unresponsive(true); + otel_set_worker_memory("w-res", "gpu", Some(512), Some(128), Some(1024)); + otel_add_worker_cpu("w-res", "gpu", 1.5, 40, 7, 0.35); + otel_set_worker_occupancy_rate("w-res", "gpu", "5m", 0.25); + otel_record_job_memory_peak("python3", 100 * 1024 * 1024); // ── Histograms ────────────────────────────────────────────────── @@ -189,7 +193,7 @@ async fn test_all_metrics_e2e() { let metrics = flush_and_get_metrics(&state); let names = metric_names(&metrics); - // ── Verify all 21 metric names are present ────────────────────── + // ── Verify all metric names are present ───────────────────────── let expected = [ "windmill.queue.push_count", @@ -213,6 +217,15 @@ async fn test_all_metrics_e2e() { "windmill.worker.uptime", "windmill.health.status", "windmill.health.db_unresponsive", + "windmill.worker.memory_usage", + "windmill.worker.windmill_memory_usage", + "windmill.worker.memory_limit", + "windmill.worker.cpu_usage", + "windmill.worker.cpu_periods", + "windmill.worker.cpu_throttled_periods", + "windmill.worker.cpu_throttled_time", + "windmill.worker.occupancy_rate", + "windmill.worker.job_memory_peak", ]; for name in expected { assert!( @@ -290,6 +303,18 @@ async fn test_all_metrics_e2e() { .expect("worker.busy data point with worker=worker-test-1 not found"); assert_eq!(dp.1, 1); + let m = find_metric(&metrics, "windmill.worker.memory_limit").unwrap(); + let values = gauge_i64_values(m); + let dp = values + .iter() + .find(|(attrs, _)| { + attrs + .iter() + .any(|kv| kv.key.as_str() == "worker_group" && kv.value.as_str() == "gpu") + }) + .expect("worker.memory_limit data point with worker_group=gpu not found"); + assert_eq!(dp.1, 1024); + let m = find_metric(&metrics, "windmill.db.pool.active").unwrap(); assert_eq!(gauge_i64_values(m)[0].1, 5); let m = find_metric(&metrics, "windmill.db.pool.idle").unwrap(); diff --git a/backend/tests/protection_rules.rs b/backend/tests/protection_rules.rs index 6714b24801..bb9ef29fa2 100644 --- a/backend/tests/protection_rules.rs +++ b/backend/tests/protection_rules.rs @@ -686,3 +686,118 @@ async fn test_protection_rule_rename(db: Pool) -> anyhow::Result<()> { Ok(()) } + +/// `RequireIsolatedForks` refuses a non-bypassing forker any data shared with the workspace, on +/// both fork entry points, and lets an admin through. +#[sqlx::test(fixtures("base"))] +async fn test_require_isolated_forks(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + // Not `test-workspace`: PROTECTION_RULES_CACHE is process-wide and keyed by workspace id, so + // the other tests here, running concurrently on their own databases, would overwrite its rules. + invalidate_protection_rules_cache("iso-ws"); + // `dt2` is a clone governed from `gov`, but its database is this workspace's; `dt3` points + // into `gov`'s database. + let pg = r#"{"resource_type": "postgresql", "resource_path": "u/test-user/pg"}"#; + let gov = r#"{"workspace_id": "gov", "datatable": "src"}"#; + sqlx::raw_sql( + "INSERT INTO workspace (id, name, owner) VALUES + ('gov', 'gov', 'test-user'), ('iso-ws', 'iso-ws', 'test-user'); + INSERT INTO workspace_settings (workspace_id) VALUES ('gov'), ('iso-ws'); + INSERT INTO workspace_key (workspace_id, kind, key) VALUES ('iso-ws', 'cloud', 'iso-key'); + INSERT INTO group_ (workspace_id, name, summary, extra_perms) VALUES + ('iso-ws', 'all', 'All users', '{}'); + INSERT INTO usr (workspace_id, email, username, is_admin, role) VALUES + ('iso-ws', 'test@windmill.dev', 'test-user', true, 'Admin'), + ('iso-ws', 'test2@windmill.dev', 'test-user-2', false, 'User')", + ) + .execute(&db) + .await?; + for (w_id, datatables) in [ + ("gov", format!(r#"{{"src": {{"database": {pg}}}}}"#)), + ( + "iso-ws", + format!( + r#"{{"dt1": {{"database": {pg}}}, "dt2": {{"database": {pg}, "governed_by": {gov}}}, + "dt3": {{"reference": {gov}}}}}"# + ), + ), + ] { + sqlx::query( + "UPDATE workspace_settings SET datatable = jsonb_build_object('datatables', $2::jsonb) \ + WHERE workspace_id = $1", + ) + .bind(w_id) + .bind(datatables) + .execute(&db) + .await?; + } + + let server = ApiServer::start(db.clone()).await?; + let base = format!("http://localhost:{}/api/w/iso-ws", server.addr.port()); + let resp = authed( + client().post(format!("{base}/workspaces/protection_rules")), + "SECRET_TOKEN", + ) + .json(&json!({ + "name": "isolate", + "rules": ["RequireIsolatedForks"], + "bypass_users": [], + "bypass_groups": [] + })) + .send() + .await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + + let cloned = + json!([{"name": "dt1", "new_dbname": "wm_fork_iso__dt1", "fork_behavior": "schema_only"}]); + for (route, body, shared) in [ + ( + "create_fork", + json!({"shared_storages": ["_default_"], "forked_datatables": cloned}), + "storage", + ), + ( + "create_workspace_fork_branch", + json!({"shared_ducklakes": ["main"], "forked_datatables": cloned}), + "ducklake", + ), + ( + "create_fork", + json!({"forked_datatables": cloned}), + "data table `dt2`", + ), + ] { + let mut body = body; + body["id"] = json!("wm-fork-iso"); + body["name"] = json!("iso"); + let resp = authed( + client().post(format!("{base}/workspaces/{route}")), + "SECRET_TOKEN_2", + ) + .json(&body) + .send() + .await?; + let status = resp.status(); + let text = resp.text().await?; + assert!( + status == 403 && text.contains(shared) && !text.contains("dt3"), + "{route} sharing {shared} should be refused: {status} {text}" + ); + } + + // An admin bypasses the rule: what stops this request is the unknown storage name. + let resp = authed( + client().post(format!("{base}/workspaces/create_fork")), + "SECRET_TOKEN", + ) + .json(&json!({"id": "wm-fork-iso", "name": "iso", "shared_storages": ["_default_"]})) + .send() + .await?; + let text = resp.text().await?; + assert!( + !text.contains("isolate"), + "admin should bypass the rule: {text}" + ); + + Ok(()) +} diff --git a/backend/tests/relock_noop.rs b/backend/tests/relock_noop.rs index a480fc57ae..8760909be9 100644 --- a/backend/tests/relock_noop.rs +++ b/backend/tests/relock_noop.rs @@ -437,3 +437,609 @@ async fn multi_file_importer_relock_is_a_no_op_too(db: Pool) -> anyhow Ok(()) } + +/// Plants raw app `f/rel/app` with python runnables of the given contents, one of which imports +/// `f/rel/a`, as a version deployed before runnables were keyed by name: recorded under the +/// empty node id and each holding a lock already. Returns its published version. +async fn plant_raw_app_with( + db: &Pool, + runnables: &[(&str, &str)], +) -> anyhow::Result { + let runnables: serde_json::Map = runnables + .iter() + .map(|(id, content)| { + let runnable = serde_json::json!({ "type": "inline", "inlineScript": { + "content": content, "language": "python3", "lock": "# py: 3.12\n" + }}); + (id.to_string(), runnable) + }) + .collect(); + let app_id: i64 = sqlx::query_scalar( + "INSERT INTO app (workspace_id, path, summary, policy, versions, extra_perms) + VALUES ($1, 'f/rel/app', '', '{}'::jsonb, '{}', '{}'::jsonb) RETURNING id", + ) + .bind(W) + .fetch_one(db) + .await?; + let published: i64 = sqlx::query_scalar( + "INSERT INTO app_version (app_id, value, created_by, raw_app) + VALUES ($1, $2, 'test-user', true) RETURNING id", + ) + .bind(app_id) + .bind(serde_json::json!({ "runnables": runnables })) + .fetch_one(db) + .await?; + sqlx::query("UPDATE app SET versions = ARRAY[$1::bigint] WHERE id = $2") + .bind(published) + .bind(app_id) + .execute(db) + .await?; + sqlx::query( + "INSERT INTO dependency_map (workspace_id, importer_path, importer_kind, imported_path, importer_node_id) + VALUES ($1, 'f/rel/app', 'app', 'f/rel/a', '')", + ) + .bind(W) + .execute(db) + .await?; + Ok(published) +} + +/// [`plant_raw_app_with`] a single runnable `a` importing `f/rel/a`. +async fn plant_raw_app(db: &Pool) -> anyhow::Result { + plant_raw_app_with(db, &[("a", B)]).await +} + +async fn app_lock(db: &Pool, version: i64) -> Option { + runnable_lock(db, version, "a").await +} + +async fn runnable_lock(db: &Pool, version: i64, runnable: &str) -> Option { + sqlx::query_scalar( + "SELECT value->'runnables'->$2->'inlineScript'->>'lock' FROM app_version WHERE id = $1", + ) + .bind(version) + .bind(runnable) + .fetch_one(db) + .await + .unwrap() +} + +const WRITTEN_MEANWHILE: &str = "# py: 3.12\n# written meanwhile\n"; + +/// Once an app dependency job waits on the version row `writer` holds, rewrites that row's +/// lock of runnable `a` to [`WRITTEN_MEANWHILE`] and commits. +async fn write_once_waited_on( + db: &Pool, + mut writer: sqlx::Transaction<'_, Postgres>, + version: i64, +) { + wait_until_blocked(db, "SELECT value FROM app_version%").await; + sqlx::query( + "UPDATE app_version SET value = jsonb_set(value::jsonb, + '{runnables,a,inlineScript,lock}', to_jsonb($2::text))::json WHERE id = $1", + ) + .bind(version) + .bind(WRITTEN_MEANWHILE) + .execute(&mut *writer) + .await + .unwrap(); + writer.commit().await.unwrap(); +} + +/// Waits until a statement of this test's database matching `query` waits on a row lock. +async fn wait_until_blocked(db: &Pool, query: &str) { + let deadline = tokio::time::Instant::now() + WAIT_BUDGET; + loop { + let waiting: bool = sqlx::query_scalar( + "SELECT EXISTS (SELECT 1 FROM pg_stat_activity + WHERE datname = current_database() AND wait_event_type = 'Lock' AND query LIKE $1)", + ) + .bind(query) + .fetch_one(db) + .await + .unwrap(); + if waiting { + return; + } + assert!( + tokio::time::Instant::now() < deadline, + "nothing ever waited on a row lock for {query}" + ); + tokio::time::sleep(POLL).await; + } +} + +/// Queues a dependency job of `f/rel/app` at `version`: the deploy's own when `components` is +/// `None`, else a relative-import relock of those components. +async fn push_app_dependency_job(db: &Pool, version: i64, components: Option<&[&str]>) { + let payload = windmill_common::jobs::JobPayload::AppDependencies { + path: "f/rel/app".to_string(), + version, + debouncing_settings: Default::default(), + }; + let mut args = std::collections::HashMap::new(); + if let Some(components) = components { + args.insert( + "triggered_by_relative_import".to_string(), + serde_json::value::to_raw_value(&true).unwrap(), + ); + args.insert( + "components_to_relock".to_string(), + serde_json::value::to_raw_value(components).unwrap(), + ); + } + let (_, tx) = windmill_queue::push( + db, + windmill_queue::PushIsolationLevel::IsolatedRoot(db.clone()), + W, + payload, + windmill_queue::PushArgs { args: &args, extra: None }, + "test-user", + "test@windmill.dev", + "u/test-user".to_string(), + None, + None, + None, + None, + None, + None, + None, + None, + false, + false, + None, + true, + None, + None, + None, + None, + None, + false, + None, + None, + None, + None, + ) + .await + .unwrap(); + tx.commit().await.unwrap(); +} + +/// Logs of every dependency job of `f/rel/app` created after `since`, oldest first. +async fn app_dependency_logs( + db: &Pool, + since: chrono::DateTime, +) -> Vec { + sqlx::query_scalar( + "SELECT COALESCE(l.logs, '') FROM v2_job j + LEFT JOIN job_logs l ON l.job_id = j.id + WHERE j.kind = 'appdependencies' AND j.runnable_path = 'f/rel/app' AND j.created_at > $1 + ORDER BY j.created_at", + ) + .bind(since) + .fetch_all(db) + .await + .unwrap() +} + +/// A raw app runnable importing a script is relocked when that script's dependencies change, +/// and the relock lands in the version the app is served from rather than in a new one: a raw +/// app's bundle is stored under its version id. +#[sqlx::test(fixtures("base"))] +async fn raw_app_relock_rewrites_the_published_version(db: Pool) -> anyhow::Result<()> { + std::env::set_var("DEPENDENCY_JOB_DEBOUNCE_DELAY", "0"); + let (client, port, _s) = init_client(db.clone()).await; + let mut completed = listen_for_completed_jobs(&db).await; + let published = plant_raw_app(&db).await?; + + in_test_worker( + &db, + async { + client + .create_script(W, &py_script("f/rel/a", A, None)) + .await + .unwrap(); + wait_for_jobs(&db, &mut completed, 1).await; + + let a_hash = live(&versions(&db, "f/rel/a").await).hash; + client + .create_script( + W, + &py_script("f/rel/a", A_WITH_TINY, Some(format!("{a_hash:016x}"))), + ) + .await + .unwrap(); + wait_for_jobs(&db, &mut completed, 2).await; + + let (versions, version_rows): (Vec, i64) = sqlx::query_as( + "SELECT versions, (SELECT count(*) FROM app_version WHERE app_id = app.id) + FROM app WHERE workspace_id = $1 AND path = 'f/rel/app'", + ) + .bind(W) + .fetch_one(&db) + .await + .unwrap(); + assert_eq!(versions, [published], "the relock publishes no other version"); + assert_eq!(version_rows, 1, "the relock mints no version"); + + let lock = app_lock(&db, published).await; + assert!( + lock.as_deref().unwrap_or("").contains("tiny"), + "the published version carries the new lock: {lock:?}" + ); + + let node_ids: Vec = sqlx::query_scalar( + "SELECT importer_node_id FROM dependency_map + WHERE workspace_id = $1 AND importer_path = 'f/rel/app' AND imported_path = 'f/rel/a'", + ) + .bind(W) + .fetch_all(&db) + .await + .unwrap(); + assert_eq!(node_ids, ["a"], "the runnable is recorded under its name"); + }, + port, + ) + .await; + + Ok(()) +} + +/// A relock rewrites the one row every other relock of the app, and the dependency job of the +/// deploy that published it, write too. When that row changed after the relock read it, the +/// relock is discarded and queued again on what is there now, rather than overwriting it. +#[sqlx::test(fixtures("base"))] +async fn raw_app_relock_racing_a_write_requeues(db: Pool) -> anyhow::Result<()> { + std::env::set_var("DEPENDENCY_JOB_DEBOUNCE_DELAY", "0"); + let (client, port, _s) = init_client(db.clone()).await; + let mut completed = listen_for_completed_jobs(&db).await; + let published = plant_raw_app(&db).await?; + + in_test_worker( + &db, + async { + client + .create_script(W, &py_script("f/rel/a", A, None)) + .await + .unwrap(); + wait_for_jobs(&db, &mut completed, 1).await; + + let mut writer = db.begin().await.unwrap(); + sqlx::query("SELECT 1 FROM app_version WHERE id = $1 FOR NO KEY UPDATE") + .bind(published) + .execute(&mut *writer) + .await + .unwrap(); + + let since = chrono::Utc::now(); + let a_hash = live(&versions(&db, "f/rel/a").await).hash; + client + .create_script( + W, + &py_script("f/rel/a", A_WITH_TINY, Some(format!("{a_hash:016x}"))), + ) + .await + .unwrap(); + + write_once_waited_on(&db, writer, published).await; + + // The leaf's own job, the discarded relock and the one it queued. + wait_for_jobs(&db, &mut completed, 3).await; + + let logs = app_dependency_logs(&db, since).await; + assert_eq!(logs.len(), 2, "one relock and its requeue: {logs:?}"); + assert!( + logs[0].contains("discarding them"), + "the first relock was discarded: {}", + logs[0] + ); + let lock = app_lock(&db, published).await; + assert!( + lock.as_deref().unwrap_or("").contains("tiny"), + "the queued relock regenerated the lock over the concurrent write: {lock:?}" + ); + }, + port, + ) + .await; + + Ok(()) +} + +/// The dependency job of the deploy that published a version writes the row relocks write +/// too, so it backs off the same way when that row changed after it read it. +#[sqlx::test(fixtures("base"))] +async fn app_deploy_dependency_job_racing_a_write_requeues( + db: Pool, +) -> anyhow::Result<()> { + let (_client, port, _s) = init_client(db.clone()).await; + let mut completed = listen_for_completed_jobs(&db).await; + let published = plant_raw_app(&db).await?; + + in_test_worker( + &db, + async { + let mut writer = db.begin().await.unwrap(); + sqlx::query("SELECT 1 FROM app_version WHERE id = $1 FOR NO KEY UPDATE") + .bind(published) + .execute(&mut *writer) + .await + .unwrap(); + + let since = chrono::Utc::now(); + push_app_dependency_job(&db, published, None).await; + + write_once_waited_on(&db, writer, published).await; + + // The deploy's job, and the relock it queued on backing off. + wait_for_jobs(&db, &mut completed, 2).await; + + let logs = app_dependency_logs(&db, since).await; + assert_eq!(logs.len(), 2, "the deploy's job and its requeue: {logs:?}"); + assert!( + logs[0].contains("discarding them"), + "the deploy's job backed off: {}", + logs[0] + ); + }, + port, + ) + .await; + + Ok(()) +} + +/// A raw app runnable ships the runnables it imports as modules, and its lock covers what they +/// import, so a change to a script one of them imports relocks the importer too. +#[sqlx::test(fixtures("base"))] +async fn raw_app_relock_follows_imports_of_imported_runnables( + db: Pool, +) -> anyhow::Result<()> { + std::env::set_var("DEPENDENCY_JOB_DEBOUNCE_DELAY", "0"); + let (client, port, _s) = init_client(db.clone()).await; + let mut completed = listen_for_completed_jobs(&db).await; + let published = plant_raw_app_with( + &db, + &[ + ("a", "from .b import g\n\ndef main():\n return g()\n"), + ("b", "from f.rel.a import main as a\n\ndef g():\n return a()\n\ndef main():\n return g()\n"), + ], + ) + .await?; + + in_test_worker( + &db, + async { + // Its relock of the app records what each runnable depends on. + client + .create_script(W, &py_script("f/rel/a", A, None)) + .await + .unwrap(); + wait_for_jobs(&db, &mut completed, 1).await; + + let a_hash = live(&versions(&db, "f/rel/a").await).hash; + client + .create_script( + W, + &py_script("f/rel/a", A_WITH_TINY, Some(format!("{a_hash:016x}"))), + ) + .await + .unwrap(); + wait_for_jobs(&db, &mut completed, 2).await; + + for runnable in ["a", "b"] { + let lock = runnable_lock(&db, published, runnable).await; + assert!( + lock.as_deref().unwrap_or("").contains("tiny"), + "{runnable} carries the new lock: {lock:?}" + ); + } + + // A rebuilt dependency map records the same dependencies. + async fn app_edges(db: &Pool) -> Vec<(String, String)> { + sqlx::query_as( + "SELECT importer_node_id, imported_path FROM dependency_map + WHERE workspace_id = $1 AND importer_path = 'f/rel/app' ORDER BY 1, 2", + ) + .bind(W) + .fetch_all(db) + .await + .unwrap() + } + let recorded = app_edges(&db).await; + assert!(rebuild_dmap(&client).await); + assert_eq!(app_edges(&db).await, recorded); + }, + port, + ) + .await; + + Ok(()) +} + +/// A relock superseded by a deploy relocks the version that deploy published, every component +/// of it: the deploy may rename the component the relock was for, keeping its stale lock. +#[sqlx::test(fixtures("base"))] +async fn superseded_app_relock_relocks_the_renamed_component( + db: Pool, +) -> anyhow::Result<()> { + std::env::set_var("DEPENDENCY_JOB_DEBOUNCE_DELAY", "0"); + let (client, port, _s) = init_client(db.clone()).await; + let mut completed = listen_for_completed_jobs(&db).await; + plant_raw_app(&db).await?; + + in_test_worker( + &db, + async { + client + .create_script(W, &py_script("f/rel/a", A, None)) + .await + .unwrap(); + wait_for_jobs(&db, &mut completed, 1).await; + + let mut deploy = db.begin().await.unwrap(); + sqlx::query( + "SELECT 1 FROM app WHERE workspace_id = $1 AND path = 'f/rel/app' FOR NO KEY UPDATE", + ) + .bind(W) + .execute(&mut *deploy) + .await + .unwrap(); + + let a_hash = live(&versions(&db, "f/rel/a").await).hash; + client + .create_script( + W, + &py_script("f/rel/a", A_WITH_TINY, Some(format!("{a_hash:016x}"))), + ) + .await + .unwrap(); + + // The relock has generated its lock for `a` and waits on the app this deploy holds, + // which publishes `a` renamed to `b` with its old lock. + wait_until_blocked(&db, "SELECT versions[array_upper(versions, 1)] FROM app%").await; + let renamed: i64 = sqlx::query_scalar( + "INSERT INTO app_version (app_id, value, created_by, raw_app) + SELECT app_id, json_build_object('runnables', + json_build_object('b', value->'runnables'->'a')), created_by, true + FROM app_version WHERE id = (SELECT versions[array_upper(versions, 1)] FROM app + WHERE workspace_id = $1 AND path = 'f/rel/app') + RETURNING id", + ) + .bind(W) + .fetch_one(&mut *deploy) + .await + .unwrap(); + sqlx::query( + "UPDATE app SET versions = array_append(versions, $2) + WHERE workspace_id = $1 AND path = 'f/rel/app'", + ) + .bind(W) + .bind(renamed) + .execute(&mut *deploy) + .await + .unwrap(); + deploy.commit().await.unwrap(); + + // The leaf's own job, the superseded relock and the one it queued. + wait_for_jobs(&db, &mut completed, 3).await; + + let lock = runnable_lock(&db, renamed, "b").await; + assert!( + lock.as_deref().unwrap_or("").contains("tiny"), + "the renamed component carries the new lock: {lock:?}" + ); + }, + port, + ) + .await; + + Ok(()) +} + +/// A relock queued before a deploy runs on the version that deploy published, every component +/// of it: the deploy may rename the component the relock was queued for, keeping its stale lock. +#[sqlx::test(fixtures("base"))] +async fn app_relock_queued_before_a_deploy_relocks_the_renamed_component( + db: Pool, +) -> anyhow::Result<()> { + std::env::set_var("DEPENDENCY_JOB_DEBOUNCE_DELAY", "0"); + let (client, port, _s) = init_client(db.clone()).await; + let mut completed = listen_for_completed_jobs(&db).await; + let queued_for = plant_raw_app(&db).await?; + + in_test_worker( + &db, + async { + client + .create_script(W, &py_script("f/rel/a", A_WITH_TINY, None)) + .await + .unwrap(); + wait_for_jobs(&db, &mut completed, 1).await; + + let renamed: i64 = sqlx::query_scalar( + "INSERT INTO app_version (app_id, value, created_by, raw_app) + SELECT app_id, $2, created_by, true FROM app_version WHERE id = $1 + RETURNING id", + ) + .bind(queued_for) + .bind( + serde_json::json!({ "runnables": { "c": { "type": "inline", "inlineScript": { + "content": B, "language": "python3", "lock": "# py: 3.12\n" + }}}}), + ) + .fetch_one(&db) + .await + .unwrap(); + sqlx::query( + "UPDATE app SET versions = array_append(versions, $2) + WHERE workspace_id = $1 AND path = 'f/rel/app'", + ) + .bind(W) + .bind(renamed) + .execute(&db) + .await + .unwrap(); + + push_app_dependency_job(&db, queued_for, Some(&["a"])).await; + wait_for_jobs(&db, &mut completed, 1).await; + + let lock = runnable_lock(&db, renamed, "c").await; + assert!( + lock.as_deref().unwrap_or("").contains("tiny"), + "the renamed component carries the new lock: {lock:?}" + ); + }, + port, + ) + .await; + + Ok(()) +} + +/// A relock of every component regenerates each lock. A deploy that kept its editor's stale +/// lock still records the imports' current lock hashes, so the skip check would keep it. +#[sqlx::test(fixtures("base"))] +async fn app_relock_of_every_component_regenerates_a_kept_stale_lock( + db: Pool, +) -> anyhow::Result<()> { + std::env::set_var("DEPENDENCY_JOB_DEBOUNCE_DELAY", "0"); + let (client, port, _s) = init_client(db.clone()).await; + let mut completed = listen_for_completed_jobs(&db).await; + let published = plant_raw_app(&db).await?; + + in_test_worker( + &db, + async { + client + .create_script(W, &py_script("f/rel/a", A_WITH_TINY, None)) + .await + .unwrap(); + wait_for_jobs(&db, &mut completed, 1).await; + + // The stale lock a deploy kept, under the hashes it recorded. + sqlx::query( + "UPDATE app_version SET value = jsonb_set(value::jsonb, + '{runnables,a,inlineScript,lock}', '\"# py: 3.12\\n\"')::json WHERE id = $1", + ) + .bind(published) + .execute(&db) + .await + .unwrap(); + + let every = windmill_dep_map::trigger_dependents::RELOCK_ALL_APP_COMPONENTS; + push_app_dependency_job(&db, published, Some(&[every])).await; + wait_for_jobs(&db, &mut completed, 1).await; + + let lock = app_lock(&db, published).await; + assert!( + lock.as_deref().unwrap_or("").contains("tiny"), + "the kept stale lock is regenerated: {lock:?}" + ); + }, + port, + ) + .await; + + Ok(()) +} diff --git a/backend/tests/restart_at_step_api.rs b/backend/tests/restart_at_step_api.rs index 2b57de2c64..f6fc2a04d3 100644 --- a/backend/tests/restart_at_step_api.rs +++ b/backend/tests/restart_at_step_api.rs @@ -217,7 +217,7 @@ async fn test_api_restart_at_step_rejects_parallel_loop(db: Pool) -> a "id": "inner", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "input_transforms": {}, "content": "export function main() { return 'ok' }" } diff --git a/backend/tests/retry.rs b/backend/tests/retry.rs index e804b96f0e..d80e386b61 100644 --- a/backend/tests/retry.rs +++ b/backend/tests/retry.rs @@ -70,12 +70,20 @@ mod retry { fn inner_step() -> &'static str { r#" +import { connect } from "node:net"; + export async function main(index, port) { - const buf = new Uint8Array([0]); - const sock = await Deno.connect({ port }); - await sock.write(new Uint8Array([index])); - if (await sock.read(buf) != 1) throw Error("read"); - return buf[0]; + return await new Promise((resolve, reject) => { + const sock = connect({ port, host: "127.0.0.1" }, () => { + sock.write(new Uint8Array([index])); + }); + sock.on("data", (data) => { + resolve(data[0]); + sock.destroy(); + }); + sock.on("error", reject); + sock.on("close", () => reject(Error("read"))); + }); } "# } @@ -105,7 +113,7 @@ def main(last, port): "port": { "type": "javascript", "expr": "flow_input.port" }, }, "type": "rawscript", - "language": "deno", + "language": "bun", "content": inner_step(), }, }], @@ -281,7 +289,7 @@ def main(last, port): "value": { "input_transforms": {}, "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main() { return \"ok\" }", }, }, { @@ -293,7 +301,7 @@ def main(last, port): "port": { "type": "javascript", "expr": "flow_input.port" }, }, "type": "rawscript", - "language": "deno", + "language": "bun", "content": inner_step(), }, "retry": { "constant": { "attempts": 1, "seconds": 0 } }, diff --git a/backend/tests/s3_proxy_headers.rs b/backend/tests/s3_proxy_headers.rs new file mode 100644 index 0000000000..8f43f8c761 --- /dev/null +++ b/backend/tests/s3_proxy_headers.rs @@ -0,0 +1,29 @@ +//! Every s3_proxy response carries `nosniff` and the sandbox CSP, error responses included, +//! since the presigned route serves workspace objects from the app origin without a login. +#![cfg(all(feature = "enterprise", feature = "private", feature = "parquet"))] + +use sqlx::{Pool, Postgres}; +use windmill_test_utils::*; + +#[sqlx::test(fixtures("base"))] +async fn test_s3_proxy_sets_content_security_headers(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + let resp = reqwest::Client::new() + .get(format!( + "http://localhost:{port}/api/w/test-workspace/s3_proxy/_default_/x.html?exp=9999999999&sig=00" + )) + .send() + .await?; + + assert!(resp.status().is_client_error(), "status: {}", resp.status()); + assert_eq!(resp.headers()["x-content-type-options"], "nosniff"); + assert_eq!( + resp.headers()["content-security-policy"], + "sandbox allow-scripts allow-forms allow-popups allow-modals allow-downloads" + ); + Ok(()) +} diff --git a/backend/tests/success_handler.rs b/backend/tests/success_handler.rs deleted file mode 100644 index 8fc4182d9e..0000000000 --- a/backend/tests/success_handler.rs +++ /dev/null @@ -1,241 +0,0 @@ -use sqlx::{Pool, Postgres}; - -use windmill_test_utils::*; - -/// Test that the workspace success handler cache works correctly with 60s TTL -#[cfg(feature = "deno_core")] -#[sqlx::test(fixtures("base"))] -async fn test_success_handler_cache(db: Pool) -> anyhow::Result<()> { - initialize_tracing().await; - - // First, create a success handler script - let _server = ApiServer::start(db.clone()).await?; - - // Set up a success handler in workspace_settings using new JSONB column - sqlx::query!( - r#" - UPDATE workspace_settings - SET success_handler = '{"path": "script/f/test/success_handler", "extra_args": {"key": "value"}}'::jsonb - WHERE workspace_id = 'test-workspace' - "# - ) - .execute(&db) - .await?; - - // Verify the success handler was set - let result = sqlx::query_scalar!( - r#"SELECT success_handler->>'path' FROM workspace_settings WHERE workspace_id = 'test-workspace'"# - ) - .fetch_one(&db) - .await?; - - assert_eq!(result, Some("script/f/test/success_handler".to_string())); - - // Verify extra args were set - let extra_args = sqlx::query_scalar!( - r#"SELECT success_handler->'extra_args' FROM workspace_settings WHERE workspace_id = 'test-workspace'"# - ) - .fetch_one(&db) - .await?; - - assert!(extra_args.is_some()); - - Ok(()) -} - -/// Test that success handler can be set and removed via database operations -#[cfg(feature = "deno_core")] -#[sqlx::test(fixtures("base"))] -async fn test_success_handler_settings(db: Pool) -> anyhow::Result<()> { - initialize_tracing().await; - - let _server = ApiServer::start(db.clone()).await?; - - // Initially success_handler should be NULL - let initial = sqlx::query_scalar!( - r#"SELECT success_handler->>'path' FROM workspace_settings WHERE workspace_id = 'test-workspace'"# - ) - .fetch_one(&db) - .await?; - assert!(initial.is_none()); - - // Set success handler - sqlx::query!( - r#" - UPDATE workspace_settings - SET success_handler = '{"path": "flow/f/test/success_flow"}'::jsonb - WHERE workspace_id = 'test-workspace' - "# - ) - .execute(&db) - .await?; - - let after_set = sqlx::query_scalar!( - r#"SELECT success_handler->>'path' FROM workspace_settings WHERE workspace_id = 'test-workspace'"# - ) - .fetch_one(&db) - .await?; - assert_eq!(after_set, Some("flow/f/test/success_flow".to_string())); - - // Remove success handler - sqlx::query!( - r#" - UPDATE workspace_settings - SET success_handler = NULL - WHERE workspace_id = 'test-workspace' - "# - ) - .execute(&db) - .await?; - - let after_remove = sqlx::query_scalar!( - r#"SELECT success_handler->>'path' FROM workspace_settings WHERE workspace_id = 'test-workspace'"# - ) - .fetch_one(&db) - .await?; - assert!(after_remove.is_none()); - - Ok(()) -} - -/// Test that a successful job completion triggers the success handler -#[cfg(all(feature = "deno_core", feature = "enterprise", feature = "private"))] -#[sqlx::test(fixtures("base"))] -async fn test_success_handler_triggered_on_success(db: Pool) -> anyhow::Result<()> { - use serde_json::json; - use windmill_common::jobs::JobPayload; - use windmill_common::runnable_settings::{ConcurrencySettings, DebouncingSettings}; - use windmill_common::scripts::{ScriptHash, ScriptLang}; - - initialize_tracing().await; - - let server = ApiServer::start(db.clone()).await?; - - // Create a simple success handler script - // Note: lock must be non-null for script to be considered "deployed" - let success_handler_code = r#" -export async function main(path: string, email: string, job_id: string, is_flow: boolean, workspace_id: string, result: any) { - console.log("Success handler called for job:", job_id); - return { handled: true, original_path: path }; -} -"#; - - sqlx::query!( - r#" - INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock) - VALUES ('test-workspace', 1234567890, 'f/test/success_handler', $1, 'deno', 'script', 'test-user', '{}', 'Success handler script', 'Handles successful job completions', '') - "#, - success_handler_code - ) - .execute(&db) - .await?; - - // Create a simple test script that we'll run (needs to be JobKind::Script, not Preview) - // Note: lock must be non-null for script to be considered "deployed" - let test_script_code = "export function main() { return 'success'; }"; - let test_script_hash: i64 = 9876543210; - - sqlx::query!( - r#" - INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock) - VALUES ('test-workspace', $1, 'f/test/simple_script', $2, 'deno', 'script', 'test-user', '{}', 'Simple test script', 'A simple test script', '') - "#, - test_script_hash, - test_script_code - ) - .execute(&db) - .await?; - - // Set up the success handler in workspace_settings - sqlx::query!( - r#" - UPDATE workspace_settings - SET success_handler = '{"path": "script/f/test/success_handler"}'::jsonb - WHERE workspace_id = 'test-workspace' - "# - ) - .execute(&db) - .await?; - - // Create the success_handler group - sqlx::query!( - r#" - INSERT INTO group_ (workspace_id, name, summary, extra_perms) - VALUES ('test-workspace', 'success_handler', 'The group the success handler acts on behalf of', '{"u/test-user": true}') - ON CONFLICT DO NOTHING - "# - ) - .execute(&db) - .await?; - - // Run a script using ScriptHash (produces JobKind::Script, not Preview) - let completed_job = RunJob::from(JobPayload::ScriptHash { - hash: ScriptHash(test_script_hash), - path: "f/test/simple_script".to_string(), - cache_ttl: None, - cache_ignore_s3_path: None, - dedicated_worker: None, - language: ScriptLang::Deno, - priority: None, - apply_preprocessor: false, - concurrency_settings: ConcurrencySettings::default(), - debouncing_settings: DebouncingSettings::default(), - labels: None, - job_token_scopes: None, - }) - .run_until_complete(&db, false, server.addr.port()) - .await; - - let result = completed_job.json_result().unwrap(); - assert_eq!(result, json!("success")); - - let main_job_id = completed_job.id; - - // Wait a short time for the success handler job to be created - tokio::time::sleep(tokio::time::Duration::from_millis(500)).await; - - // Verify the success handler job was created (query by email since trigger is not set) - let success_handler_job = sqlx::query!( - r#" - SELECT - id, - runnable_path, - permissioned_as_email, - parent_job - FROM v2_job - WHERE workspace_id = 'test-workspace' - AND permissioned_as_email = 'success_handler@windmill.dev' - ORDER BY created_at DESC - LIMIT 1 - "# - ) - .fetch_optional(&db) - .await?; - - assert!( - success_handler_job.is_some(), - "Success handler job should have been created" - ); - - let handler_job = success_handler_job.unwrap(); - - // Verify the success handler job has correct parameters - assert_eq!( - handler_job.runnable_path.as_deref(), - Some("f/test/success_handler"), - "Success handler should run the configured script" - ); - assert_eq!( - handler_job.permissioned_as_email.as_str(), - "success_handler@windmill.dev", - "Success handler should run as success_handler user" - ); - assert_eq!( - handler_job.parent_job, - Some(main_job_id), - "Success handler should have main job as parent" - ); - // Note: root_job may be None when it equals parent_job (optimization in push function) - - Ok(()) -} diff --git a/backend/tests/suspend_resume.rs b/backend/tests/suspend_resume.rs index 6fb5d68004..0decc16519 100644 --- a/backend/tests/suspend_resume.rs +++ b/backend/tests/suspend_resume.rs @@ -63,11 +63,11 @@ mod suspend_resume { "op": { "type": "javascript", "expr": "flow_input.op ?? 'resume'", }, }, "type": "rawscript", - "language": "deno", + "language": "bun", "content": "\ export async function main(n, port, op) {\ - const job = Deno.env.get('WM_JOB_ID'); - const token = Deno.env.get('WM_TOKEN'); + const job = process.env.WM_JOB_ID; + const token = process.env.WM_TOKEN; const r = await fetch( `http://localhost:${port}/api/w/test-workspace/jobs/job_signature/${job}/0?token=${token}&approver=ruben`,\ {\ @@ -102,7 +102,7 @@ mod suspend_resume { "resumes": { "type": "javascript", "expr": "resumes", }, }, "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main(n, resume, resumes) { return { n: n + 1, resume, resumes } }" }, "suspend": { @@ -116,7 +116,7 @@ mod suspend_resume { "resumes": { "type": "javascript", "expr": "resumes", }, }, "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main(last, resume, resumes) { return { last, resume, resumes } }" }, }], @@ -256,11 +256,11 @@ mod suspend_resume { "port": { "type": "javascript", "expr": "flow_input.port" }, }, "type": "rawscript", - "language": "deno", + "language": "bun", "content": "\ export async function main(port) {\ - const job = Deno.env.get('WM_JOB_ID');\ - const token = Deno.env.get('WM_TOKEN');\ + const job = process.env.WM_JOB_ID;\ + const token = process.env.WM_TOKEN;\ const secret = await (await fetch(\ `http://localhost:${port}/api/w/test-workspace/jobs/job_signature/${job}/0?token=${token}&approver=ruben`,\ { headers: { 'Authorization': `Bearer ${token}` } }\ @@ -278,7 +278,7 @@ mod suspend_resume { "value": { "input_transforms": {}, "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main() { return 'b ran' }", }, // The gate holds `b` back, so `b` never runs and its error policy describes @@ -290,7 +290,7 @@ mod suspend_resume { "value": { "input_transforms": {}, "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main() { return 'handled' }", }, }, @@ -343,7 +343,7 @@ mod suspend_resume { "id": "a", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main() { return 'step1'; }" }, "suspend": { @@ -355,7 +355,7 @@ mod suspend_resume { "id": "b", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main() { return 'step2 - after approval'; }" } }] @@ -454,7 +454,7 @@ mod suspend_resume { "id": "a", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main() { return 'step1'; }" }, "suspend": { @@ -466,7 +466,7 @@ mod suspend_resume { "id": "b", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main() { return 'step2 - after approval'; }" } }] @@ -556,7 +556,7 @@ mod suspend_resume { "id": "a", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main() { return 'step1'; }" }, "suspend": { @@ -567,7 +567,7 @@ mod suspend_resume { "id": "b", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main() { return 'step2 - after approval'; }" } }] @@ -658,7 +658,7 @@ mod suspend_resume { "id": "a", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main() { return 'step1'; }" }, "suspend": { @@ -670,7 +670,7 @@ mod suspend_resume { "id": "b", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main() { return 'step2 - after approval'; }" } }] @@ -764,7 +764,7 @@ mod suspend_resume { "id": "a", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main() { return 'step1'; }" }, "suspend": { @@ -776,7 +776,7 @@ mod suspend_resume { "id": "b", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main() { return 'step2 - after approval'; }" } }] @@ -933,7 +933,7 @@ mod suspend_resume { "suspend": { "required_events": 1, "timeout": 86400 }, "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export async function main() { return 1 }", "input_transforms": {}, }, @@ -942,7 +942,7 @@ mod suspend_resume { "id": "b", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export async function main() { return 42 }", "input_transforms": {}, }, @@ -980,7 +980,7 @@ mod suspend_resume { "suspend": { "required_events": APPROVALS, "timeout": 86400 }, "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export async function main() { return 1 }", "input_transforms": {}, }, @@ -989,7 +989,7 @@ mod suspend_resume { "id": "b", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main(resumes) { return resumes.length }", "input_transforms": { "resumes": { "type": "javascript", "expr": "resumes" }, diff --git a/backend/tests/v2_job_delete_orphans.rs b/backend/tests/v2_job_delete_orphans.rs index 45029f024d..a11494baa7 100644 --- a/backend/tests/v2_job_delete_orphans.rs +++ b/backend/tests/v2_job_delete_orphans.rs @@ -325,6 +325,7 @@ async fn test_new_turns_wait_for_conversation_cleanup_and_recreate( WS, "f/flow", "test-user", + false, "hi again", conv_id, false, @@ -527,6 +528,16 @@ async fn test_jobs_export_delete_is_workspace_scoped(db: Pool) -> anyh let other_job = Uuid::new_v4(); insert_job(&db, "ws-other", other_job).await?; seed_side_rows(&db, "ws-other", other_job).await?; + // A queued flow's per-job tables, which carry no workspace_id of their own. + for sql in [ + "INSERT INTO v2_job_queue (id, workspace_id, scheduled_for) VALUES ($1, 'ws-other', now())", + "INSERT INTO v2_job_runtime (id) VALUES ($1)", + "INSERT INTO v2_job_status (id) VALUES ($1)", + "INSERT INTO resume_job (id, job, flow) VALUES (gen_random_uuid(), $1, $1)", + "INSERT INTO concurrency_key (key, job_id) VALUES ('k', $1)", + ] { + sqlx::query(sql).bind(other_job).execute(&db).await?; + } // A test-workspace admin calls the purge endpoint with the FOREIGN job id. let server = ApiServer::start(db.clone()).await?; @@ -551,5 +562,20 @@ async fn test_jobs_export_delete_is_workspace_scoped(db: Pool) -> anyh (1, 1, 1, 1), "jobs_export purge crossed workspaces: dispatch_event={de} flow_conversation_message={fcm} zombie_job_counter={zombie} v2_job={job}" ); + for table_col in [ + "v2_job_queue WHERE id", + "v2_job_runtime WHERE id", + "v2_job_status WHERE id", + "resume_job WHERE job", + "concurrency_key WHERE job_id", + ] { + let n = count( + &db, + &format!("SELECT count(*) FROM {table_col} = $1"), + other_job, + ) + .await?; + assert_eq!(n, 1, "jobs_export purge crossed workspaces: {table_col}"); + } Ok(()) } diff --git a/backend/tests/wac_suspend_started_at.rs b/backend/tests/wac_suspend_started_at.rs index 5a83730d24..ca364e5993 100644 --- a/backend/tests/wac_suspend_started_at.rs +++ b/backend/tests/wac_suspend_started_at.rs @@ -109,3 +109,91 @@ async fn wac_suspend_stands_down_for_a_cancel(db: Pool) -> anyhow::Res Ok(()) } + +/// Each park clears `started_at`, so the completion would otherwise store only the last +/// segment: a workflow that waited an hour on its tasks would read as a sub-second job that +/// started an hour late. The completed row spans the workflow from its first start, and +/// keeps the last segment aside: that is what is metered and what worker-time readers sum. +#[sqlx::test] +async fn wac_completion_spans_the_workflow_and_keeps_the_last_segment( + db: Pool, +) -> anyhow::Result<()> { + let job_id = Uuid::new_v4(); + sqlx::query( + "INSERT INTO v2_job (id, workspace_id, created_by, created_at, permissioned_as, \ + permissioned_as_email, kind, script_lang, runnable_path, tag, visible_to_owner) \ + VALUES ($1, 'test-workspace', 'test-user', now() - interval '2 hours', 'u/test-user', \ + 'test@windmill.dev', 'script', 'bun', 'u/test-user/wac', 'bun', true)", + ) + .bind(job_id) + .execute(&db) + .await?; + sqlx::query( + "INSERT INTO v2_job_queue (id, workspace_id, scheduled_for, running, tag, started_at) \ + VALUES ($1, 'test-workspace', now(), true, 'bun', now() - interval '1 hour')", + ) + .bind(job_id) + .execute(&db) + .await?; + + // Two parks, each followed by the pull re-stamping `started_at`: the second park must + // not replace the first start with its own segment's. + for resumed_ago in ["10 minutes", "3 seconds"] { + let mut tx = db.begin().await?; + suspend_wac_parent(&mut tx, &job_id, "test-workspace", 1, 3600.0).await?; + tx.commit().await?; + sqlx::query( + "UPDATE v2_job_queue SET suspend = 0, started_at = now() - $2::text::interval \ + WHERE id = $1", + ) + .bind(job_id) + .bind(resumed_ago) + .execute(&db) + .await?; + } + + let job = windmill_queue::get_mini_completed_job(&job_id, "test-workspace", &db) + .await? + .unwrap(); + let result = serde_json::value::to_raw_value(&serde_json::json!("done"))?; + let (_, span) = windmill_queue::add_completed_job( + &db, + &job, + true, + false, + sqlx::types::Json(&result), + None, + 0, + None, + false, + Some(3000), + false, + ) + .await?; + + let (started_ago_s, duration_ms, last_segment_ms): (f64, i64, Option) = sqlx::query_as( + "SELECT extract(epoch FROM now() - started_at)::float8, duration_ms, \ + (extras->>'wac_last_segment_ms')::bigint \ + FROM v2_job_completed WHERE id = $1", + ) + .bind(job_id) + .fetch_one(&db) + .await?; + assert!( + (started_ago_s - 3600.0).abs() < 60.0, + "started_at must be the first start, got {started_ago_s}s ago" + ); + assert!( + (duration_ms - 3_600_000).abs() < 60_000, + "duration_ms must be the wall time since the first start, got {duration_ms}" + ); + assert_eq!(last_segment_ms, Some(3000)); + assert_eq!( + span.duration_ms, duration_ms, + "a flow records the step with the span the row holds" + ); + assert!(span.outlasts_run(job.started_at)); + assert_eq!(span.last_run_ms, 3000, "only the last segment is left to meter"); + + Ok(()) +} diff --git a/backend/tests/wm_token_confinement.rs b/backend/tests/wm_token_confinement.rs index 23d88301b7..e15d33354e 100644 --- a/backend/tests/wm_token_confinement.rs +++ b/backend/tests/wm_token_confinement.rs @@ -319,7 +319,7 @@ async fn test_wm_token_is_confined_to_its_workspace(db: Pool) -> anyho ); } // ...and the `settings/global` keys on the allowlist, which the CLI reads from a job: on a - // git-sync push, and in `u/admin/hub_sync`. `ws_base_url` is the control: the handler + // git-sync push, and in `wmill hub pull`. `ws_base_url` is the control: the handler // leaves it as ungated as these, so only the allowlist stops it. for key in ["automate_username_creation", "uid", "hub_base_url"] { let resp = authed( @@ -381,6 +381,22 @@ async fn test_wm_token_is_confined_to_its_workspace(db: Pool) -> anyho "WM_TOKEN must still record its own tutorial progress: {}", resp.text().await? ); + // Every Teams notification a job sends posts here. An empty body is a 422 from the + // handler's extractor, so a 403 means confinement refused it. The real route is only + // mounted in an EE build. + #[cfg(all(feature = "enterprise", feature = "private"))] + { + let resp = authed(client().post(format!("{api}/teams/activities")), &user_wm) + .json(&json!({})) + .send() + .await?; + assert_eq!( + resp.status(), + 422, + "WM_TOKEN must still reach the Teams message route: {}", + resp.text().await? + ); + } // 11. ...and the caller-scoped reads deliberately left out of it, each because it // names another workspace or the identity's credentials. diff --git a/backend/tests/worker.rs b/backend/tests/worker.rs index 73d3fc2567..553106e6fe 100644 --- a/backend/tests/worker.rs +++ b/backend/tests/worker.rs @@ -166,7 +166,7 @@ async fn test_iteration_parallel(db: Pool) -> anyhow::Result<()> { #[cfg(feature = "deno_core")] #[sqlx::test(fixtures("base"))] -async fn test_deno_flow(db: Pool) -> anyhow::Result<()> { +async fn test_bun_flow(db: Pool) -> anyhow::Result<()> { initialize_tracing().await; let server = ApiServer::start(db.clone()).await?; @@ -183,7 +183,7 @@ async fn test_deno_flow(db: Pool) -> anyhow::Result<()> { id: "a".to_string(), value: FlowModuleValue::RawScript { input_transforms: Default::default(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: numbers.to_string(), path: None, lock: None, @@ -232,7 +232,7 @@ async fn test_deno_flow(db: Pool) -> anyhow::Result<()> { }, )] .into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: doubles.to_string(), path: None, lock: None, @@ -296,7 +296,7 @@ async fn test_deno_flow(db: Pool) -> anyhow::Result<()> { let port = server.addr.port(); for i in 0..50 { - println!("deno flow iteration: {}", i); + println!("bun flow iteration: {}", i); let job = run_job_in_new_worker_until_complete(&db, false, job.clone(), port).await; // println!("job: {:#?}", job.flow_status); let result = job.json_result().unwrap(); @@ -346,13 +346,13 @@ async fn test_identity(db: Pool) -> anyhow::Result<()> { #[cfg(feature = "deno_core")] #[sqlx::test(fixtures("base"))] -async fn test_deno_flow_same_worker(db: Pool) -> anyhow::Result<()> { +async fn test_bun_flow_same_worker(db: Pool) -> anyhow::Result<()> { initialize_tracing().await; let server = ApiServer::start(db.clone()).await?; let write_file = r#"export async function main(loop: boolean, i: number, path: string) { - await Deno.writeTextFile(`./shared/${path}`, `${loop} ${i}`); + await Bun.write(`./shared/${path}`, `${loop} ${i}`); }"# .to_string(); @@ -373,7 +373,7 @@ async fn test_deno_flow_same_worker(db: Pool) -> anyhow::Result<()> { ), ] .into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: write_file.clone(), path: None, lock: None, @@ -432,7 +432,7 @@ async fn test_deno_flow_same_worker(db: Pool) -> anyhow::Result<()> { ), ] .into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: write_file, path: None, lock: None, @@ -472,9 +472,9 @@ async fn test_deno_flow_same_worker(db: Pool) -> anyhow::Result<()> { InputTransform::Static { value: windmill_common::worker::to_raw_value(&"outer.txt") }, )] .into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#"export async function main(path: string, path2: string) { - return await Deno.readTextFile(`./shared/${path}`) + "," + await Deno.readTextFile(`./shared/${path2}`); + return await Bun.file(`./shared/${path}`).text() + "," + await Bun.file(`./shared/${path2}`).text(); }"# .to_string(), path: None, @@ -546,9 +546,9 @@ async fn test_deno_flow_same_worker(db: Pool) -> anyhow::Result<()> { ), ] .into(), - language: ScriptLang::Deno, + language: ScriptLang::Bun, content: r#"export async function main(path: string, loops: string[], path2: string) { - return await Deno.readTextFile(`./shared/${path}`) + "," + loops + "," + await Deno.readTextFile(`./shared/${path2}`); + return await Bun.file(`./shared/${path}`).text() + "," + loops + "," + await Bun.file(`./shared/${path2}`).text(); }"# .to_string(), path: None, @@ -618,7 +618,7 @@ async fn test_same_worker_survives_empty_branch(db: Pool) -> anyhow::R "id": "c", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main(){ return 1 }", } }] @@ -630,7 +630,7 @@ async fn test_same_worker_survives_empty_branch(db: Pool) -> anyhow::R "id": "b", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main(){ return 42 }", } } @@ -671,7 +671,7 @@ async fn test_flow_result_by_id(db: Pool) -> anyhow::Result<()> { "id": "a", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main(){ return 42 }", } }, @@ -686,7 +686,7 @@ async fn test_flow_result_by_id(db: Pool) -> anyhow::Result<()> { "value": { "input_transforms": {"v": {"type": "javascript", "expr": "results.a"}}, "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main(v){ return v }", } @@ -2123,7 +2123,6 @@ async fn test_postgresql_single_worker_session_isolation(db: Pool) -> #[serial(pg_cache)] async fn test_postgresql_100_jobs_cached(db: Pool) -> anyhow::Result<()> { use std::sync::atomic::Ordering; - use windmill_common::worker::Connection; use windmill_worker::pg_executor::{clear_pg_cache, CACHE_HITS}; initialize_tracing().await; @@ -2176,27 +2175,7 @@ async fn test_postgresql_100_jobs_cached(db: Pool) -> anyhow::Result<( ids.push(make_pg_job(content).push(&db).await); } - // Run ONE worker for all 100 jobs. - let listener = listen_for_completed_jobs(&db).await; - let id_set = ids - .iter() - .copied() - .collect::>(); - in_test_worker( - Connection::Sql(db.clone()), - async { - use futures::StreamExt; - let mut remaining = id_set; - let mut listener = listener; - while !remaining.is_empty() { - if let Some(id) = listener.next().await { - remaining.remove(&id); - } - } - }, - port, - ) - .await; + run_on_one_worker(&db, port, &ids).await; // Verify all 100 jobs succeeded. for (i, id) in ids.iter().enumerate() { @@ -2259,6 +2238,26 @@ async fn test_postgresql_arg_type_combinations(db: Pool) -> anyhow::Re let db_arg = json!({"host": "localhost", "port": 5432, "dbname": "windmill", "user": "postgres", "password": "changeme"}); + let make_pg_job = |content: String| { + RunJob::from(JobPayload::Code(RawCode { + hash: None, + content, + path: None, + lock: None, + language: ScriptLang::Postgresql, + cache_ttl: None, + cache_ignore_s3_path: None, + dedicated_worker: None, + concurrency_settings: windmill_common::runnable_settings::ConcurrencySettings::default( + ) + .into(), + debouncing_settings: windmill_common::runnable_settings::DebouncingSettings::default(), + modules: None, + tag: None, + })) + .arg("database", db_arg.clone()) + }; + // Build a fresh schema for this test so we don't trip over prior runs. let setup = r#" DROP SCHEMA IF EXISTS wm_pg_arg_combo_test CASCADE; @@ -2289,26 +2288,7 @@ CREATE TABLE wm_pg_arg_combo_test.allcols ( CREATE TYPE wm_pg_arg_combo_test.color AS ENUM ('red','green','blue'); CREATE TABLE wm_pg_arg_combo_test.enumtbl (c wm_pg_arg_combo_test.color); "#; - RunJob::from(JobPayload::Code(RawCode { - hash: None, - content: setup.to_owned(), - path: None, - lock: None, - language: ScriptLang::Postgresql, - cache_ttl: None, - cache_ignore_s3_path: None, - dedicated_worker: None, - concurrency_settings: windmill_common::runnable_settings::ConcurrencySettings::default() - .into(), - debouncing_settings: windmill_common::runnable_settings::DebouncingSettings::default(), - modules: None, - tag: None, - })) - .arg("database", db_arg.clone()) - .run_until_complete(&db, false, port) - .await - .json_result() - .unwrap(); + let setup_id = make_pg_job(setup.to_owned()).push(&db).await; // Each case: (name, content, args, expected_result) let cases: Vec<(&str, String, serde_json::Value, serde_json::Value)> = vec![ @@ -2742,29 +2722,22 @@ SELECT 'price: $5' AS lbl, $5::int + $50::int AS sum"# ), ]; - for (name, content, args, expected) in cases { - let mut job = RunJob::from(JobPayload::Code(RawCode { - hash: None, - content, - path: None, - lock: None, - language: ScriptLang::Postgresql, - cache_ttl: None, - cache_ignore_s3_path: None, - dedicated_worker: None, - concurrency_settings: windmill_common::runnable_settings::ConcurrencySettings::default( - ) - .into(), - debouncing_settings: windmill_common::runnable_settings::DebouncingSettings::default(), - modules: None, - tag: None, - })) - .arg("database", db_arg.clone()); + let mut ids = vec![setup_id]; + for (_, content, args, _) in &cases { + let mut job = make_pg_job(content.clone()); for (k, v) in args.as_object().unwrap() { job = job.arg(k, v.clone()); } - let result = job - .run_until_complete(&db, false, port) + ids.push(job.push(&db).await); + } + run_on_one_worker(&db, port, &ids).await; + + completed_job(setup_id, &db) + .await + .json_result() + .expect("setup: no json result"); + for ((name, _, _, expected), id) in cases.into_iter().zip(&ids[1..]) { + let result = completed_job(*id, &db) .await .json_result() .unwrap_or_else(|| panic!("case '{name}': no json result")); @@ -2774,6 +2747,32 @@ SELECT 'price: $5' AS lbl, $5::int + $50::int AS sum"# Ok(()) } +/// Runs the already pushed `ids` on a single worker and returns once all completed. One worker +/// takes them one at a time in push order, so a setup job pushed first runs before the rest, +/// and they all share the process-wide PG connection cache as consecutive jobs would. +async fn run_on_one_worker(db: &Pool, port: u16, ids: &[Uuid]) { + use futures::StreamExt; + use windmill_common::worker::Connection; + + let mut listener = listen_for_completed_jobs(db).await; + let mut remaining = ids + .iter() + .copied() + .collect::>(); + in_test_worker( + Connection::Sql(db.clone()), + async { + while !remaining.is_empty() { + if let Some(id) = listener.next().await { + remaining.remove(&id); + } + } + }, + port, + ) + .await; +} + /// Pooler-safety regression test for #8988: when every arg has a resolvable /// otyp (the common SDK case), the dispatch must use unnamed prepared /// statements (`query_typed_raw`) and *must not* leak named statements @@ -3010,11 +3009,7 @@ CREATE SCHEMA wm_pg_cached_test; CREATE TYPE wm_pg_cached_test.color AS ENUM ('red', 'green', 'blue'); CREATE DOMAIN wm_pg_cached_test.short_name AS TEXT CHECK (length(VALUE) BETWEEN 1 AND 10); "#; - make_pg_job(setup.to_owned()) - .run_until_complete(&db, false, port) - .await - .json_result() - .unwrap(); + let setup_id = make_pg_job(setup.to_owned()).push(&db).await; // Run a long alternating sequence of enum + domain queries on the same // cached connection. Each query goes through the prepare-fallback path @@ -3022,21 +3017,36 @@ CREATE DOMAIN wm_pg_cached_test.short_name AS TEXT CHECK (length(VALUE) BETWEEN // tokio_postgres' typeinfo cache to resolve the Oids server-side. Pre-fix // this would fail intermittently with `prepared statement "sN" does not // exist` after the first cached-conn reuse. + let mut pairs = Vec::with_capacity(10); for i in 0..10 { - let r = make_pg_job("-- $1 arg1\nSELECT $1::wm_pg_cached_test.color AS c".to_owned()) + let enum_id = make_pg_job("-- $1 arg1\nSELECT $1::wm_pg_cached_test.color AS c".to_owned()) .arg("arg1", json!(if i % 2 == 0 { "red" } else { "blue" })) - .run_until_complete(&db, false, port) + .push(&db) .await; + let domain_id = + make_pg_job("-- $1 arg1\nSELECT $1::wm_pg_cached_test.short_name AS s".to_owned()) + .arg("arg1", json!(format!("v{i}"))) + .push(&db) + .await; + pairs.push((enum_id, domain_id)); + } + let mut ids = vec![setup_id]; + ids.extend(pairs.iter().flat_map(|(e, d)| [*e, *d])); + run_on_one_worker(&db, port, &ids).await; + + completed_job(setup_id, &db) + .await + .json_result() + .expect("setup: no json result"); + for (i, (enum_id, domain_id)) in pairs.into_iter().enumerate() { + let r = completed_job(enum_id, &db).await; assert!( r.success, "iter {i} enum query failed (was the DISCARD ALL bug); result: {:?}", r.result ); - let r = make_pg_job("-- $1 arg1\nSELECT $1::wm_pg_cached_test.short_name AS s".to_owned()) - .arg("arg1", json!(format!("v{i}"))) - .run_until_complete(&db, false, port) - .await; + let r = completed_job(domain_id, &db).await; assert!( r.success, "iter {i} domain query failed (was the DISCARD ALL bug); result: {:?}", @@ -3857,7 +3867,7 @@ fn module_add_item_to_list(i: i32, id: &str) -> serde_json::Value { } }, "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main(array, i){ array.push(i); return array }", } }) @@ -3868,7 +3878,7 @@ fn module_failure() -> serde_json::Value { "value": { "input_transforms": {}, "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main(){ throw Error('failure') }", } }) @@ -3886,7 +3896,7 @@ async fn test_branchone_simple(db: Pool) -> anyhow::Result<()> { "id": "a", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main(){ return [1] }", } }, @@ -3924,7 +3934,7 @@ async fn test_branchone_with_cond(db: Pool) -> anyhow::Result<()> { "id": "a", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main(){ return [1] }", } }, @@ -3962,7 +3972,7 @@ async fn test_branchall_sequential(db: Pool) -> anyhow::Result<()> { "id": "a", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main(){ return [1] }", } }, @@ -4002,7 +4012,7 @@ async fn test_branchall_simple(db: Pool) -> anyhow::Result<()> { "id": "a", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main(){ return [1] }", } }, @@ -4050,7 +4060,7 @@ async fn test_branchall_skip_failure(db: Pool) -> anyhow::Result<()> { "id": "a", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main(){ return [1] }", } }, @@ -4086,7 +4096,7 @@ async fn test_branchall_skip_failure(db: Pool) -> anyhow::Result<()> { "id": "a", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main(){ return [1] }", } }, @@ -4132,7 +4142,7 @@ async fn test_branchone_nested(db: Pool) -> anyhow::Result<()> { "id": "a", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main(){ return [] }", } }, @@ -4191,7 +4201,7 @@ async fn test_branchall_nested(db: Pool) -> anyhow::Result<()> { "id": "a", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main(){ return [1] }", } }, @@ -4257,7 +4267,7 @@ async fn test_failure_module(db: Pool) -> anyhow::Result<()> { "n": { "type": "javascript", "expr": "flow_input.n", }, }, "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main(n, l) { if (n == 0) throw Error(JSON.stringify(l)); return { l: [...l, 0] } }", }, }, { @@ -4268,7 +4278,7 @@ async fn test_failure_module(db: Pool) -> anyhow::Result<()> { "n": { "type": "javascript", "expr": "flow_input.n", }, }, "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main(n, l) { if (n == 1) throw Error(JSON.stringify(l)); return { l: [...l, 1] } }", }, }, { @@ -4278,7 +4288,7 @@ async fn test_failure_module(db: Pool) -> anyhow::Result<()> { "n": { "type": "javascript", "expr": "flow_input.n", }, }, "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main(n, l) { if (n == 2) throw Error(JSON.stringify(l)); return { l: [...l, 2] } }", }, }], @@ -4286,7 +4296,7 @@ async fn test_failure_module(db: Pool) -> anyhow::Result<()> { "value": { "input_transforms": { "error": { "type": "javascript", "expr": "previous_result", } }, "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main(error) { return { 'from failure module': error } }", } }, @@ -4475,7 +4485,7 @@ fn hanging_step_value() -> serde_json::Value { serde_json::json!({ "input_transforms": {}, "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export async function main() { await new Promise((r) => setTimeout(r, 600000)); }", }) } @@ -4487,7 +4497,7 @@ fn marker_failure_module() -> serde_json::Value { "value": { "input_transforms": { "error": { "type": "javascript", "expr": "previous_result", } }, "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main(error) { return { handled_unrecoverable: true, error } }", } }) @@ -4585,7 +4595,7 @@ async fn test_unrecoverable_failure_on_continue_on_error_runs_failure_module( "value": { "input_transforms": {}, "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main() { return { ran_b: true }; }", }, }, @@ -4624,7 +4634,7 @@ async fn test_run_wait_result_early_return_with_failure_module( "id": "a", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "input_transforms": {}, "content": "export function main() { throw new Error('boom'); }", }, @@ -4632,7 +4642,7 @@ async fn test_run_wait_result_early_return_with_failure_module( "failure_module": { "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "input_transforms": {}, "content": "export function main() { return { recovered: true } }", }, @@ -4698,6 +4708,224 @@ async fn test_run_wait_result_early_return_with_failure_module( Ok(()) } +/// An early-return node inside a branch to one resolves while the flow is still running when its +/// branch is taken, and falls back to the flow's final result when it is not. A nested branch to +/// all resolves to its list, though its status is not in the root flow's modules. +#[cfg(all(feature = "deno_core", feature = "quickjs"))] +#[sqlx::test(fixtures("base"))] +async fn test_run_wait_result_early_return_inside_branch_one( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + let returns = |v: &str, sleep_ms: u64| { + json!({ + "type": "rawscript", + "language": "deno", + "input_transforms": {}, + "content": format!( + "export async function main() {{ await new Promise((r) => setTimeout(r, {sleep_ms})); return '{v}' }}" + ), + }) + }; + let flow: FlowValue = serde_json::from_value(json!({ + "modules": [ + { + "id": "a", + "value": { + "type": "branchone", + "branches": [{ "expr": "flow_input.take", "modules": [ + { + "id": "b", + "value": { + "type": "branchone", + "branches": [], + "default": [{ "id": "c", "value": returns("c", 0) }], + }, + }, + { + "id": "e", + "value": { + "type": "branchall", + "branches": [{ "modules": [{ "id": "f", "value": returns("f", 0) }] }], + }, + }, + ] }], + "default": [], + }, + }, + { "id": "d", "value": returns("d", 3000) }, + ], + })) + .unwrap(); + + for (early_return, take, expected) in [ + ("c", true, json!("c")), + ("c", false, json!("d")), + ("e", true, json!(["f"])), + ] { + let mut flow = flow.clone(); + flow.early_return = Some(early_return.to_string()); + let id = + RunJob::from(JobPayload::RawFlow { value: flow, path: None, restarted_from: None }) + .arg("take", json!(take)) + .push(&db) + .await; + + // The completion check runs inside the worker's lifetime: the worker finishes `d` before + // quitting, so checking afterwards would always see the flow completed. + let (resp, flow_completed) = in_test_worker( + windmill_common::worker::Connection::Sql(db.clone()), + async { + let resp = windmill_api::jobs::run_wait_result( + &db, + id, + "test-workspace", + Some(early_return.to_string()), + false, + "test-user", + ) + .await + .unwrap(); + let completed: bool = sqlx::query_scalar( + "SELECT EXISTS(SELECT 1 FROM v2_job_completed WHERE id = $1)", + ) + .bind(id) + .fetch_one(&db) + .await + .unwrap(); + (resp, completed) + }, + port, + ) + .await; + // Only the taken branch returns before `d` finishes sleeping. + assert_eq!(flow_completed, !take, "{early_return}, take = {take}"); + + let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await?; + let body: serde_json::Value = serde_json::from_slice(&bytes)?; + assert_eq!(expected, body, "{early_return}, take = {take}"); + } + + Ok(()) +} + +/// The step whose stream `run_and_stream` follows: the early-return step inside branches to one +/// and to all, the last step when the early-return step's branch is not taken, and neither when +/// the early-return step ran inside a loop. Only a deployed flow reads `early_return` here. +#[cfg(all(feature = "deno_core", feature = "quickjs"))] +#[sqlx::test(fixtures("base"))] +async fn test_early_return_stream_job_inside_branches(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + let streams = |v: &str| { + json!({ + "type": "rawscript", + "language": "deno", + "input_transforms": {}, + "content": format!( + "export async function main() {{ console.log('WM_STREAM: {v}'); await new Promise((r) => setTimeout(r, 1000)); return '{v}' }}" + ), + }) + }; + let modules = json!([ + { + "id": "a", + "value": { + "type": "branchone", + "branches": [{ "expr": "flow_input.take", "modules": [ + { + "id": "b", + "value": { + "type": "branchall", + "branches": [{ "modules": [{ "id": "c", "value": streams("c") }] }], + }, + }, + { + "id": "l", + "value": { + "type": "forloopflow", + "iterator": { "type": "javascript", "expr": "[1]" }, + "skip_failures": false, + // Two steps, so the loop body is not inlined into the iteration job. + "modules": [ + { "id": "j", "value": streams("j") }, + { "id": "m", "value": { "type": "identity" } }, + ], + }, + }, + ] }], + "default": [], + }, + }, + { "id": "d", "value": streams("d") }, + ]); + + for (version, early_return, take, expected) in [ + (1, "c", true, Some("c")), + (2, "c", false, Some("d")), + (3, "j", true, None), + ] { + let path = format!("f/system/early_return_stream_{version}"); + let value = json!({ "modules": modules, "early_return": early_return }); + sqlx::query( + "INSERT INTO flow(workspace_id, summary, description, path, versions, schema, value, edited_by) VALUES ('test-workspace', '', '', $1, ARRAY[$2]::bigint[], '{}'::jsonb, $3, 'system')", + ) + .bind(&path) + .bind(version) + .bind(&value) + .execute(&db) + .await?; + sqlx::query( + "INSERT INTO flow_version(id, workspace_id, path, schema, value, created_by) VALUES ($1, 'test-workspace', $2, '{}'::jsonb, $3, 'system')", + ) + .bind(version) + .bind(&path) + .bind(&value) + .execute(&db) + .await?; + RunJob::from(JobPayload::FlowDependencies { + path: path.clone(), + dedicated_worker: None, + version, + debouncing_settings: Default::default(), + }) + .run_until_complete(&db, false, port) + .await; + + let completed = RunJob::from(JobPayload::Flow { + path, + dedicated_worker: None, + apply_preprocessor: false, + labels: None, + version, + job_token_scopes: None, + }) + .arg("take", json!(take)) + .run_until_complete(&db, false, port) + .await; + + let stream_step: Option = sqlx::query_scalar( + "SELECT flow_step_id FROM v2_job + WHERE id = (SELECT (flow_status->>'stream_job')::uuid FROM v2_job_completed WHERE id = $1)", + ) + .bind(completed.id) + .fetch_optional(&db) + .await?; + assert_eq!( + expected.map(String::from), + stream_step, + "{early_return}, take = {take}" + ); + } + + Ok(()) +} + /// `recover: true` from the error handler of a step that fails inside a loop turns the flow /// green, as it does for a top-level step, without changing which steps run: a loop that /// stops at a failed iteration still stops there, one that skips failures still carries on. @@ -4720,7 +4948,7 @@ async fn test_failure_module_recover_inside_loop(db: Pool) -> anyhow:: "value": { "input_transforms": {}, "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main() { throw new Error('boom'); }", }, }], @@ -4734,7 +4962,7 @@ async fn test_failure_module_recover_inside_loop(db: Pool) -> anyhow:: "value": { "input_transforms": {}, "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main() { return { ran_b: true } }", }, }], @@ -4742,7 +4970,7 @@ async fn test_failure_module_recover_inside_loop(db: Pool) -> anyhow:: "value": { "input_transforms": {}, "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main() { return { handled: true, recover: true } }", }, }, @@ -4797,14 +5025,23 @@ async fn test_failure_module_recover_inside_loop(db: Pool) -> anyhow:: server.close().await.unwrap(); #[cfg(feature = "quickjs")] - assert!(!chaining_error.success, "an error no handler recovered must keep the flow failed"); + assert!( + !chaining_error.success, + "an error no handler recovered must keep the flow failed" + ); - assert!(stopped.success, "a recovered failure inside a loop should end the flow as a success"); + assert!( + stopped.success, + "a recovered failure inside a loop should end the flow as a success" + ); assert!( stopped.json_result().unwrap().get("ran_b").is_none(), "the step after the loop must not run, as without recovery" ); - assert_eq!(stopped_handler_runs, 1, "the loop must stop at the first failed iteration"); + assert_eq!( + stopped_handler_runs, 1, + "the loop must stop at the first failed iteration" + ); assert!(skipping.success); assert_eq!( @@ -4815,7 +5052,11 @@ async fn test_failure_module_recover_inside_loop(db: Pool) -> anyhow:: assert_eq!(skipping_handler_runs, 3); assert!( - !parallel.json_result().unwrap().to_string().contains("ran_b"), + !parallel + .json_result() + .unwrap() + .to_string() + .contains("ran_b"), "the parallel loop fails as without recovery, so the step after it must not run" ); Ok(()) @@ -4987,6 +5228,101 @@ async fn test_flow_lock_all(db: Pool) -> anyhow::Result<()> { Ok(()) } +/// A deployed flow runs a multi-step loop body as the flow node its deploy stored, which +/// carries its own copy of the flow's `preserve_step_tags`. A preview never loads that node. +#[sqlx::test(fixtures("base"))] +async fn test_saved_flow_preserves_nested_step_tags(db: Pool) -> anyhow::Result<()> { + use futures::StreamExt; + + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let client = reqwest::Client::new(); + let flow = json!({ + "path": "g/all/saved_step_tags", "summary": "", "description": "", "tag": "python3", + "schema": { "type": "object", "properties": {}, "required": [] }, + "value": { + "preserve_step_tags": true, + "modules": [{ + "id": "loop", + "value": { + "type": "forloopflow", "skip_failures": false, + "iterator": { "type": "static", "value": [2, 3] }, + "modules": [{ + "id": "own_tag", + "value": { + "type": "rawscript", "language": "bun", "lock": "", "tag": "bun", + "content": "export function main(n: number) { return n * n; }", + "input_transforms": { + "n": { "type": "javascript", "expr": "flow_input.iter.value" } + } + } + }, { + "id": "untagged", + "value": { + "type": "rawscript", "language": "bun", "lock": "", + "content": "export function main(n: number) { return n + 1; }", + "input_transforms": { + "n": { "type": "javascript", "expr": "results.own_tag" } + } + } + }] + } + }] + } + }); + let mut completed = listen_for_completed_jobs(&db).await; + client + .post(format!( + "http://localhost:{port}/api/w/test-workspace/flows/create" + )) + .bearer_auth("SECRET_TOKEN") + .json(&flow) + .send() + .await? + .error_for_status()?; + let deployment = in_test_worker(&db, completed.next(), port).await.unwrap(); + let deployed = completed_job(deployment, &db).await; + assert!(deployed.success, "{:?}", deployed.result); + + let job_id = client + .post(format!( + "http://localhost:{port}/api/w/test-workspace/jobs/run/f/g/all/saved_step_tags" + )) + .bearer_auth("SECRET_TOKEN") + .json(&json!({})) + .send() + .await? + .error_for_status()? + .text() + .await? + .parse::()?; + in_test_worker(&db, completed.find(&job_id), port).await; + let job = completed_job(job_id, &db).await; + assert!(job.success, "{:?}", job.result); + let tags = sqlx::query_as::<_, (String, String)>( + "WITH RECURSIVE descendants AS ( + SELECT id FROM v2_job WHERE id = $1 + UNION ALL + SELECT child.id FROM v2_job child JOIN descendants ON child.parent_job = descendants.id + ) + SELECT DISTINCT flow_step_id, tag FROM v2_job + WHERE id IN (SELECT id FROM descendants) AND flow_step_id IN ('own_tag', 'untagged') + ORDER BY flow_step_id, tag", + ) + .bind(job_id) + .fetch_all(&db) + .await?; + assert_eq!( + tags, + vec![ + ("own_tag".to_owned(), "bun".to_owned()), + ("untagged".to_owned(), "python3".to_owned()) + ] + ); + Ok(()) +} + #[cfg(feature = "deno_core")] #[sqlx::test(fixtures("base"))] @@ -5526,42 +5862,6 @@ async fn test_flow_schedule_handlers(db: Pool) -> anyhow::Result<()> { Ok(()) } -#[sqlx::test(fixtures("base", "relative_bun"))] -async fn test_relative_imports_bun(db: Pool) -> anyhow::Result<()> { - let content = r#" -import { main as test1 } from "/f/system/same_folder_script.ts"; -import { main as test2 } from "./same_folder_script.ts"; -import { main as test3 } from "/f/system_relative/different_folder_script.ts"; -import { main as test4 } from "../system_relative/different_folder_script.ts"; - -export async function main() { - return [test1(), test2(), test3(), test4()]; -} -"# - .to_string(); - - run_deployed_relative_imports(&db, content.clone(), ScriptLang::Bun).await?; - run_preview_relative_imports(&db, content, ScriptLang::Bun).await?; - Ok(()) -} - -#[cfg(feature = "deno_core")] -#[sqlx::test(fixtures("base", "relative_bun"))] -async fn test_nested_imports_bun(db: Pool) -> anyhow::Result<()> { - let content = r#" -import { main as test } from "/f/system_relative/nested_script.ts"; - -export async function main() { - return test(); -} -"# - .to_string(); - - run_deployed_relative_imports(&db, content.clone(), ScriptLang::Bun).await?; - run_preview_relative_imports(&db, content, ScriptLang::Bun).await?; - Ok(()) -} - #[sqlx::test(fixtures("base", "relative_deno"))] async fn test_relative_imports_deno(db: Pool) -> anyhow::Result<()> { let content = r#" @@ -5687,7 +5987,7 @@ async fn test_job_labels(db: Pool) -> anyhow::Result<()> { console.log(greet) return { greet, wm_labels: ["yolo", "greet", "greet", world] }; }"#, - "language": "deno", + "language": "bun", "input_transforms": { "world": { "type": "javascript", "expr": "flow_input.world" } } @@ -5896,7 +6196,7 @@ async fn test_flow_substep_tag_availability_check(db: Pool) -> anyhow: "id": "a", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main() { return 42; }", "tag": "restricted-tag", }, @@ -5956,7 +6256,7 @@ async fn test_flow_substep_tag_checked_on_resolved_value(db: Pool) -> "id": id, "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "content": "export function main() { return { lang: 'bun' } }", "tag": tag, }, diff --git a/backend/tests/worker_ping_ip.rs b/backend/tests/worker_ping_ip.rs index 772f4193c3..2421e888ef 100644 --- a/backend/tests/worker_ping_ip.rs +++ b/backend/tests/worker_ping_ip.rs @@ -2,10 +2,19 @@ use sqlx::{Pool, Postgres}; use uuid::Uuid; use windmill_common::{ external_ip::UNKNOWN_IP, - worker::{insert_ping_query, update_worker_ping_main_loop_query}, + worker::{insert_ping_query, set_worker_draining_query, update_worker_ping_main_loop_query}, }; async fn insert_ping(db: &Pool, worker: &str, ip: Option<&str>) -> anyhow::Result<()> { + register(db, worker, ip, None).await +} + +async fn register( + db: &Pool, + worker: &str, + ip: Option<&str>, + draining: Option, +) -> anyhow::Result<()> { insert_ping_query( "test-instance", worker, @@ -19,12 +28,33 @@ async fn insert_ping(db: &Pool, worker: &str, ip: Option<&str>) -> any None, None, false, + draining, db, ) .await?; Ok(()) } +/// A worker re-registers mid-life once its external IP resolves. That registration must not +/// clear a draining flag the same process already published; only a worker starting up under +/// a reclaimed name resets it. +#[sqlx::test] +async fn only_a_starting_worker_resets_draining(db: Pool) -> anyhow::Result<()> { + let draining = || async { + sqlx::query_scalar::<_, bool>("SELECT draining FROM worker_ping WHERE worker = 'wk-drain'") + .fetch_one(&db) + .await + }; + register(&db, "wk-drain", None, Some(false)).await?; + set_worker_draining_query("wk-drain", &db).await?; + register(&db, "wk-drain", Some("1.2.3.4"), None).await?; + assert!(draining().await?); + + register(&db, "wk-drain", None, Some(false)).await?; + assert!(!draining().await?); + Ok(()) +} + /// The external IP resolves in the background, so the initial ping often has none yet. That must /// not blank the address a previous process wrote to the row this one reclaims — worker names are /// stable across restarts under EXIT_AFTER_N_JOBS. diff --git a/backend/tests/workspace_dependencies.rs b/backend/tests/workspace_dependencies.rs index 773a4fd965..8136416190 100644 --- a/backend/tests/workspace_dependencies.rs +++ b/backend/tests/workspace_dependencies.rs @@ -1,23 +1,10 @@ mod workspace_dependencies { use sqlx::{Pool, Postgres}; - use tokio_stream::StreamExt; use windmill_common::scripts::ScriptLang; use windmill_dep_map::workspace_dependencies::NewWorkspaceDependencies; - use windmill_test_utils::in_test_worker; - use windmill_test_utils::init_client; - use windmill_test_utils::listen_for_completed_jobs; - mod deps { - pub const REQUIREMENTS_IN: &'static str = "tiny==0.1.3"; - // pub const GO_MOD: &'static str = r##" - // module example.com/project - // go 1.20 - - // require github.com/gin-gonic/gin v1.8.1 - // "##; - - pub const PACKAGE_JSON: &'static str = r##" + const PACKAGE_JSON: &'static str = r##" { "name": "example-project", "version": "1.0.0", @@ -27,101 +14,13 @@ mod workspace_dependencies { } "##; - pub const COMPOSER_JSON: &'static str = r##" - { - "name": "example/project", - "require": { - "monolog/monolog": "^2.3" - } - } - "##; - } - - #[cfg(feature = "python")] - #[sqlx::test(fixtures("base", "workspace_dependencies_leafs"))] - #[ignore] - async fn basic_manual_named(db: Pool) -> anyhow::Result<()> { - let ((_client, port, _s), db, mut completed) = ( - init_client(db.clone()).await, - &db, - listen_for_completed_jobs(&db).await, - ); - - for (idx, (l, c)) in [ - (ScriptLang::Python3, deps::REQUIREMENTS_IN), - (ScriptLang::Bun, deps::PACKAGE_JSON), - (ScriptLang::Php, deps::COMPOSER_JSON), - // (ScriptLang::Go, deps::GO_MOD), - ] - .iter() - .enumerate() - { - let id = NewWorkspaceDependencies { - workspace_id: "test-workspace".into(), - language: *l, - content: (*c).into(), - name: Some("test".to_owned()), - description: None, - } - .create(("".to_owned(), "".to_owned(), "".to_owned()), db.clone()) - .await - .unwrap(); - - assert_eq!(idx + 1, id as usize); - } - - // Wait for 4 jobs. - // Creating those dependencies will trigger redeployment of all scripts in workspace_dependencies_leafs.sql - in_test_worker( - db, - async { - completed.next().await; - completed.next().await; - completed.next().await; - // completed.next().await; - }, - port, - ) - .await; - - // Verify all scripts have correct locks - // let mut langs = vec![]; - // for r in sqlx::query!( - // r#"SELECT language AS "language: ScriptLang",lock FROM script WHERE archived = false"# - // ) - // .fetch_all(db) - // .await - // .unwrap() - // { - // match r.language { - // ScriptLang::Python3 => assert_eq!("", &r.lock.unwrap()), - // ScriptLang::Go => todo!(), - // ScriptLang::Bun => todo!(), - // ScriptLang::Bunnative => todo!(), - // ScriptLang::Php => todo!(), - // _ => panic!("Unsupported language"), - // } - - // langs.push(r.language); - // } - - // langs.sort(); - // // Just tiny additional verification for peace of mind. - // assert_eq!(langs.as_slice(), &[]); - - Ok(()) - } - #[sqlx::test(fixtures("base", "hub_sync_blacklist"))] async fn hub_sync_blacklist_from_workspace_deps(db: Pool) -> anyhow::Result<()> { - let ((_client, port, _s), db, mut completed) = ( - init_client(db.clone()).await, - &db, - listen_for_completed_jobs(&db).await, - ); + // The first unnamed workspace dependencies wait out the existence cache before + // redeploying their dependents. Read once per process, and this binary has no other test. + std::env::set_var("EXISTS_CACHE_TIMEOUT_MS", "0"); + let db = &db; - // Verify built-in fixtures exist - // Check that hub_sync script exists and is a Bun script let hub_sync_lang = sqlx::query_scalar!( r#"SELECT language AS "language: ScriptLang" FROM script WHERE path = 'u/admin/hub_sync'"# ) @@ -134,51 +33,55 @@ mod workspace_dependencies { "Expected hub_sync to be a Bun script" ); - // Create unnamed (default) workspace dependencies for Bun - let _id = NewWorkspaceDependencies { + // Unnamed (default) workspace dependencies for Bun + NewWorkspaceDependencies { workspace_id: "admins".into(), language: ScriptLang::Bun, - content: deps::PACKAGE_JSON.into(), - name: None, // No name = default workspace dependencies + content: PACKAGE_JSON.into(), + name: None, description: None, } .create(("".to_owned(), "".to_owned(), "".to_owned()), db.clone()) .await .unwrap(); - // Wait for exactly 1 job (only u/admin/simple_bun, not hub_sync) - let job_id = in_test_worker(db, async { completed.next().await }, port) - .await - .expect("Expected one job to complete"); - - // Query the job's runnable_path - let runnable_path = - sqlx::query_scalar!("SELECT runnable_path FROM v2_job WHERE id = $1", job_id) - .fetch_one(db) - .await - .unwrap(); - + // The dependency map decides which runnables are redeployed, and is rebuilt before + // `create` returns. + let importers: Vec = sqlx::query_scalar( + "SELECT importer_path FROM dependency_map + WHERE workspace_id = 'admins' AND imported_path = 'dependencies/package.json' + ORDER BY importer_path", + ) + .fetch_all(db) + .await?; assert_eq!( - runnable_path, - Some("u/admin/simple_bun".to_string()), - "Expected job runnable_path to be 'u/admin/simple_bun' (hub_sync should be blacklisted)" + importers, + vec!["u/admin/simple_bun".to_string()], + "hub_sync must not be recorded as importing the default workspace dependencies" ); - // Assert total job count is 1 - let job_count = sqlx::query_scalar!("SELECT COUNT(*) FROM v2_job") - .fetch_one(db) - .await - .unwrap(); - - assert_eq!(job_count, Some(1), "Expected exactly one job total"); - - // Assert v2_job_queue is empty - let queue_count = sqlx::query_scalar!("SELECT COUNT(*) FROM v2_job_queue") - .fetch_one(db) - .await - .unwrap(); - - assert_eq!(queue_count, Some(0), "Expected job queue to be empty"); + // The redeploy is pushed in the background as a debounced dependency job; it never needs + // to run for what is asserted here. + let mut jobs: Vec<(Option, String)> = vec![]; + for _ in 0..200 { + jobs = sqlx::query_as( + "SELECT runnable_path, kind::text FROM v2_job WHERE workspace_id = 'admins'", + ) + .fetch_all(db) + .await?; + if !jobs.is_empty() { + break; + } + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + } + assert_eq!( + jobs, + vec![( + Some("u/admin/simple_bun".to_string()), + "dependencies".to_string() + )], + "Expected exactly one dependency job, for u/admin/simple_bun (hub_sync should be blacklisted)" + ); Ok(()) } diff --git a/backend/tests/workspace_handlers.rs b/backend/tests/workspace_handlers.rs new file mode 100644 index 0000000000..0ad1e044bd --- /dev/null +++ b/backend/tests/workspace_handlers.rs @@ -0,0 +1,422 @@ +#![cfg(all(feature = "enterprise", feature = "private"))] + +use sqlx::{Pool, Postgres}; + +use windmill_test_utils::*; + +const ERROR_HANDLER_EMAIL: &str = "error_handler@windmill.dev"; +const SUCCESS_HANDLER_EMAIL: &str = "success_handler@windmill.dev"; + +/// Every test seeds `f/test/error_handler` or `f/test/success_handler` with a different hash, +/// each in its own database, while the deployed-script caches are process-global and keyed by +/// workspace and path. With them on, one test resolves the handler to another's hash and the +/// handler push 404s whenever that hash's info is not cached yet. +fn disable_deployed_script_cache() { + windmill_common::DEPLOYED_SCRIPT_CACHE_DISABLED + .store(true, std::sync::atomic::Ordering::Relaxed); +} + +/// Polls so the assertion does not depend on the handler being pushed before +/// `run_until_complete` returns, which only holds while the worker drains its completions on exit. +async fn wait_for_handler_job( + db: &Pool, + handler_email: &str, +) -> anyhow::Result, Option)>> { + for _ in 0..100 { + let job = sqlx::query_as::<_, (Option, Option)>( + "SELECT runnable_path, parent_job FROM v2_job + WHERE workspace_id = 'test-workspace' AND permissioned_as_email = $1", + ) + .bind(handler_email) + .fetch_optional(db) + .await?; + if job.is_some() { + return Ok(job); + } + tokio::time::sleep(tokio::time::Duration::from_millis(100)).await; + } + Ok(None) +} + +#[cfg(feature = "deno_core")] +async fn insert_bun_script( + db: &Pool, + hash: i64, + path: &str, + content: &str, + ws_error_handler_muted: bool, +) -> anyhow::Result<()> { + // The lock must be non-null for the script to count as deployed. + sqlx::query( + r#"INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock, ws_error_handler_muted) + VALUES ('test-workspace', $1, $2, $3, 'bun', 'script', 'test-user', '{}', '', '', E'{}\n//bun.lock\n', $4)"#, + ) + .bind(hash) + .bind(path) + .bind(content) + .bind(ws_error_handler_muted) + .execute(db) + .await?; + Ok(()) +} + +/// Configures `f/test/error_handler` and `f/test/success_handler` as the workspace handlers. +/// Both settings are cached per workspace id across the tests of this binary, and any test's +/// top-level job can fill either cache, so every test configures both, with the same paths. +async fn configure_workspace_handlers(db: &Pool) -> anyhow::Result<()> { + sqlx::query( + r#"UPDATE workspace_settings + SET error_handler = '{"path": "script/f/test/error_handler"}'::jsonb, + success_handler = '{"path": "script/f/test/success_handler"}'::jsonb + WHERE workspace_id = 'test-workspace'"#, + ) + .execute(db) + .await?; + sqlx::query( + r#"INSERT INTO group_ (workspace_id, name, summary, extra_perms) + VALUES ('test-workspace', 'error_handler', '', '{"u/test-user": true}'), + ('test-workspace', 'success_handler', '', '{"u/test-user": true}') + ON CONFLICT DO NOTHING"#, + ) + .execute(db) + .await?; + Ok(()) +} + +/// Runs a deployed script by hash, which makes a `script` job rather than a preview. +#[cfg(feature = "deno_core")] +async fn run_script_hash(db: &Pool, port: u16, hash: i64, path: &str) -> CompletedJob { + use windmill_common::jobs::JobPayload; + use windmill_common::runnable_settings::{ConcurrencySettings, DebouncingSettings}; + use windmill_common::scripts::{ScriptHash, ScriptLang}; + + RunJob::from(JobPayload::ScriptHash { + hash: ScriptHash(hash), + path: path.to_string(), + cache_ttl: None, + cache_ignore_s3_path: None, + dedicated_worker: None, + language: ScriptLang::Bun, + priority: None, + apply_preprocessor: false, + concurrency_settings: ConcurrencySettings::default(), + debouncing_settings: DebouncingSettings::default(), + labels: None, + job_token_scopes: None, + }) + .run_until_complete(db, false, port) + .await +} + +/// A job's handler, if any, is pushed before the worker that ran it exits, so once a control +/// job has been handled, every handler job that the jobs run before it would produce exists. +#[cfg(feature = "deno_core")] +async fn assert_only_handled( + db: &Pool, + control_job: uuid::Uuid, + message: &str, +) -> anyhow::Result<()> { + assert!( + wait_for_handler_job(db, ERROR_HANDLER_EMAIL) + .await? + .is_some(), + "Error handler should have handled the control failure" + ); + let handled = sqlx::query_scalar::<_, Option>( + "SELECT parent_job FROM v2_job + WHERE workspace_id = 'test-workspace' AND permissioned_as_email = $1", + ) + .bind(ERROR_HANDLER_EMAIL) + .fetch_all(db) + .await?; + assert_eq!(handled, vec![Some(control_job)], "{message}"); + Ok(()) +} + +/// Test that a failed job triggers the workspace error handler +#[cfg(feature = "deno_core")] +#[sqlx::test(fixtures("base"))] +async fn test_error_handler_triggered_on_failure(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + disable_deployed_script_cache(); + + let server = ApiServer::start(db.clone()).await?; + + insert_bun_script( + &db, + 1111111111, + "f/test/error_handler", + r#" +export async function main(path: string, email: string, job_id: string, is_flow: boolean, workspace_id: string, error: any) { + console.log("Error handler called for job:", job_id); + return { handled: true, original_path: path }; +} +"#, + false, + ) + .await?; + insert_bun_script( + &db, + 2222222222, + "f/test/failing_script", + "export function main() { throw new Error('intentional failure'); }", + false, + ) + .await?; + configure_workspace_handlers(&db).await?; + + let completed_job = + run_script_hash(&db, server.addr.port(), 2222222222, "f/test/failing_script").await; + assert!(!completed_job.success, "Job should have failed"); + + assert_eq!( + wait_for_handler_job(&db, ERROR_HANDLER_EMAIL).await?, + Some(( + Some("f/test/error_handler".to_string()), + Some(completed_job.id) + )), + "Error handler should run the configured script with the failed job as parent" + ); + + Ok(()) +} + +/// Test that error handler is NOT triggered when ws_error_handler_muted is set on the script +#[cfg(feature = "deno_core")] +#[sqlx::test(fixtures("base"))] +async fn test_error_handler_muted_on_script(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + disable_deployed_script_cache(); + + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + insert_bun_script( + &db, + 3333333333, + "f/test/error_handler", + r#"export function main() { return "handled"; }"#, + false, + ) + .await?; + let failing = r#"export function main() { throw new Error("fail"); }"#; + insert_bun_script( + &db, + 4444444444, + "f/test/muted_failing_script", + failing, + true, + ) + .await?; + insert_bun_script(&db, 4444444445, "f/test/failing_script", failing, false).await?; + configure_workspace_handlers(&db).await?; + + let muted_job = run_script_hash(&db, port, 4444444444, "f/test/muted_failing_script").await; + assert!(!muted_job.success, "Job should have failed"); + + let control_job = run_script_hash(&db, port, 4444444445, "f/test/failing_script").await; + assert!(!control_job.success, "Job should have failed"); + + assert_only_handled( + &db, + control_job.id, + "Error handler should NOT have been triggered for a muted script", + ) + .await +} + +/// Test that error handler is NOT triggered on successful job completion +#[cfg(feature = "deno_core")] +#[sqlx::test(fixtures("base"))] +async fn test_error_handler_not_triggered_on_success(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + disable_deployed_script_cache(); + + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + insert_bun_script( + &db, + 5555555555, + "f/test/error_handler", + r#"export function main() { return "handled"; }"#, + false, + ) + .await?; + insert_bun_script( + &db, + 6666666666, + "f/test/success_script", + r#"export function main() { return "ok"; }"#, + false, + ) + .await?; + insert_bun_script( + &db, + 6666666667, + "f/test/failing_script", + r#"export function main() { throw new Error("fail"); }"#, + false, + ) + .await?; + configure_workspace_handlers(&db).await?; + + let success_job = run_script_hash(&db, port, 6666666666, "f/test/success_script").await; + assert!(success_job.success, "Job should have succeeded"); + + let control_job = run_script_hash(&db, port, 6666666667, "f/test/failing_script").await; + assert!(!control_job.success, "Job should have failed"); + + assert_only_handled( + &db, + control_job.id, + "Error handler should NOT have been triggered for a successful job", + ) + .await +} + +/// A hub script run at the top level (a schedule, a trigger, the API) is a `script_hub` job, +/// and its failure must reach the workspace error handler like a workspace script's. +#[sqlx::test(fixtures("base"))] +async fn test_error_handler_triggered_on_hub_script_failure( + db: Pool, +) -> anyhow::Result<()> { + use windmill_common::jobs::JobPayload; + + initialize_tracing().await; + disable_deployed_script_cache(); + + let server = ApiServer::start(db.clone()).await?; + + let version = "990000002"; + let hub_dir = &*windmill_common::worker::HUB_CACHE_DIR; + tokio::fs::create_dir_all(hub_dir).await?; + tokio::fs::write( + format!("{hub_dir}/{version}"), + r#"{"content":"exit 1","lockfile":null,"language":"bash","schema":{},"summary":null}"#, + ) + .await?; + + sqlx::query( + "INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock) + VALUES ('test-workspace', 1111111112, 'f/test/error_handler', 'echo handled', 'bash', 'script', 'test-user', '{}', '', '', '')", + ) + .execute(&db) + .await?; + configure_workspace_handlers(&db).await?; + + let completed_job = RunJob::from(JobPayload::ScriptHub { + path: format!("hub/{version}/test/fail"), + apply_preprocessor: false, + }) + .run_until_complete(&db, false, server.addr.port()) + .await; + assert!(!completed_job.success, "Hub script should have failed"); + + let handler_job = wait_for_handler_job(&db, ERROR_HANDLER_EMAIL).await?; + assert_eq!( + handler_job.map(|(_, parent)| parent), + Some(Some(completed_job.id)), + "Workspace error handler should handle the failed hub script" + ); + + Ok(()) +} + +/// Test that a successful job completion triggers the success handler +#[cfg(feature = "deno_core")] +#[sqlx::test(fixtures("base"))] +async fn test_success_handler_triggered_on_success(db: Pool) -> anyhow::Result<()> { + use serde_json::json; + + initialize_tracing().await; + disable_deployed_script_cache(); + + let server = ApiServer::start(db.clone()).await?; + + insert_bun_script( + &db, + 1234567890, + "f/test/success_handler", + r#" +export async function main(path: string, email: string, job_id: string, is_flow: boolean, workspace_id: string, result: any) { + console.log("Success handler called for job:", job_id); + return { handled: true, original_path: path }; +} +"#, + false, + ) + .await?; + insert_bun_script( + &db, + 9876543210, + "f/test/simple_script", + "export function main() { return 'success'; }", + false, + ) + .await?; + configure_workspace_handlers(&db).await?; + + let completed_job = + run_script_hash(&db, server.addr.port(), 9876543210, "f/test/simple_script").await; + assert_eq!(completed_job.json_result().unwrap(), json!("success")); + + assert_eq!( + wait_for_handler_job(&db, SUCCESS_HANDLER_EMAIL).await?, + Some(( + Some("f/test/success_handler".to_string()), + Some(completed_job.id) + )), + "Success handler should run the configured script with the main job as parent" + ); + + Ok(()) +} + +/// A hub script run at the top level (a schedule, a trigger, the API) is a `script_hub` job, +/// and its success must reach the workspace success handler like a workspace script's. +#[sqlx::test(fixtures("base"))] +async fn test_success_handler_triggered_on_hub_script_success( + db: Pool, +) -> anyhow::Result<()> { + use windmill_common::jobs::JobPayload; + + initialize_tracing().await; + disable_deployed_script_cache(); + + let server = ApiServer::start(db.clone()).await?; + + let version = "990000003"; + let hub_dir = &*windmill_common::worker::HUB_CACHE_DIR; + tokio::fs::create_dir_all(hub_dir).await?; + tokio::fs::write( + format!("{hub_dir}/{version}"), + r#"{"content":"echo ok","lockfile":null,"language":"bash","schema":{},"summary":null}"#, + ) + .await?; + + sqlx::query( + "INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, summary, description, lock) + VALUES ('test-workspace', 1234567891, 'f/test/success_handler', 'echo handled', 'bash', 'script', 'test-user', '{}', '', '', '')", + ) + .execute(&db) + .await?; + configure_workspace_handlers(&db).await?; + + let completed_job = RunJob::from(JobPayload::ScriptHub { + path: format!("hub/{version}/test/ok"), + apply_preprocessor: false, + }) + .run_until_complete(&db, false, server.addr.port()) + .await; + assert!(completed_job.success, "Hub script should have succeeded"); + + let handler_job = wait_for_handler_job(&db, SUCCESS_HANDLER_EMAIL).await?; + assert_eq!( + handler_job.map(|(_, parent)| parent), + Some(Some(completed_job.id)), + "Workspace success handler should handle the successful hub script" + ); + + Ok(()) +} diff --git a/backend/tests/zombie_flow_recovery.rs b/backend/tests/zombie_flow_recovery.rs index fb658dfb03..333aac70a8 100644 --- a/backend/tests/zombie_flow_recovery.rs +++ b/backend/tests/zombie_flow_recovery.rs @@ -78,7 +78,7 @@ async fn test_between_steps_zombie_restart_reuses_all_children( "id": "inner", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "input_transforms": { "v": { "type": "javascript", "expr": "flow_input.iter.value" } }, @@ -91,7 +91,7 @@ async fn test_between_steps_zombie_restart_reuses_all_children( "id": "after", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "input_transforms": { "loop_res": { "type": "javascript", "expr": "results.fanout" } }, @@ -210,7 +210,7 @@ async fn test_mid_iteration_zombie_not_reused(db: Pool) -> anyhow::Res "id": "inner", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "input_transforms": { "v": { "type": "javascript", "expr": "flow_input.iter.value" } }, @@ -223,7 +223,7 @@ async fn test_mid_iteration_zombie_not_reused(db: Pool) -> anyhow::Res "id": "after", "value": { "type": "rawscript", - "language": "deno", + "language": "bun", "input_transforms": { "loop_res": { "type": "javascript", "expr": "results.fanout" } }, @@ -331,7 +331,7 @@ async fn test_nested_restart_not_swallowed_by_zombie_reuse( { "id": "inner_first", "value": { - "type": "rawscript", "language": "deno", + "type": "rawscript", "language": "bun", "input_transforms": {}, "content": "export function main() { return 'first' }" } @@ -339,7 +339,7 @@ async fn test_nested_restart_not_swallowed_by_zombie_reuse( { "id": "inner_second", "value": { - "type": "rawscript", "language": "deno", + "type": "rawscript", "language": "bun", "input_transforms": { "first": { "type": "javascript", "expr": "results.inner_first" } }, @@ -353,7 +353,7 @@ async fn test_nested_restart_not_swallowed_by_zombie_reuse( { "id": "after", "value": { - "type": "rawscript", "language": "deno", + "type": "rawscript", "language": "bun", "input_transforms": { "b": { "type": "javascript", "expr": "results.branch" } }, @@ -466,7 +466,7 @@ async fn test_raw_flow_restart_does_not_reuse_edited_step( "modules": [{ "id": "inner", "value": { - "type": "rawscript", "language": "deno", + "type": "rawscript", "language": "bun", "input_transforms": { "v": { "type": "javascript", "expr": "flow_input.iter.value" } }, @@ -478,7 +478,7 @@ async fn test_raw_flow_restart_does_not_reuse_edited_step( { "id": "after", "value": { - "type": "rawscript", "language": "deno", + "type": "rawscript", "language": "bun", "input_transforms": { "loop_res": { "type": "javascript", "expr": "results.fanout" } }, @@ -578,7 +578,7 @@ async fn test_non_monitor_cancel_is_not_reused(db: Pool) -> anyhow::Re "modules": [{ "id": "inner", "value": { - "type": "rawscript", "language": "deno", + "type": "rawscript", "language": "bun", "input_transforms": { "v": { "type": "javascript", "expr": "flow_input.iter.value" } }, @@ -590,7 +590,7 @@ async fn test_non_monitor_cancel_is_not_reused(db: Pool) -> anyhow::Re { "id": "after", "value": { - "type": "rawscript", "language": "deno", + "type": "rawscript", "language": "bun", "input_transforms": { "loop_res": { "type": "javascript", "expr": "results.fanout" } }, diff --git a/backend/windmill-ai/Cargo.toml b/backend/windmill-ai/Cargo.toml index b1dea3ae54..38f62fa16f 100644 --- a/backend/windmill-ai/Cargo.toml +++ b/backend/windmill-ai/Cargo.toml @@ -12,6 +12,8 @@ mcp = ["dep:windmill-mcp"] [lib] name = "windmill_ai" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [dependencies] windmill-common = { workspace = true, default-features = false } @@ -28,6 +30,7 @@ eventsource-stream.workspace = true futures.workspace = true http.workspace = true mime_guess.workspace = true +rand.workspace = true reqwest.workspace = true serde.workspace = true serde_json.workspace = true diff --git a/backend/windmill-ai/src/ai_bedrock.rs b/backend/windmill-ai/src/ai_bedrock.rs index a9318a1f3a..f55fcca415 100644 --- a/backend/windmill-ai/src/ai_bedrock.rs +++ b/backend/windmill-ai/src/ai_bedrock.rs @@ -477,6 +477,29 @@ pub async fn assume_role_with_oidc_token( // Error Formatting // ============================================================================ +/// The error for a Bedrock stream that failed after it opened, retrying the exceptions the +/// Vercel AI SDK retries (`amazon-bedrock-stream-error.ts`) and a broken connection. The +/// SDK's own retries cover the opening call alone. +pub fn bedrock_stream_error( + error: &aws_sdk_bedrockruntime::error::SdkError< + aws_sdk_bedrockruntime::types::error::ConverseStreamOutputError, + R, + >, +) -> Error { + let message = format!("Bedrock stream error: {}", format_bedrock_error(error)); + match error.as_service_error() { + Some(e) + if !(e.is_internal_server_exception() + || e.is_model_stream_error_exception() + || e.is_service_unavailable_exception() + || e.is_throttling_exception()) => + { + Error::AIError(message) + } + _ => crate::retry::transient_error(message, None), + } +} + /// Format AWS SDK errors with detailed information pub fn format_bedrock_error(error: &aws_sdk_bedrockruntime::error::SdkError) -> String where diff --git a/backend/windmill-ai/src/ai_google.rs b/backend/windmill-ai/src/ai_google.rs index bb8ae83e13..9f48edca8a 100644 --- a/backend/windmill-ai/src/ai_google.rs +++ b/backend/windmill-ai/src/ai_google.rs @@ -326,6 +326,17 @@ pub struct GeminiSSEEvent { pub candidates: Option>, #[serde(rename = "usageMetadata")] pub usage_metadata: Option, + #[serde(default)] + pub error: Option, + #[serde(rename = "promptFeedback", default)] + pub prompt_feedback: Option, +} + +/// Set when Gemini refuses the prompt itself, in which case no candidate follows. +#[derive(Deserialize, Debug)] +pub struct GeminiPromptFeedback { + #[serde(rename = "blockReason", default)] + pub block_reason: Option, } // ============================================================================ @@ -550,10 +561,40 @@ pub fn openai_tools_to_gemini( } } +/// Follows a Gemini stream to tell a complete turn from one cut short. +#[derive(Default)] +pub struct GeminiTurn { + ended: bool, + has_output: bool, +} + +impl GeminiTurn { + pub fn observe(&mut self, event: &GeminiParsedEvent) { + // A function call arrives whole and may come without a `finishReason`, so it + // counts too, as in gemini-cli's stream validation. + self.ended |= event.finish_reason.is_some() || !event.tool_calls.is_empty(); + self.has_output |= event.text.is_some() || event.reasoning.is_some(); + } + + /// Whether the turn's final event arrived. + pub fn ended(&self) -> bool { + self.ended + } + + /// Whether a stream that closed cleanly here holds the whole turn. Gemini 2.5 closes + /// its stream without a single event when thinking spends the whole + /// `maxOutputTokens`: an empty answer, which a retry would only get again, rather + /// than a cut one. + pub fn complete_at_close(&self) -> bool { + self.ended || !self.has_output + } +} + /// Parse one Gemini SSE data line into a [`GeminiParsedEvent`]. /// /// Returns `Ok(None)` for empty data or unrecognised payloads (e.g. `"[DONE]"`). /// Logs a warning and returns `Ok(None)` on JSON parse errors rather than propagating. +/// An error the stream reports is returned as one. pub fn parse_gemini_sse_event(data: &str) -> Result, Error> { if data.is_empty() || data == "[DONE]" { return Ok(None); @@ -567,6 +608,21 @@ pub fn parse_gemini_sse_event(data: &str) -> Result, E } }; + if let Some(error) = event.error { + return Err(error.into_error("Gemini")); + } + + // `BLOCK_REASON_UNSPECIFIED` is the protobuf enum's placeholder, not a block. + if let Some(reason) = event + .prompt_feedback + .and_then(|f| f.block_reason) + .filter(|r| !matches!(r.as_str(), "" | "BLOCK_REASON_UNSPECIFIED")) + { + return Err(Error::AIError(format!( + "Gemini blocked the prompt: {reason}" + ))); + } + let mut parsed = GeminiParsedEvent { usage: event.usage_metadata, ..Default::default() }; let Some(candidates) = event.candidates else { diff --git a/backend/windmill-ai/src/ai_providers.rs b/backend/windmill-ai/src/ai_providers.rs index 3b3af833d6..311c8d3eb7 100644 --- a/backend/windmill-ai/src/ai_providers.rs +++ b/backend/windmill-ai/src/ai_providers.rs @@ -5,6 +5,9 @@ use serde::{Deserialize, Deserializer, Serialize}; use windmill_common::db::DB; use windmill_common::error::{Error, Result}; +use windmill_common::ssrf::{PrivateHostAllowance, SsrfValidationError, ValidatedTarget}; + +const ALLOW_PRIVATE_AI_BASE_URLS_ENV: &str = "ALLOW_PRIVATE_AI_BASE_URLS"; /// Deserializes an Option where empty strings become None. /// Use with `#[serde(default, deserialize_with = "empty_string_as_none")]` @@ -20,10 +23,10 @@ where lazy_static::lazy_static! { static ref OPENAI_AZURE_BASE_PATH: Option = std::env::var("OPENAI_AZURE_BASE_PATH").ok(); - pub static ref ALLOW_PRIVATE_AI_BASE_URLS: bool = std::env::var("ALLOW_PRIVATE_AI_BASE_URLS") - .ok() - .map(|v| v == "true" || v == "1") - .unwrap_or(false); + /// Covers every AI base URL, whoever supplied it: the workspace or instance AI config, a + /// resource a member picked, or an inline resource value sent to the proxy. + pub static ref ALLOW_PRIVATE_AI_BASE_URLS: PrivateHostAllowance = + PrivateHostAllowance::from_env(ALLOW_PRIVATE_AI_BASE_URLS_ENV); /// Drops the cache breakpoints from agent-step requests on every Anthropic platform, /// not just the one that motivates it: a Google Cloud project can have explicit prompt /// caching turned off (by request to Cloud support), and Vertex then rejects any request @@ -131,6 +134,23 @@ pub enum AIProvider { Cloudflare, } +/// Check an AI endpoint URL against the SSRF rules, allowing the private hosts +/// `ALLOW_PRIVATE_AI_BASE_URLS` names. Callers that connect next pin the returned target. +pub async fn validate_ai_url(url: &str) -> Result { + windmill_common::ssrf::validate_url_for_ssrf_allowing(url, &ALLOW_PRIVATE_AI_BASE_URLS) + .await + .map_err(|e| match e { + // Only a private target is fixed by the env var; for a malformed URL or bad + // scheme the hint would send users the wrong way (issue #9171). + e @ SsrfValidationError::Private { .. } => Error::BadRequest(format!( + "{e}. To use a private/internal AI endpoint, add its host (host, host:port or \ + CIDR range) to the comma-separated {ALLOW_PRIVATE_AI_BASE_URLS_ENV} environment \ + variable, or set it to true to allow every private host" + )), + e => Error::from(e), + }) +} + /// The Workers AI models URL of a Cloudflare account. The id goes into the path, so it is held to /// the characters an account id has rather than trusted to stay inside its segment. pub fn cloudflare_workers_ai_base_url(account_id: Option<&str>) -> Result { @@ -161,22 +181,7 @@ impl AIProvider { /// Get the base URL for the AI provider pub async fn get_base_url(&self, resource_base_url: Option, db: &DB) -> Result { if let Some(base_url) = resource_base_url { - if !*ALLOW_PRIVATE_AI_BASE_URLS { - use windmill_common::ssrf::SsrfValidationError; - windmill_common::ssrf::validate_url_for_ssrf(&base_url) - .await - .map_err(|e| match e { - // The env-var hint is only actionable when the URL is - // well-formed but blocked for targeting a private - // address. For a malformed URL or bad scheme, surface - // the real error so users fix the URL (issue #9171). - e @ SsrfValidationError::Private { .. } => Error::BadRequest(format!( - "{e}. If you need to use private/internal AI endpoints, \ - set the ALLOW_PRIVATE_AI_BASE_URLS=true environment variable" - )), - e => Error::from(e), - })?; - } + validate_ai_url(&base_url).await?; return Ok(base_url); } diff --git a/backend/windmill-ai/src/lib.rs b/backend/windmill-ai/src/lib.rs index ccc40da432..634614a3cf 100644 --- a/backend/windmill-ai/src/lib.rs +++ b/backend/windmill-ai/src/lib.rs @@ -11,6 +11,7 @@ pub mod model_context; pub mod providers; pub mod proxy; pub mod query_builder; +pub mod retry; pub mod sse; pub mod types; pub mod utils; diff --git a/backend/windmill-ai/src/providers/bedrock.rs b/backend/windmill-ai/src/providers/bedrock.rs index 836244a666..5aa142a127 100644 --- a/backend/windmill-ai/src/providers/bedrock.rs +++ b/backend/windmill-ai/src/providers/bedrock.rs @@ -9,11 +9,12 @@ use super::{anthropic_model_rejects_sampling_params, REASONING_OFF_SENTINEL}; use crate::{ ai_bedrock::{ - bedrock_model_supports_prompt_caching, bedrock_stream_event_is_block_stop, - bedrock_stream_event_to_reasoning_delta, bedrock_stream_event_to_text, - bedrock_stream_event_to_tool_delta, bedrock_stream_event_to_tool_delta_with_block_index, - bedrock_stream_event_to_tool_start, bedrock_stream_event_to_tool_start_with_block_index, - build_tool_config, create_inference_config, format_bedrock_error, json_to_document, + bedrock_model_supports_prompt_caching, bedrock_stream_error, + bedrock_stream_event_is_block_stop, bedrock_stream_event_to_reasoning_delta, + bedrock_stream_event_to_text, bedrock_stream_event_to_tool_delta, + bedrock_stream_event_to_tool_delta_with_block_index, bedrock_stream_event_to_tool_start, + bedrock_stream_event_to_tool_start_with_block_index, build_tool_config, + create_inference_config, format_bedrock_error, json_to_document, openai_messages_to_bedrock, streaming_tool_calls_to_openai, BearerTokenProvider, BedrockClient, StreamingToolCall, }, @@ -24,6 +25,7 @@ use crate::{ image_handler::prepare_messages_for_api, proxy::ProxyBuildArgs, query_builder::{ParsedResponse, StreamEventSink}, + retry::{openai_stream_error_chunk, truncated_stream_error}, types::{OpenAIMessage, StreamingEvent, TokenUsage, ToolDef}, }; use bytes::Bytes; @@ -461,26 +463,31 @@ pub fn sdk_stream_to_sse( async_stream::stream! { let mut stream = stream; let mut state = BedrockSseStreamState::new(id, model, created); + let mut message_stopped = false; - loop { + let failure = loop { match stream.recv().await { Ok(Some(event)) => { + if matches!( + event, + aws_sdk_bedrockruntime::types::ConverseStreamOutput::MessageStop(_) + ) { + message_stopped = true; + } for chunk in bedrock_sse_chunks_for_event(&event, &mut state) { yield Ok(chunk); } } - Ok(None) => break, - Err(e) => { - yield Err(std::io::Error::new( - std::io::ErrorKind::Other, - e.to_string(), - )); - break; - } + Ok(None) => break (!message_stopped).then(truncated_stream_error), + Err(_) if message_stopped => break None, + Err(e) => break Some(bedrock_stream_error(&e)), } - } + }; - yield Ok(Bytes::from("data: [DONE]\n\n")); + match failure { + Some(error) => yield Ok(Bytes::from(openai_stream_error_chunk(&error))), + None => yield Ok(Bytes::from("data: [DONE]\n\n")), + } } } @@ -1081,11 +1088,19 @@ impl BedrockQueryBuilder { // Claude reasoning block for the turn (only populated when thinking is on), // attached to the first tool call for replay before toolUse. let mut reasoning: Option = None; + let mut message_stopped = false; // Process stream events using shared parsing functions loop { match stream.recv().await { Ok(Some(event)) => { + if matches!( + event, + aws_sdk_bedrockruntime::types::ConverseStreamOutput::MessageStop(_) + ) { + message_stopped = true; + } + // Fold reasoning deltas into the turn's reasoning block (for // replay before toolUse, required by Claude when thinking is // on) and stream the readable summary as a thinking affordance. @@ -1161,11 +1176,13 @@ impl BedrockQueryBuilder { } } Ok(None) => break, - Err(e) => { - return Err(Error::internal_err(format!("Bedrock stream error: {}", e))); - } + Err(_) if message_stopped => break, + Err(e) => return Err(bedrock_stream_error(&e)), } } + if !message_stopped { + return Err(truncated_stream_error()); + } // Send tool call events to stream processor if let Some(processor) = stream_event_sink.as_ref() { diff --git a/backend/windmill-ai/src/providers/google_ai.rs b/backend/windmill-ai/src/providers/google_ai.rs index 97d0383ba4..bbf45e5e57 100644 --- a/backend/windmill-ai/src/providers/google_ai.rs +++ b/backend/windmill-ai/src/providers/google_ai.rs @@ -5,17 +5,20 @@ use crate::{ parse_gemini_response, parse_gemini_sse_event, sanitize_schema_for_google, GeminiFunctionDeclaration, GeminiGenerationConfig, GeminiImageContent, GeminiImageRequest, GeminiImageResponse, GeminiInlineData, GeminiPart, GeminiPredictContent, GeminiTextRequest, - GeminiThinkingConfig, GeminiTool, + GeminiThinkingConfig, GeminiTool, GeminiTurn, }, image_handler::{download_and_encode_s3_image, prepare_messages_for_api}, proxy::{ProxyBuildArgs, ProxyRequest}, query_builder::{BuildRequestArgs, ParsedResponse, QueryBuilder, StreamEventSink}, + retry::{ + openai_stream_error_chunk, send_with_retries, transient_error, truncated_stream_error, + }, sse::{GeminiSSEParser, SSEParser}, types::*, }; use async_trait::async_trait; use bytes::Bytes; -use eventsource_stream::Eventsource; +use eventsource_stream::{EventStreamError, Eventsource}; use futures::{stream::BoxStream, StreamExt}; use http::{header, HeaderMap, HeaderValue, Method, StatusCode}; use serde::Deserialize; @@ -336,9 +339,7 @@ pub async fn handle_google_ai_chat_proxy( ) -> Result { let GoogleAIProxyRequest { request, model, stream } = build_google_ai_chat_proxy_request(args)?; - let response = - send_google_ai_proxy_request(client, request, "Failed to send request to Gemini API") - .await?; + let response = send_google_ai_proxy_request(client, request).await?; if stream { Ok(convert_streaming_response(response, &model)) @@ -356,8 +357,7 @@ pub async fn handle_google_ai_models_proxy( args: &ProxyBuildArgs<'_>, ) -> Result { let request = build_google_ai_models_proxy_request(args); - let response = - send_google_ai_proxy_request(client, request, "Failed to fetch Gemini models").await?; + let response = send_google_ai_proxy_request(client, request).await?; let gemini_resp: GeminiModelsResponse = response.json().await.map_err(|e| { Error::internal_err(format!("Failed to parse Gemini models response: {}", e)) @@ -505,26 +505,13 @@ fn add_google_ai_auth_header(headers: &mut Vec<(String, String)>, api_key: &str, async fn send_google_ai_proxy_request( client: &reqwest::Client, proxy_request: ProxyRequest, - send_error_message: &str, ) -> Result { let mut request = client.request(proxy_request.method.clone(), &proxy_request.url); for (header_name, header_value) in &proxy_request.headers { request = request.header(header_name.as_str(), header_value.as_str()); } - let response = request - .body(proxy_request.body) - .send() - .await - .map_err(|e| Error::internal_err(format!("{}: {}", send_error_message, e)))?; - - if let Err(e) = response.error_for_status_ref() { - let status = e.status().map(|s| s.to_string()).unwrap_or_default(); - let body = response.text().await.unwrap_or_default(); - return Err(Error::AIError(format!("{}: {}", status, body))); - } - - Ok(response) + send_with_retries(request.body(proxy_request.body)).await } fn convert_streaming_response(response: reqwest::Response, model: &str) -> GoogleAIProxyResponse { @@ -535,10 +522,15 @@ fn convert_streaming_response(response: reqwest::Response, model: &str) -> Googl let openai_sse_stream = async_stream::stream! { tokio::pin!(gemini_sse_stream); let mut tool_call_index: usize = 0; - while let Some(event) = gemini_sse_stream.next().await { + let mut turn = GeminiTurn::default(); + let failure = loop { + let Some(event) = gemini_sse_stream.next().await else { + break (!turn.complete_at_close()).then(truncated_stream_error); + }; match event { Ok(event) => match parse_gemini_sse_event(&event.data) { Ok(Some(parsed)) => { + turn.observe(&parsed); for chunk in gemini_event_to_openai_sse_chunks( &parsed, &id, &model, &mut tool_call_index, ) { @@ -546,12 +538,23 @@ fn convert_streaming_response(response: reqwest::Response, model: &str) -> Googl } } Ok(None) => {} - Err(e) => tracing::error!("Error parsing Gemini SSE event: {}", e), + Err(e) => break Some(e), }, + Err(EventStreamError::Transport(_)) if turn.ended() => break None, + Err(EventStreamError::Transport(e)) => { + break Some(transient_error( + format!("The connection to Gemini broke off mid-response: {e}"), + None, + )); + } Err(e) => tracing::error!("Error reading Gemini SSE stream: {}", e), } - } - yield Ok::(Bytes::from("data: [DONE]\n\n")); + }; + let last = match failure { + Some(error) => openai_stream_error_chunk(&error), + None => "data: [DONE]\n\n".to_string(), + }; + yield Ok::(Bytes::from(last)); } .boxed(); diff --git a/backend/windmill-ai/src/providers/mod.rs b/backend/windmill-ai/src/providers/mod.rs index 7dcddc93a3..82dceaa02f 100644 --- a/backend/windmill-ai/src/providers/mod.rs +++ b/backend/windmill-ai/src/providers/mod.rs @@ -30,6 +30,11 @@ pub fn effective_reasoning_effort<'a>(model: &str, effort: Option<&'a str>) -> O } } +/// Whether Chat Completions refuses function tools while this model reasons. +pub(crate) fn completions_rejects_tools_with_reasoning(model: &str) -> bool { + reasoning_rule(model).is_some_and(|rule| rule.completions_tools_need_off) +} + /// Whether a request with function tools must send the off sentinel on Chat Completions: /// the model refuses tools there while it reasons, and does accept being turned off. pub(crate) fn completions_tools_need_reasoning_off(model: &str) -> bool { @@ -208,6 +213,12 @@ pub fn create_query_builder( AIProvider::AzureFoundry if AIProvider::is_anthropic_model(model) => Box::new( AnthropicQueryBuilder::new(AIProvider::AzureFoundry, AIPlatform::Standard), ), + // Foundry serves its OpenAI models on `/openai/v1/responses` too. `/chat/completions` + // takes function tools from these only with reasoning off, which gpt-6.1-sol and + // gpt-6-astra cannot do at all. + AIProvider::AzureFoundry if completions_rejects_tools_with_reasoning(model) => { + Box::new(OpenAIQueryBuilder::new(AIProvider::AzureFoundry)) + } // Only for forwarding through the API proxy, which is bearer auth on `/` as // TypeSafe and Cloudflare expect. Neither serves a chat route for its decision models, and // `run_agent` refuses both before a chat request could be built. @@ -408,6 +419,12 @@ mod parity_tests { "claude-sonnet-5", "v1/messages", ), + case( + AIProvider::AzureFoundry, + "https://example.services.ai.azure.com", + "gpt-6.1-sol", + "responses", + ), case( AIProvider::AzureOpenAI, "https://example.openai.azure.com/openai", diff --git a/backend/windmill-ai/src/providers/other.rs b/backend/windmill-ai/src/providers/other.rs index 1ea54a7e79..fea8edbdac 100644 --- a/backend/windmill-ai/src/providers/other.rs +++ b/backend/windmill-ai/src/providers/other.rs @@ -266,6 +266,7 @@ impl QueryBuilder for OtherQueryBuilder { mut events_str, stream_event_processor, usage: openai_usage, + .. } = openai_sse_parser; // Process streaming events with error handling diff --git a/backend/windmill-ai/src/proxy.rs b/backend/windmill-ai/src/proxy.rs index 887cab0f3e..ca6ee1b59b 100644 --- a/backend/windmill-ai/src/proxy.rs +++ b/backend/windmill-ai/src/proxy.rs @@ -19,6 +19,25 @@ pub struct ProxyBuildArgs<'a> { pub credentials: &'a ProviderCredentials, } +/// Refuses a client-supplied proxy path that could resolve outside the provider's base +/// path once appended to it. URL parsing treats `\` as `/`, drops tabs and newlines, trims +/// spaces and ends the path at `?` or `#`, so `.\t./`, `..\`, `.. ` and `..?x` climb a +/// segment like `../`. The path arrives decoded once, so any `%` left is a second encoding +/// (`%2e`, `%2f`) that the URL parser or a gateway in front of the provider may decode again. +pub fn validate_proxy_path(path: &str) -> Result<()> { + let invalid = || Error::BadRequest(format!("Invalid AI proxy path: {path}")); + if path + .chars() + .any(|c| matches!(c, '\\' | ' ' | '?' | '#' | '%') || c.is_control()) + || path + .split('/') + .any(|segment| segment == "." || segment == "..") + { + return Err(invalid()); + } + Ok(()) +} + /// Provider-specific request produced by proxy request builders. #[derive(Clone, Debug)] pub struct ProxyRequest { @@ -271,6 +290,39 @@ mod tests { } } + #[test] + fn proxy_path_refuses_dot_segments() { + for path in [ + "chat/completions", + "v1/messages", + "models", + "openai/deployments/gpt-4.1/chat/completions", + "a..b/c", + ] { + assert!(validate_proxy_path(path).is_ok(), "{path}"); + } + for path in [ + "../key/info", + "..", + "models/../../key/info", + "./x", + "%2e%2e/key/info", + "%2E./key/info", + ".%2E/key/info", + "..\\key/info", + ".\t./key/info", + "..\n/key/info", + ".. ", + "..?x=1", + "..#f", + "%2e%2e?x", + "..%2fkey/info", + "%2e%2e%2fkey", + ] { + assert!(validate_proxy_path(path).is_err(), "{path:?}"); + } + } + #[test] fn builds_openai_compatible_proxy_request() { let credentials = credentials(AIProvider::OpenRouter, "https://openrouter.ai/api/v1/"); diff --git a/backend/windmill-ai/src/retry.rs b/backend/windmill-ai/src/retry.rs new file mode 100644 index 0000000000..9de9d309da --- /dev/null +++ b/backend/windmill-ai/src/retry.rs @@ -0,0 +1,474 @@ +use std::time::Duration; + +use reqwest::{header::HeaderMap, RequestBuilder, Response, StatusCode}; +use windmill_common::error::{to_anyhow, Error}; + +/// How many times a provider call is retried after its first attempt. +pub const MAX_RETRIES: u32 = 3; +const BASE_DELAY: Duration = Duration::from_secs(1); +const MAX_BACKOFF: Duration = Duration::from_secs(10); +/// A provider that asks for a longer wait is out of capacity for longer than anyone should +/// block on (a spent daily quota, say), so its error is returned instead of waited out. +const MAX_RETRY_AFTER: Duration = Duration::from_secs(60); + +/// A provider call that failed for a reason a later attempt may not meet: the provider was +/// overloaded, throttled or unreachable, or its response broke off part way. +#[derive(Debug)] +pub struct TransientAIError { + pub message: String, + /// The wait the provider asked for, when it named one. + pub retry_after: Option, +} + +impl std::fmt::Display for TransientAIError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.message) + } +} + +impl std::error::Error for TransientAIError {} + +pub fn transient_error(message: impl Into, retry_after: Option) -> Error { + to_anyhow(TransientAIError { message: message.into(), retry_after }).into() +} + +pub fn as_transient(error: &Error) -> Option<&TransientAIError> { + match error { + Error::Anyhow { error, .. } => error.downcast_ref::(), + _ => None, + } +} + +/// The error to report once a transient failure is no longer retried, without the source +/// location `Error::Anyhow` renders. +pub fn into_final_error(error: Error) -> Error { + match as_transient(&error) { + Some(transient) => Error::AIError(transient.message.clone()), + None => error, + } +} + +/// The statuses the OpenAI and Anthropic SDKs and the Vercel AI SDK retry. +fn is_retryable_status(status: u16) -> bool { + matches!(status, 408 | 409 | 429 | 500..=599) +} + +/// The error for a provider's error response. The rules follow the OpenAI and Anthropic +/// SDKs (`x-should-retry`, then the status) and gemini-cli (a daily quota is spent until +/// tomorrow, and the wait Gemini asks for is in its body). +pub fn response_error( + status: StatusCode, + headers: &HeaderMap, + body: &str, + message: String, +) -> Error { + let retryable = match headers.get("x-should-retry").and_then(|v| v.to_str().ok()) { + Some("true") => true, + Some("false") => false, + _ => { + is_retryable_status(status.as_u16()) + // OpenAI answers a spent balance with the 429 it also uses for rate limits. + && !body.contains("insufficient_quota") + && !google_quota_spent_for_the_day(body) + } + }; + if retryable { + transient_error( + message, + retry_after(headers).or_else(|| google_retry_delay(body)), + ) + } else { + Error::AIError(message) + } +} + +/// The `details` of a Google API error body, where Gemini puts its quota and retry hints. +fn google_error_details(body: &str) -> Vec { + serde_json::from_str::(body) + .ok() + .and_then(|v| v.get("error")?.get("details")?.as_array().cloned()) + .unwrap_or_default() +} + +fn google_quota_spent_for_the_day(body: &str) -> bool { + google_error_details(body).iter().any(|detail| { + detail + .get("violations") + .and_then(|v| v.as_array()) + .is_some_and(|violations| { + violations.iter().any(|violation| { + violation + .get("quotaId") + .and_then(|id| id.as_str()) + .is_some_and(|id| id.contains("PerDay") || id.contains("Daily")) + }) + }) + }) +} + +/// The `RetryInfo.retryDelay` of a Google API error, a protobuf duration such as `"53s"`. +fn google_retry_delay(body: &str) -> Option { + google_error_details(body).iter().find_map(|detail| { + let delay = detail.get("retryDelay")?.as_str()?.strip_suffix('s')?; + let seconds = delay + .parse::() + .ok() + .filter(|v| v.is_finite() && *v >= 0.0)?; + Some(Duration::try_from_secs_f64(seconds).unwrap_or(Duration::MAX)) + }) +} + +/// The wait a provider asked for in its `retry-after-ms` or `retry-after` header. An +/// HTTP-date `retry-after` is ignored, which falls back to the computed backoff. +fn retry_after(headers: &HeaderMap) -> Option { + let seconds = |name: &str, scale: f64| { + headers + .get(name)? + .to_str() + .ok()? + .trim() + .parse::() + .ok() + .filter(|v| v.is_finite() && *v >= 0.0) + .map(|v| Duration::try_from_secs_f64(v / scale).unwrap_or(Duration::MAX)) + }; + seconds("retry-after-ms", 1000.0).or_else(|| seconds("retry-after", 1.0)) +} + +/// The error object a provider sends inside a stream: OpenAI-compatible chunks carry +/// `type` and a string or status `code`, Anthropic `type`, Gemini a status `code` and +/// `status`. +#[derive(Debug, Default, serde::Deserialize)] +pub struct StreamErrorBody { + #[serde(default)] + pub message: Option, + #[serde(default, rename = "type")] + pub kind: Option, + #[serde(default)] + pub code: Option, + #[serde(default)] + pub status: Option, +} + +impl StreamErrorBody { + /// The error for a failure an OpenAI-compatible or Gemini stream reported after opening + /// with a 200, classified as the Vercel AI SDK classifies OpenAI stream errors + /// (`openai-stream-error.ts`): the status `code` holds, else the status its code and type + /// name, else a server error. + pub fn into_error(self, provider: &str) -> Error { + let code = self.code_str(); + let discriminator = [code.as_deref(), self.kind.as_deref()] + .into_iter() + .flatten() + .collect::>() + .join(" ") + .to_lowercase(); + let has = |terms: &[&str]| terms.iter().any(|term| discriminator.contains(term)); + let status = match code.as_deref().and_then(|code| code.parse::().ok()) { + Some(status @ 400..=599) => status, + _ if has(&["insufficient_quota", "rate_limit"]) => 429, + _ if has(&["authentication"]) => 401, + _ if has(&["permission"]) => 403, + _ if has(&["not_found"]) => 404, + _ if has(&["invalid", "bad_request", "context_length"]) => 400, + _ if has(&["overload"]) => 503, + _ if has(&["timeout"]) => 504, + _ => 500, + }; + let retryable = !has(&["insufficient_quota"]) && is_retryable_status(status); + self.into_classified_error(provider, retryable) + } + + /// The error for a failure an Anthropic stream reported after opening with a 200. The + /// kinds retried are those the Vercel AI SDK retries, plus `timeout_error`, which + /// Anthropic documents as its 504; any other kind is a fault in the request or account. + pub fn into_anthropic_error(self) -> Error { + let retryable = matches!( + self.kind.as_deref(), + Some("api_error" | "overloaded_error" | "rate_limit_error" | "timeout_error") + ); + self.into_classified_error("Anthropic", retryable) + } + + fn code_str(&self) -> Option { + match self.code.as_ref()? { + serde_json::Value::String(code) => Some(code.clone()), + serde_json::Value::Number(code) => Some(code.to_string()), + _ => None, + } + } + + fn into_classified_error(self, provider: &str, retryable: bool) -> Error { + let kind = [self.kind.clone(), self.code_str(), self.status] + .into_iter() + .flatten() + .collect::>() + .join("/"); + let message = format!( + "{provider} stream error{}: {}", + (!kind.is_empty()) + .then(|| format!(" ({kind})")) + .unwrap_or_default(), + self.message.as_deref().unwrap_or("no details") + ); + if retryable { + transient_error(message, None) + } else { + Error::AIError(message) + } + } +} + +/// The error for a stream that closed before the provider sent the event ending a +/// complete response: cut off by the provider or by a proxy in between. +pub fn truncated_stream_error() -> Error { + transient_error( + "The AI provider's response stream ended before the response was complete", + None, + ) +} + +/// An OpenAI-format stream chunk reporting `error`, which ends a response converted to that +/// format after it started streaming: the chat's OpenAI SDK throws on a chunk carrying +/// `error`, where a bare end of stream would read as a finished answer. +pub fn openai_stream_error_chunk(error: &Error) -> String { + let message = as_transient(error).map_or_else(|| error.to_string(), |t| t.message.clone()); + format!( + "data: {}\n\n", + serde_json::json!({ "error": { "message": message } }) + ) +} + +/// Sends a provider request, retrying a transient failure while nothing of the response +/// has been read: a failed connection or an error status. Once retries are spent the error +/// carries the provider's answer, as a single attempt's would. +pub async fn send_with_retries(request: RequestBuilder) -> Result { + let mut backoff = Backoff::default(); + loop { + // A streamed body cannot be replayed, so such a request is sent once. + let Some(attempt) = request.try_clone() else { + return send_once(request).await.map_err(into_final_error); + }; + let error = match send_once(attempt).await { + Ok(response) => return Ok(response), + Err(error) => error, + }; + let Some(delay) = as_transient(&error).and_then(|t| backoff.next_delay(t)) else { + return Err(into_final_error(error)); + }; + tracing::warn!( + "AI provider call failed ({error}); retrying in {:.1}s ({}/{MAX_RETRIES})", + delay.as_secs_f64(), + backoff.retries() + ); + tokio::time::sleep(delay).await; + } +} + +/// The error for a provider request that failed before any response arrived. The request +/// timeout is the caller's whole budget, so a timed-out call leaves no time for another +/// attempt; a connect timeout has its own, shorter one. +pub fn send_error(e: reqwest::Error, context: &str) -> Error { + let message = format!("{context}: {e}"); + if e.is_builder() || (e.is_timeout() && !e.is_connect()) { + Error::AIError(message) + } else { + transient_error(message, None) + } +} + +async fn send_once(request: RequestBuilder) -> Result { + let response = request + .send() + .await + .map_err(|e| send_error(e, "Failed to reach the AI provider"))?; + let status = response.status(); + if status.is_client_error() || status.is_server_error() { + let headers = response.headers().clone(); + let body = response.text().await.unwrap_or_default(); + return Err(response_error(status, &headers, &body, body.clone())); + } + Ok(response) +} + +/// Counts the retries of one provider call and spaces them out. +#[derive(Debug, Default)] +pub struct Backoff { + retries: u32, +} + +impl Backoff { + /// The wait before retrying a call that failed with `error`, or `None` once it should + /// fail instead. + pub fn next_delay(&mut self, error: &TransientAIError) -> Option { + if self.retries >= MAX_RETRIES { + return None; + } + let delay = match error.retry_after { + Some(wait) if wait > MAX_RETRY_AFTER => return None, + // A zero wait would retry back to back, so it gets the computed backoff. + Some(wait) if !wait.is_zero() => wait, + // Jittered, so callers throttled together do not come back together. + _ => (BASE_DELAY * 2u32.pow(self.retries)) + .min(MAX_BACKOFF) + .mul_f64(0.5 + rand::random::() * 0.5), + }; + self.retries += 1; + Some(delay) + } + + /// Retries granted so far. + pub fn retries(&self) -> u32 { + self.retries + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Error responses as providers send them, each with the retry decision of the client + /// the rule is taken from. + #[test] + fn classifies_error_responses() { + const GEMINI_QUOTA: &str = r#"{"error":{"code":429,"status":"RESOURCE_EXHAUSTED","details":[{"@type":"type.googleapis.com/google.rpc.QuotaFailure","violations":[{"quotaId":"QUOTA_ID"}]},{"@type":"type.googleapis.com/google.rpc.RetryInfo","retryDelay":"53s"}]}}"#; + let cases: &[(u16, &[(&str, &str)], &str, Option>)] = &[ + ( + 429, + &[], + r#"{"error":{"code":"rate_limit_exceeded"}}"#, + Some(None), + ), + ( + 429, + &[], + r#"{"error":{"type":"insufficient_quota","code":"insufficient_quota"}}"#, + None, + ), + ( + 529, + &[], + r#"{"type":"error","error":{"type":"overloaded_error"}}"#, + Some(None), + ), + (501, &[], "", Some(None)), + (400, &[], "", None), + (401, &[], "", None), + (400, &[("x-should-retry", "true")], "", Some(None)), + (503, &[("x-should-retry", "false")], "", None), + (429, &[("retry-after", "2")], "", Some(Some(2))), + ( + 429, + &[], + &GEMINI_QUOTA.replace("QUOTA_ID", "GenerateRequestsPerMinutePerProjectPerModel"), + Some(Some(53)), + ), + ( + 429, + &[], + &GEMINI_QUOTA.replace( + "QUOTA_ID", + "GenerateRequestsPerDayPerProjectPerModel-FreeTier", + ), + None, + ), + ]; + for (status, headers, body, expected) in cases { + let headers = headers + .iter() + .map(|(k, v)| (k.parse().unwrap(), v.parse().unwrap())) + .collect::(); + let error = response_error( + StatusCode::from_u16(*status).unwrap(), + &headers, + body, + String::new(), + ); + let got = as_transient(&error).map(|t| t.retry_after.map(|d| d.as_secs())); + assert_eq!(&got, expected, "{status} {headers:?} {body}"); + } + } + + /// In-stream error objects as providers send them, after the 200 opened the stream. + #[test] + fn classifies_stream_errors() { + let retried = |json: &str, anthropic: bool| { + let body: StreamErrorBody = serde_json::from_str(json).unwrap(); + let error = if anthropic { + body.into_anthropic_error() + } else { + body.into_error("AI provider") + }; + as_transient(&error).is_some() + }; + for (json, expected) in [ + (r#"{"message":"m","type":"server_error"}"#, true), + ( + r#"{"message":"m","type":"requests","code":"rate_limit_exceeded"}"#, + true, + ), + ( + r#"{"message":"m","type":"insufficient_quota","code":"insufficient_quota"}"#, + false, + ), + ( + r#"{"message":"m","type":"invalid_request_error","code":"context_length_exceeded"}"#, + false, + ), + // LiteLLM's proxy puts the upstream status in `code` as a string. + (r#"{"message":"m","type":"None","code":"400"}"#, false), + (r#"{"message":"m","code":"503"}"#, true), + (r#"{"code":503,"message":"m","status":"UNAVAILABLE"}"#, true), + ( + r#"{"code":400,"message":"m","status":"INVALID_ARGUMENT"}"#, + false, + ), + (r#"{"message":"m"}"#, true), + ] { + assert_eq!(retried(json, false), expected, "{json}"); + } + for (kind, expected) in [ + ("overloaded_error", true), + ("api_error", true), + ("rate_limit_error", true), + ("timeout_error", true), + ("billing_error", false), + ("invalid_request_error", false), + ("some_new_error", false), + ] { + let json = format!(r#"{{"type":"{kind}","message":"m"}}"#); + assert_eq!(retried(&json, true), expected, "{kind}"); + } + } + + #[test] + fn honours_retry_after_up_to_a_bound() { + let mut headers = HeaderMap::new(); + headers.insert("retry-after", "2".parse().unwrap()); + assert_eq!(retry_after(&headers), Some(Duration::from_secs(2))); + headers.insert("retry-after-ms", "1500".parse().unwrap()); + assert_eq!(retry_after(&headers), Some(Duration::from_millis(1500))); + headers.remove("retry-after-ms"); + headers.insert("retry-after", "1e30".parse().unwrap()); + assert_eq!(retry_after(&headers), Some(Duration::MAX)); + + let mut backoff = Backoff::default(); + let asked = |secs| TransientAIError { + message: String::new(), + retry_after: Some(Duration::from_secs(secs)), + }; + assert_eq!(backoff.next_delay(&asked(5)), Some(Duration::from_secs(5))); + assert_eq!(backoff.next_delay(&asked(3600)), None); + } + + #[test] + fn stops_after_max_retries() { + let mut backoff = Backoff::default(); + let error = TransientAIError { message: String::new(), retry_after: None }; + for _ in 0..MAX_RETRIES { + let delay = backoff.next_delay(&error).expect("retry"); + assert!(delay <= MAX_BACKOFF); + } + assert_eq!(backoff.next_delay(&error), None); + } +} diff --git a/backend/windmill-ai/src/sse.rs b/backend/windmill-ai/src/sse.rs index ada50afca5..bdaa75025f 100644 --- a/backend/windmill-ai/src/sse.rs +++ b/backend/windmill-ai/src/sse.rs @@ -1,6 +1,6 @@ use std::collections::HashMap; -use eventsource_stream::Eventsource; +use eventsource_stream::{EventStreamError, Eventsource}; use indexmap::IndexMap; use reqwest::Response; use serde::Deserialize; @@ -8,12 +8,13 @@ use tokio_stream::StreamExt; use windmill_common::{error::Error, utils::rd_string}; use crate::{ - ai_google::{parse_gemini_sse_event, GeminiUsageMetadata}, + ai_google::{parse_gemini_sse_event, GeminiTurn, GeminiUsageMetadata}, ai_types::UrlCitation, ai_types::{ AnthropicExtraContent, ExtraContent, GoogleExtraContent, OpenAIFunction, OpenAIToolCall, }, query_builder::StreamEventSink, + retry::{transient_error, truncated_stream_error, StreamErrorBody}, types::{StreamingEvent, TokenUsage}, }; @@ -43,6 +44,8 @@ pub struct OpenAIChoiceDelta { #[derive(Deserialize)] pub struct OpenAIChoice { pub delta: Option, + #[serde(default)] + pub finish_reason: Option, } /// Nested prompt token details returned by the Chat Completions API. @@ -87,6 +90,8 @@ pub struct OpenAISSEEvent { pub choices: Option>, #[serde(default)] pub usage: Option, + #[serde(default)] + pub error: Option, } lazy_static::lazy_static! { @@ -99,6 +104,14 @@ lazy_static::lazy_static! { pub trait SSEParser { async fn parse_event_data(&mut self, data: &str) -> Result<(), Error>; + /// Whether the stream delivered the event that ends a complete response. + fn is_complete(&self) -> bool; + + /// Whether a stream that closed cleanly holds a complete response. + fn is_complete_at_close(&self) -> bool { + self.is_complete() + } + async fn parse_events(&mut self, response: Response) -> Result<(), Error> { let mut stream = response.bytes_stream().eventsource(); let mut consecutive_errors = 0; @@ -113,6 +126,18 @@ pub trait SSEParser { self.parse_event_data(&event.data).await?; } + // The body ends right after a transport error, so it cannot be skipped + // like a malformed event. A timeout spent the caller's whole budget. + Err(EventStreamError::Transport(_)) if self.is_complete() => break, + Err(EventStreamError::Transport(e)) => { + let message = + format!("The connection to the AI provider broke off mid-response: {e}"); + return Err(if e.is_timeout() { + Error::AIError(message) + } else { + transient_error(message, None) + }); + } Err(e) => { consecutive_errors += 1; tracing::error!("Failed to parse SSE event: {}", e); @@ -130,6 +155,9 @@ pub trait SSEParser { } } + if !self.is_complete_at_close() { + return Err(truncated_stream_error()); + } Ok(()) } } @@ -145,6 +173,9 @@ pub struct OpenAISSEParser { pub stream_event_processor: Box, /// Token usage from final chunk (when stream_options.include_usage is true) pub usage: Option, + /// Set by `[DONE]` or by a choice's `finish_reason`: OpenAI-compatible gateways do not + /// all send `[DONE]`. + complete: bool, } impl OpenAISSEParser { @@ -156,13 +187,19 @@ impl OpenAISSEParser { events_str: String::new(), stream_event_processor, usage: None, + complete: false, } } } impl SSEParser for OpenAISSEParser { + fn is_complete(&self) -> bool { + self.complete + } + async fn parse_event_data(&mut self, data: &str) -> Result<(), Error> { if data == "[DONE]" { + self.complete = true; return Ok(()); } @@ -173,13 +210,21 @@ impl SSEParser for OpenAISSEParser { .ok(); if let Some(event) = event { + if let Some(error) = event.error { + return Err(error.into_error("AI provider")); + } + // Extract usage from final chunk (when stream_options.include_usage is true) if let Some(usage) = event.usage { self.usage = Some(usage); } if let Some(mut choices) = event.choices.filter(|s| !s.is_empty()) { - if let Some(delta) = choices.remove(0).delta { + let choice = choices.remove(0); + if choice.finish_reason.is_some() { + self.complete = true; + } + if let Some(delta) = choice.delta { if let Some(reasoning) = delta.reasoning_content.filter(|s| !s.is_empty()) { self.accumulated_reasoning.push_str(&reasoning); let event = StreamingEvent::ReasoningTokenDelta { content: reasoning }; @@ -345,6 +390,8 @@ pub enum AnthropicSSEEvent { MessageDelta { #[serde(default)] usage: Option, + #[serde(default)] + delta: Option, }, #[serde(rename = "message_stop")] MessageStop {}, @@ -353,12 +400,18 @@ pub enum AnthropicSSEEvent { #[serde(rename = "error")] Error { #[serde(default)] - message: Option, + error: StreamErrorBody, }, #[serde(other)] Unknown, } +#[derive(Deserialize, Debug)] +pub struct AnthropicMessageDelta { + #[serde(default)] + pub stop_reason: Option, +} + /// Tracks state of a content block during streaming #[derive(Debug)] #[allow(dead_code)] @@ -391,6 +444,9 @@ pub struct AnthropicSSEParser { /// can be replayed before `tool_use` (required by Claude when thinking is on). pending_reasoning: Option, reasoning_attached: bool, + /// Set by `message_stop` or by the `stop_reason` of the `message_delta` sent just + /// before it, so a gateway that drops `message_stop` does not fail a whole answer. + complete: bool, } impl AnthropicSSEParser { @@ -407,11 +463,16 @@ impl AnthropicSSEParser { usage: None, pending_reasoning: None, reasoning_attached: false, + complete: false, } } } impl SSEParser for AnthropicSSEParser { + fn is_complete(&self) -> bool { + self.complete + } + async fn parse_event_data(&mut self, data: &str) -> Result<(), Error> { let event: Option = serde_json::from_str(data) .inspect_err(|e| { @@ -583,9 +644,8 @@ impl SSEParser for AnthropicSSEParser { .await?; } } - AnthropicSSEEvent::Error { message } => { - let error_msg = message.unwrap_or_else(|| "Unknown error".to_string()); - tracing::error!("Anthropic streaming error: {}", error_msg); + AnthropicSSEEvent::Error { error } => { + return Err(error.into_anthropic_error()); } AnthropicSSEEvent::MessageStart { message } => { // The only event carrying the prompt-side counts. `message_delta` @@ -595,7 +655,10 @@ impl SSEParser for AnthropicSSEParser { self.usage = Some(usage); } } - AnthropicSSEEvent::MessageDelta { usage } => { + AnthropicSSEEvent::MessageDelta { usage, delta } => { + if delta.is_some_and(|d| d.stop_reason.is_some()) { + self.complete = true; + } if let Some(u) = usage { match &mut self.usage { // Field by field, so the prompt counts from `message_start` @@ -614,10 +677,9 @@ impl SSEParser for AnthropicSSEParser { } } } + AnthropicSSEEvent::MessageStop {} => self.complete = true, // Ignore other events - AnthropicSSEEvent::MessageStop {} - | AnthropicSSEEvent::Ping {} - | AnthropicSSEEvent::Unknown => {} + AnthropicSSEEvent::Ping {} | AnthropicSSEEvent::Unknown => {} } } @@ -645,6 +707,7 @@ pub struct GeminiSSEParser { pub annotations: Vec, pub used_websearch: bool, pub usage: Option, + turn: GeminiTurn, } impl GeminiSSEParser { @@ -659,15 +722,25 @@ impl GeminiSSEParser { annotations: Vec::new(), used_websearch: false, usage: None, + turn: GeminiTurn::default(), } } } impl SSEParser for GeminiSSEParser { + fn is_complete(&self) -> bool { + self.turn.ended() + } + + fn is_complete_at_close(&self) -> bool { + self.turn.complete_at_close() + } + async fn parse_event_data(&mut self, data: &str) -> Result<(), Error> { let Some(parsed) = parse_gemini_sse_event(data)? else { return Ok(()); }; + self.turn.observe(&parsed); if let Some(reasoning) = parsed.reasoning.filter(|s| !s.is_empty()) { self.accumulated_reasoning.push_str(&reasoning); @@ -797,6 +870,8 @@ impl OpenAIResponsesUsage { pub struct OpenAIResponsesResponse { #[serde(default)] pub usage: Option, + #[serde(default)] + pub error: Option, } /// SSE event types for OpenAI Responses API streaming @@ -833,6 +908,20 @@ pub enum OpenAIResponsesSSEEvent { #[serde(rename = "response.incomplete")] Incomplete { response: OpenAIResponsesResponse }, + #[serde(rename = "response.failed")] + Failed { response: OpenAIResponsesResponse }, + + /// Flat (`code`, `message`) from OpenAI, nested under `error` from some compatible servers. + #[serde(rename = "error")] + Error { + #[serde(default)] + code: Option, + #[serde(default)] + message: Option, + #[serde(default)] + error: Option, + }, + /// Response created #[serde(rename = "response.created")] Created {}, @@ -890,6 +979,7 @@ pub struct OpenAIResponsesSSEParser { pub usage: Option, /// Reasoning summary parts seen so far, to separate them as paragraphs reasoning_summary_parts: usize, + response_ended: bool, } impl OpenAIResponsesSSEParser { @@ -906,11 +996,16 @@ impl OpenAIResponsesSSEParser { used_websearch: false, usage: None, reasoning_summary_parts: 0, + response_ended: false, } } } impl SSEParser for OpenAIResponsesSSEParser { + fn is_complete(&self) -> bool { + self.response_ended + } + async fn parse_event_data(&mut self, data: &str) -> Result<(), Error> { let event: Option = serde_json::from_str(data) .inspect_err(|e| { @@ -1010,11 +1105,22 @@ impl SSEParser for OpenAIResponsesSSEParser { OpenAIResponsesSSEEvent::Completed { response } | OpenAIResponsesSSEEvent::Incomplete { response } => { + self.response_ended = true; if let Some(usage) = response.usage { self.usage = Some(usage); } } + OpenAIResponsesSSEEvent::Failed { response } => { + return Err(response.error.unwrap_or_default().into_error("OpenAI")); + } + + OpenAIResponsesSSEEvent::Error { code, message, error } => { + return Err(error + .unwrap_or(StreamErrorBody { code, message, ..Default::default() }) + .into_error("OpenAI")); + } + OpenAIResponsesSSEEvent::ReasoningSummaryPartAdded {} => { self.reasoning_summary_parts += 1; if self.reasoning_summary_parts > 1 { @@ -1037,9 +1143,10 @@ impl SSEParser for OpenAIResponsesSSEParser { } } + OpenAIResponsesSSEEvent::Done {} => self.response_ended = true, + // Ignore other event types - OpenAIResponsesSSEEvent::Done {} - | OpenAIResponsesSSEEvent::Created {} + OpenAIResponsesSSEEvent::Created {} | OpenAIResponsesSSEEvent::InProgress {} | OpenAIResponsesSSEEvent::OutputItemDone {} | OpenAIResponsesSSEEvent::ContentPartAdded {} @@ -1093,6 +1200,117 @@ mod tests { } } + fn sse_response(chunks: Vec>) -> Response { + let body = reqwest::Body::wrap_stream(futures::stream::iter(chunks)); + Response::from(http::Response::new(body)) + } + + /// A stream that breaks off, or reports a failure inside its 200, must fail the call + /// rather than hand back what arrived as if it were the whole answer. + #[tokio::test] + async fn stream_failures_are_errors_not_partial_answers() { + use crate::retry::as_transient; + + const STARTED: &str = concat!( + "data: {\"type\":\"message_start\"}\n\n", + "data: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n", + "data: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"text_delta\",\"text\":\"Hel\"}}\n\n", + ); + let anthropic = |chunks| async move { + AnthropicSSEParser::new(Box::new(NoopSink)) + .parse_events(sse_response(chunks)) + .await + }; + + let overloaded = anthropic(vec![ + Ok(STARTED), + Ok("data: {\"type\":\"error\",\"error\":{\"type\":\"overloaded_error\",\"message\":\"Overloaded\"}}\n\n"), + ]) + .await + .unwrap_err(); + assert!(as_transient(&overloaded).is_some(), "{overloaded}"); + + let refused = anthropic(vec![ + Ok(STARTED), + Ok("data: {\"type\":\"error\",\"error\":{\"type\":\"invalid_request_error\",\"message\":\"bad\"}}\n\n"), + ]) + .await + .unwrap_err(); + assert!(as_transient(&refused).is_none(), "{refused}"); + + let truncated = anthropic(vec![Ok(STARTED)]).await.unwrap_err(); + assert!(as_transient(&truncated).is_some(), "{truncated}"); + + let dropped = anthropic(vec![ + Ok(STARTED), + Err(std::io::Error::new( + std::io::ErrorKind::ConnectionReset, + "reset", + )), + ]) + .await + .unwrap_err(); + assert!(as_transient(&dropped).is_some(), "{dropped}"); + + anthropic(vec![ + Ok(STARTED), + Ok("data: {\"type\":\"message_stop\"}\n\n"), + ]) + .await + .unwrap(); + + anthropic(vec![ + Ok(STARTED), + Ok("data: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"}}\n\n"), + ]) + .await + .unwrap(); + + let truncated = OpenAISSEParser::new(Box::new(NoopSink)) + .parse_events(sse_response(vec![Ok( + "data: {\"choices\":[{\"delta\":{\"content\":\"Hi\"}}]}\n\n", + )])) + .await + .unwrap_err(); + assert!(as_transient(&truncated).is_some(), "{truncated}"); + + let quota = OpenAIResponsesSSEParser::new(Box::new(NoopSink)) + .parse_events(sse_response(vec![Ok( + "data: {\"type\":\"error\",\"error\":{\"type\":\"insufficient_quota\",\"code\":\"insufficient_quota\",\"message\":\"m\"}}\n\n", + )])) + .await + .unwrap_err(); + assert!(as_transient("a).is_none(), "{quota}"); + + GeminiSSEParser::new(Box::new(NoopSink)) + .parse_events(sse_response(vec![Ok( + "data: {\"candidates\":[{\"content\":{\"role\":\"model\",\"parts\":[{\"functionCall\":{\"name\":\"get_weather\",\"args\":{}}}]}}]}\n\n", + )])) + .await + .unwrap(); + + let gemini = |chunks| async move { + GeminiSSEParser::new(Box::new(NoopSink)) + .parse_events(sse_response(chunks)) + .await + }; + // Thinking spent the whole `maxOutputTokens`: a clean close with no event. + gemini(vec![]).await.unwrap(); + let dropped = gemini(vec![Err(std::io::Error::new( + std::io::ErrorKind::ConnectionReset, + "reset", + ))]) + .await + .unwrap_err(); + assert!(as_transient(&dropped).is_some(), "{dropped}"); + let truncated = gemini(vec![Ok( + "data: {\"candidates\":[{\"content\":{\"role\":\"model\",\"parts\":[{\"text\":\"Hi\"}]}}]}\n\n", + )]) + .await + .unwrap_err(); + assert!(as_transient(&truncated).is_some(), "{truncated}"); + } + /// The prompt-side counts arrive only on `message_start` and the completion total /// only on `message_delta`; a parser that keeps just the last one reports a request /// with no input tokens at all. diff --git a/backend/windmill-ai/src/types.rs b/backend/windmill-ai/src/types.rs index e591e85159..59733e352c 100644 --- a/backend/windmill-ai/src/types.rs +++ b/backend/windmill-ai/src/types.rs @@ -1,3 +1,4 @@ +use indexmap::IndexMap; use serde::{Deserialize, Serialize}; use serde_json::value::RawValue; use std::collections::HashMap; @@ -533,7 +534,7 @@ pub struct OpenAPISchema { #[serde(skip_serializing_if = "Option::is_none")] pub items: Option>, #[serde(skip_serializing_if = "Option::is_none")] - pub properties: Option>>, + pub properties: Option>>, #[serde(skip_serializing_if = "Option::is_none")] pub required: Option>, #[serde(skip_serializing_if = "Option::is_none", rename = "oneOf")] @@ -560,9 +561,9 @@ pub struct OpenAPISchema { #[serde(skip_serializing_if = "Option::is_none", rename = "$ref")] pub ref_path: Option, #[serde(skip_serializing_if = "Option::is_none", rename = "$defs")] - pub defs: Option>>, + pub defs: Option>>, #[serde(skip_serializing_if = "Option::is_none")] - pub definitions: Option>>, + pub definitions: Option>>, // Schema composition #[serde(skip_serializing_if = "Option::is_none", rename = "allOf")] @@ -829,7 +830,7 @@ impl OpenAPISchema { // Merge properties (other's properties are added if key doesn't exist) if let Some(ref other_props) = other.properties { - let props = self.properties.get_or_insert_with(HashMap::new); + let props = self.properties.get_or_insert_with(IndexMap::new); for (key, value) in other_props { props.entry(key.clone()).or_insert_with(|| value.clone()); } @@ -880,13 +881,13 @@ impl OpenAPISchema { // Merge $defs and definitions if let Some(ref other_defs) = other.defs { - let defs = self.defs.get_or_insert_with(HashMap::new); + let defs = self.defs.get_or_insert_with(IndexMap::new); for (key, value) in other_defs { defs.entry(key.clone()).or_insert_with(|| value.clone()); } } if let Some(ref other_definitions) = other.definitions { - let definitions = self.definitions.get_or_insert_with(HashMap::new); + let definitions = self.definitions.get_or_insert_with(IndexMap::new); for (key, value) in other_definitions { definitions .entry(key.clone()) @@ -981,7 +982,29 @@ pub struct S3ObjectWithType { #[cfg(test)] mod tests { use super::*; - use std::collections::HashMap; + + /// The schema is part of the prompt prefix the provider caches on, so its keys must + /// serialize in the same order on every request. + #[test] + fn strict_schema_keeps_the_defined_property_order() { + let keys = [ + "zeta", "alpha", "mid", "beta", "omega", "gamma", "delta", "kappa", + ]; + let props = keys + .iter() + .map(|k| format!(r#""{k}":{{"type":"string"}}"#)) + .collect::>() + .join(","); + let mut schema: OpenAPISchema = + serde_json::from_str(&format!(r#"{{"type":"object","properties":{{{props}}}}}"#)) + .unwrap(); + schema.make_strict(); + + let value = serde_json::to_value(&schema).unwrap(); + let serialized: Vec<&String> = value["properties"].as_object().unwrap().keys().collect(); + assert_eq!(serialized, keys); + assert_eq!(value["required"], serde_json::json!(keys)); + } /// Whichever provider served the request, `input_tokens` has to end up meaning the /// whole prompt. Leaving the Anthropic shape as reported under-states it by the @@ -1248,7 +1271,7 @@ mod tests { #[test] fn test_make_strict_defs() { let def_schema = object_schema(vec![("prop", string_schema())]); - let mut defs = HashMap::new(); + let mut defs = IndexMap::new(); defs.insert("MyType".to_string(), Box::new(def_schema)); let mut schema = OpenAPISchema { defs: Some(defs), ..Default::default() }; @@ -1274,7 +1297,7 @@ mod tests { #[test] fn test_make_strict_definitions() { let def_schema = object_schema(vec![("prop", string_schema())]); - let mut definitions = HashMap::new(); + let mut definitions = IndexMap::new(); definitions.insert("MyType".to_string(), Box::new(def_schema)); let mut schema = OpenAPISchema { definitions: Some(definitions), ..Default::default() }; @@ -1528,7 +1551,7 @@ mod tests { #[test] fn test_flatten_all_of_preserves_defs() { let def_schema = object_schema(vec![("field", string_schema())]); - let mut defs = HashMap::new(); + let mut defs = IndexMap::new(); defs.insert("MyType".to_string(), Box::new(def_schema)); let schema_with_defs = OpenAPISchema { defs: Some(defs), ..Default::default() }; @@ -1642,7 +1665,7 @@ mod tests { schema_url: Some("http://json-schema.org/draft-07/schema#".to_string()), ..Default::default() }; - let mut defs = HashMap::new(); + let mut defs = IndexMap::new(); defs.insert("MyType".to_string(), Box::new(def_schema)); let mut schema = OpenAPISchema { diff --git a/backend/windmill-ai/src/utils.rs b/backend/windmill-ai/src/utils.rs index 328d2e0458..de7efda183 100644 --- a/backend/windmill-ai/src/utils.rs +++ b/backend/windmill-ai/src/utils.rs @@ -88,30 +88,17 @@ pub fn ai_http_client_builder() -> reqwest::ClientBuilder { /// after the check (DNS-rebinding TOCTOU). /// /// Returns the shared pooled [`AI_HTTP_CLIENT`] unchanged when there is nothing -/// to pin — an IP-literal host, or a deployment that opted into private AI -/// endpoints via `ALLOW_PRIVATE_AI_BASE_URLS`. The same opt-out and error hint -/// as `AIProvider::get_base_url` apply, so this is consistent with the +/// to pin — an IP-literal host, or a host `ALLOW_PRIVATE_AI_BASE_URLS` allows +/// by name or wholesale. The same allowlist and error hint as +/// `AIProvider::get_base_url` apply, so this is consistent with the /// credential-time validation while additionally closing the connect-time window. pub async fn pinned_ai_client_for( url: &str, ) -> windmill_common::error::Result> { use std::borrow::Cow; - use windmill_common::error::{to_anyhow, Error}; - use windmill_common::ssrf::SsrfValidationError; + use windmill_common::error::to_anyhow; - if *crate::ai_providers::ALLOW_PRIVATE_AI_BASE_URLS { - return Ok(Cow::Borrowed(&AI_HTTP_CLIENT)); - } - - let target = windmill_common::ssrf::validate_url_for_ssrf(url) - .await - .map_err(|e| match e { - e @ SsrfValidationError::Private { .. } => Error::BadRequest(format!( - "{e}. If you need to use private/internal AI endpoints, \ - set the ALLOW_PRIVATE_AI_BASE_URLS=true environment variable" - )), - e => Error::from(e), - })?; + let target = crate::ai_providers::validate_ai_url(url).await?; if target.pinned_addrs().is_empty() { return Ok(Cow::Borrowed(&AI_HTTP_CLIENT)); diff --git a/backend/windmill-alerting/Cargo.toml b/backend/windmill-alerting/Cargo.toml index 6f7352426e..a1c46edbb9 100644 --- a/backend/windmill-alerting/Cargo.toml +++ b/backend/windmill-alerting/Cargo.toml @@ -7,6 +7,9 @@ edition.workspace = true [lib] name = "windmill_alerting" path = "src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [dependencies] windmill-common = { workspace = true, default-features = false } diff --git a/backend/windmill-api-agent-workers/Cargo.toml b/backend/windmill-api-agent-workers/Cargo.toml index feabde8b12..4b3a202003 100644 --- a/backend/windmill-api-agent-workers/Cargo.toml +++ b/backend/windmill-api-agent-workers/Cargo.toml @@ -7,17 +7,20 @@ edition.workspace = true [lib] name = "windmill_api_agent_workers" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] enterprise = ["windmill-common/enterprise", "windmill-queue/enterprise"] -private = ["windmill-common/private", "windmill-queue/private"] +private = ["windmill-common/private", "windmill-queue/private", "windmill-audit/private"] python = ["dep:windmill-parser-py-imports"] benchmark = ["windmill-queue/benchmark"] [dependencies] windmill-api-auth.workspace = true windmill-common = { workspace = true, default-features = false } +windmill-audit.workspace = true windmill-queue.workspace = true windmill-worker.workspace = true axum.workspace = true diff --git a/backend/windmill-api-assets/Cargo.toml b/backend/windmill-api-assets/Cargo.toml index 62bc3d9c8d..5b43e3f2a5 100644 --- a/backend/windmill-api-assets/Cargo.toml +++ b/backend/windmill-api-assets/Cargo.toml @@ -7,6 +7,9 @@ edition.workspace = true [lib] name = "windmill_api_assets" path = "src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [features] private = ["windmill-common/private"] diff --git a/backend/windmill-api-auth/Cargo.toml b/backend/windmill-api-auth/Cargo.toml index 515a51cab7..1461e95237 100644 --- a/backend/windmill-api-auth/Cargo.toml +++ b/backend/windmill-api-auth/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_api_auth" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-api-auth/src/auth.rs b/backend/windmill-api-auth/src/auth.rs index 720111e89d..6bc9a930a4 100644 --- a/backend/windmill-api-auth/src/auth.rs +++ b/backend/windmill-api-auth/src/auth.rs @@ -6,6 +6,7 @@ use axum::{ }; use chrono::TimeZone; use http::{request::Parts, StatusCode}; +use itertools::Itertools; use quick_cache::sync::Cache; use serde::{Deserialize, Serialize}; use sqlx::FromRow; @@ -1022,6 +1023,49 @@ where } } +/// Adds the suffixed form of each tag of an `if_jobs:filter_tags:` scope: in a dev workspace a +/// job allowed on `gpu` is queued on `gpu-dev`, and the token must still reach the jobs it starts. +fn expand_filter_tags_with_dev_suffix(scopes: &mut [String], suffix: &str) { + for scope in scopes.iter_mut() { + if let Some(tags) = scope.strip_prefix("if_jobs:filter_tags:") { + let expanded = tags + .split(',') + .flat_map(|t| { + let suffixed = windmill_common::worker::with_dev_workspace_suffix(t, suffix); + [t.to_string(), suffixed] + }) + .unique() + .join(","); + *scope = format!("if_jobs:filter_tags:{expanded}"); + } + } +} + +/// Only while isolation is on and for a workspace whose jobs get the suffix then: otherwise the +/// suffixed tags are other tags the token was not given. +async fn expand_filter_tags_for_dev_workspace( + db: &DB, + workspace_id: &str, + scopes: Option<&mut Vec>, +) { + let Some(scopes) = scopes else { return }; + if !windmill_common::worker::DEV_WORKSPACE_ISOLATION.load(std::sync::atomic::Ordering::Relaxed) + || !scopes.iter().any(|s| s.starts_with("if_jobs:filter_tags:")) + { + return; + } + let (is_dev, in_dev_lineage) = windmill_common::workspaces::dev_lineage(db, workspace_id) + .await + .unwrap_or(( + workspace_id.starts_with(windmill_common::workspaces::WM_FORK_PREFIX), + true, + )); + if windmill_common::worker::is_isolated_workspace(is_dev, in_dev_lineage) { + let suffix = windmill_common::worker::DEV_WORKSPACE_TAG_SUFFIX.load(); + expand_filter_tags_with_dev_suffix(scopes, &suffix); + } +} + pub fn transform_old_scope_to_new_scope(scopes: Option<&mut Vec>) { if let Some(scopes) = scopes { for scope in scopes.iter_mut() { @@ -1110,10 +1154,10 @@ pub async fn resolve_opt_job_authed( }; if is_no_auth() { - return Ok(( - OptJobAuthed { authed: no_auth_admin_authed(), job_id: None }, - parts, - )); + let authed = no_auth_admin_authed(); + // Handlers taking `Extension` read this insert, as on the token path. + parts.extensions.insert(authed.clone()); + return Ok((OptJobAuthed { authed, job_id: None }, parts)); } // Safe only while what the route checks below read is fixed before the first @@ -1172,6 +1216,14 @@ pub async fn resolve_opt_job_authed( let authed = &mut opt_job_authed.authed; if authed.scopes.is_some() && !own_job_runtime_route { transform_old_scope_to_new_scope(authed.scopes.as_mut()); + if let Some(w_id) = workspace_id.as_deref() { + expand_filter_tags_for_dev_workspace( + &cache.db, + w_id, + authed.scopes.as_mut(), + ) + .await; + } if let Err(err) = crate::scopes::check_scopes_for_route( authed.scopes.as_deref(), @@ -1359,6 +1411,19 @@ pub async fn list_tokens_internal( mod tests { use super::*; + #[test] + fn filter_tags_reach_their_dev_workspace_form() { + let mut scopes = vec![ + "jobs:read".to_string(), + "if_jobs:filter_tags:gpu,bash-dev".to_string(), + ]; + expand_filter_tags_with_dev_suffix(&mut scopes, "-dev"); + assert_eq!( + scopes, + vec!["jobs:read", "if_jobs:filter_tags:gpu,gpu-dev,bash-dev"] + ); + } + /// Dropping the `AUTH_CACHE` entry between the two resolutions is what makes a memo /// hit observable: only a working memo can answer the second one. #[tokio::test] diff --git a/backend/windmill-api-auth/src/scopes.rs b/backend/windmill-api-auth/src/scopes.rs index dce6a0ff72..bdbab1bfe7 100644 --- a/backend/windmill-api-auth/src/scopes.rs +++ b/backend/windmill-api-auth/src/scopes.rs @@ -73,7 +73,12 @@ pub fn check_route_access( .to_string(), )); } - if required_domain == ScopeDomain::Users && suffix != "users/whoami" { + if required_domain == ScopeDomain::Users { + // Whoami returns what the bundle already has in `window.ctx`, so it + // needs no declared scope. + if suffix == "users/whoami" { + return Ok(()); + } return Err(Error::PermissionDenied( "Access denied. A raw app frontend SDK token can only read the viewer's own identity." .to_string(), @@ -170,10 +175,16 @@ const FLOW_JOBS: [&'static str; 6] = [ /// scoped by the agent's path like a deployed runnable's, as `jobs:run:agents:`. const AGENT_JOBS: [&'static str; 1] = ["jobs/run/agent"]; +/// Lock resolution for scripts, apps and flows, scoped as `jobs:run:dependencies:`. +/// Resolving a package can run its build or install scripts on the worker, so this is +/// still code execution: the scope only takes away the direct ways to run code. +const DEPENDENCY_JOBS: [&'static str; 2] = ["jobs/run/dependencies", "jobs/run/flow_dependencies"]; + lazy_static::lazy_static! { static ref RUN_PATH_ACTIONS: Vec<&'static str> = { - let mut v = vec!["jobs/resume/", "jobs/run/batch_rerun_jobs", "jobs/run/workflow_as_code", "jobs/run/dependencies","jobs/run/flow_dependencies", "apps_u/execute_component", "apps_u/upload_s3_file"]; + let mut v = vec!["jobs/resume/", "jobs/run/batch_rerun_jobs", "jobs/run/workflow_as_code", "apps_u/execute_component", "apps_u/upload_s3_file"]; + v.extend(DEPENDENCY_JOBS); v.extend(SCRIPT_JOBS); v.extend(FLOW_JOBS); v.extend(AGENT_JOBS); @@ -227,11 +238,13 @@ fn map_http_method_to_action(method: &str, route_path: &str) -> ScopeAction { } } -/// Checks the route path to determine the runnable kind ("agents", "flows" or "scripts"). +/// Checks the route path to determine the runnable kind ("dependencies", "agents", "flows" +/// or "scripts"). /// /// The order of checks is important: -/// - Flow-related paths are checked first to avoid false positives, as some flow paths -/// (e.g., `/run_preview_flow`) share prefixes with script paths (e.g., `/run_preview`). +/// - Dependency paths are checked before flow paths: `flow_dependencies` starts with `f`. +/// - Flow-related paths are checked before script paths to avoid false positives, as some +/// flow paths (e.g., `/run_preview_flow`) share prefixes with script paths (e.g., `/run_preview`). /// /// Returns the kind based on the match, or `None` if no match is found. fn determine_kind_from_route(route_path: &str) -> Option { @@ -247,6 +260,12 @@ fn determine_kind_from_route(route_path: &str) -> Option { { return None; } + if DEPENDENCY_JOBS + .iter() + .any(|path| route_path.starts_with(path)) + { + return Some("dependencies".to_string()); + } if AGENT_JOBS.iter().any(|path| route_path.starts_with(path)) { return Some("agents".to_string()); } @@ -404,8 +423,9 @@ pub fn guest_session_scopes(app_path: &str) -> windmill_common::error::Result) -> bool { @@ -448,8 +468,9 @@ fn app_embed_route_denied(domain: ScopeDomain, suffix: &str) -> bool { } } -/// App routes a running app uses: its own definition (`apps/get/p/`, further -/// path-scoped by `apps:read:`) and the public app-serving endpoints +/// App routes a running app uses: its own definition (`apps/get/p/`, or +/// `apps/get/lite/` that the viewer runs from, both further path-scoped by +/// `apps:read:`) and the public app-serving endpoints /// (`apps_u/*`: public_app, public_resource, get_data, and the path-taking /// `execute_component` / `download_s3_file`, which re-check `apps:run|read:` /// in their handlers so they stay confined to this app). Everything else in the @@ -463,7 +484,9 @@ fn app_embed_apps_route_allowed(suffix: &str) -> bool { if suffix.starts_with("apps_u/embed_token") { return false; } - suffix.starts_with("apps/get/p/") || suffix.starts_with("apps_u/") + suffix.starts_with("apps/get/p/") + || suffix.starts_with("apps/get/lite/") + || suffix.starts_with("apps_u/") } /// Routes a guest session is denied: the app-embed allowlist, plus the embed-token @@ -586,17 +609,23 @@ pub struct JobReadConfinement { } impl JobReadConfinement { - /// Whether a job that ran `runnable_path` as `kind` (`scripts`, `flows` or `agents`) - /// is inside the confinement. A read path admits every kind; a run scope only its own. + /// Whether a job that ran `runnable_path` as `kind` (`scripts`, `flows`, `agents` or + /// `dependencies`) is inside the confinement. A read path admits every kind; a run + /// scope only its own. pub fn admits(&self, kind: &str, runnable_path: &str) -> bool { if self.read_paths.allows(runnable_path) { return true; } + // Lock jobs and previews store the path their caller sent. The matcher reads `*` + // in it as a pattern, and `,`/`:` are scope syntax: such a path needs a grant + // covering every path, as enqueuing it did. + let resource = windmill_common::auth::is_scope_literal_path(runnable_path) + .then(|| vec![runnable_path.to_string()]); let required = ScopeDefinition::new( ScopeDomain::Jobs.as_str(), ScopeAction::Run.as_str(), Some(kind), - Some(vec![runnable_path.to_string()]), + resource, ); self.run.iter().any(|scope| scope.includes(&required)) } @@ -862,7 +891,8 @@ fn scope_grants_access( /// from its own super-admin gate, these among them, so each is already readable by every /// authenticated user; each is here because the CLI reads it from a job: /// `automate_username_creation` before creating a user during a git-sync push, `uid` and -/// `hub_base_url` when `u/admin/hub_sync` pulls resource types from the Hub. The other +/// `hub_base_url` when a job runs `wmill hub pull`, as an edited copy of the retired +/// `u/admin/hub_sync` still does (servers sync resource types themselves). The other /// ungated keys have no such caller, so they stay confined — being ungated earns a key /// nothing on its own. Listing a gated key earns it nothing either: `require_super_admin` /// refuses every job token, so `hub_api_secret`, which that pull reads for a private Hub, @@ -916,11 +946,15 @@ fn is_global_read_open_to_job_token(route_path: &str) -> bool { /// not send. /// - tutorial progress upserts a UI bitfield keyed on the caller's own email. Its path /// serves a `GET` too, which the read list above carries. -const GLOBAL_WRITES_OPEN_TO_JOB_TOKEN: [&str; 4] = [ +/// - a Teams message from a job (the Teams error, recovery and success handlers) posts as +/// the instance-wide bot. The handler refuses a job token whose conversation is not a +/// channel of the team connected to the job's workspace. +const GLOBAL_WRITES_OPEN_TO_JOB_TOKEN: [&str; 5] = [ "/api/settings/test_object_storage_config", "/api/workspaces/exists", "/api/schedules/preview", "/api/users/tutorial_progress", + "/api/teams/activities", ]; /// Confines a job token (`$WM_TOKEN`) to routes that name a workspace. It is minted @@ -996,6 +1030,7 @@ pub fn is_own_job_runtime_route(route_path: &str, http_method: &str, job_id: uui ["job_metrics", "set_progress", ..] => (http_method == "POST", 2), ["job_metrics", "get_progress", ..] => (http_method == "GET", 2), ["jobs" | "jobs_u", "resume_urls" | "wac_approval_urls", ..] => (http_method == "GET", 2), + ["jobs", "worker_is_draining", ..] => (http_method == "GET", 2), ["jobs", "wac", "inline_checkpoint", ..] => (http_method == "POST", 3), ["jobs", "run", "workflow_as_code", ..] => (http_method == "POST", 3), _ => return false, @@ -1713,6 +1748,24 @@ mod tests { scope_for_route("POST", "/api/w/ws/jobs/run/agent/u/x/y").as_deref(), Some("jobs:run:agents") ); + for path in [ + "/api/w/ws/jobs/run/dependencies", + "/api/w/ws/jobs/run/dependencies_async", + "/api/w/ws/jobs/run/flow_dependencies", + "/api/w/ws/jobs/run/flow_dependencies_async", + ] { + assert_eq!( + scope_for_route("POST", path).as_deref(), + Some("jobs:run:dependencies"), + "{path}" + ); + assert!(check_route_access(&["jobs:run:dependencies".into()], path, "POST").is_ok()); + assert!(check_route_access(&["jobs:run:flows".into()], path, "POST").is_err()); + } + // A dependencies grant reaches no other run route. + for path in ["/api/w/ws/jobs/run/preview", "/api/w/ws/jobs/run/p/u/x/y"] { + assert!(check_route_access(&["jobs:run:dependencies".into()], path, "POST").is_err()); + } // Preview/bundle runs have no deployed path and their handlers require the // broad `jobs:run` scope, so the derived scope must not carry a kind. diff --git a/backend/windmill-api-client/Cargo.toml b/backend/windmill-api-client/Cargo.toml index 5d7ea274d9..ac326f9215 100644 --- a/backend/windmill-api-client/Cargo.toml +++ b/backend/windmill-api-client/Cargo.toml @@ -7,6 +7,9 @@ edition.workspace = true [lib] name = "windmill_api_client" path = "./src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [dependencies] diff --git a/backend/windmill-api-configs/Cargo.toml b/backend/windmill-api-configs/Cargo.toml index a24e0b9540..f8c1c48dab 100644 --- a/backend/windmill-api-configs/Cargo.toml +++ b/backend/windmill-api-configs/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_api_configs" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-api-configs/src/lib.rs b/backend/windmill-api-configs/src/lib.rs index f1f4792e71..890a561679 100644 --- a/backend/windmill-api-configs/src/lib.rs +++ b/backend/windmill-api-configs/src/lib.rs @@ -273,18 +273,22 @@ async fn update_config( } let mut tx = db.begin().await?; - let was_paused = if name.starts_with("worker__") { + let previous = if name.starts_with("worker__") { sqlx::query_scalar!( - "SELECT COALESCE(config->'paused' = 'true'::jsonb, false) FROM config WHERE name = $1 FOR UPDATE", + "SELECT config FROM config WHERE name = $1 FOR UPDATE", &name ) .fetch_optional(&mut *tx) .await? .flatten() - .unwrap_or(false) } else { - false + None }; + let is_set = |c: Option<&serde_json::Value>, k: &str| { + c.and_then(|c| c.get(k)).and_then(|v| v.as_bool()) == Some(true) + }; + let was_paused = is_set(previous.as_ref(), "paused"); + let was_serving_dev = is_set(previous.as_ref(), "serves_dev_workspaces"); sqlx::query!( "INSERT INTO config (name, config) VALUES ($1, $2) ON CONFLICT (name) DO UPDATE SET config = EXCLUDED.config", &name, @@ -306,7 +310,7 @@ async fn update_config( tx.commit().await?; if name.starts_with("worker__") { - let paused = config.get("paused").and_then(|v| v.as_bool()) == Some(true); + let paused = is_set(Some(&config), "paused"); if paused != was_paused { windmill_common::feature_usage::log_feature_usage( "worker_group", @@ -314,6 +318,14 @@ async fn update_config( if paused { "pause" } else { "resume" }, ); } + let serving_dev = is_set(Some(&config), "serves_dev_workspaces"); + if serving_dev != was_serving_dev { + windmill_common::feature_usage::log_feature_usage( + "worker_group", + "dev_workspaces_toggle", + if serving_dev { "serve" } else { "stop" }, + ); + } } Ok(format!("Updated config {name}")) } diff --git a/backend/windmill-api-debug/Cargo.toml b/backend/windmill-api-debug/Cargo.toml index c262ac3d32..8e3ce3daf0 100644 --- a/backend/windmill-api-debug/Cargo.toml +++ b/backend/windmill-api-debug/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_api_debug" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-api-embeddings/Cargo.toml b/backend/windmill-api-embeddings/Cargo.toml index ff7c3435aa..411dc0efb0 100644 --- a/backend/windmill-api-embeddings/Cargo.toml +++ b/backend/windmill-api-embeddings/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_api_embeddings" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-api-embeddings/src/lib.rs b/backend/windmill-api-embeddings/src/lib.rs index 6e4d6a1c71..a470648cbb 100644 --- a/backend/windmill-api-embeddings/src/lib.rs +++ b/backend/windmill-api-embeddings/src/lib.rs @@ -9,16 +9,11 @@ use windmill_common::DEFAULT_HUB_BASE_URL; #[cfg(feature = "embedding")] use windmill_common::HUB_BASE_URL; -use axum::Router; - -#[cfg(feature = "embedding")] use axum::{ extract::{Path, Query}, - Json, + routing::get, + Extension, Json, Router, }; - -#[cfg(feature = "embedding")] -use axum::routing::get; #[cfg(feature = "embedding")] use candle_core::{Device, Tensor}; #[cfg(feature = "embedding")] @@ -27,10 +22,7 @@ use candle_nn::VarBuilder; use candle_transformers::models::bert::{BertModel, Config, DTYPE}; #[cfg(feature = "embedding")] use hf_hub::api::tokio::Api; -#[cfg(feature = "embedding")] -use serde::Deserialize; -#[cfg(feature = "embedding")] -use serde::Serialize; +use serde::{Deserialize, Serialize}; #[cfg(feature = "embedding")] use sqlx::{Pool, Postgres}; #[cfg(feature = "embedding")] @@ -44,9 +36,7 @@ use tokenizers::Tokenizer; use tokio::sync::RwLock; #[cfg(feature = "embedding")] use windmill_common::utils::http_get_from_hub; - -#[cfg(feature = "embedding")] -use windmill_common::error::JsonResult; +use windmill_common::{db::DB, error::JsonResult}; #[cfg(feature = "embedding")] use windmill_store::resources::ResourceType; @@ -60,6 +50,7 @@ lazy_static::lazy_static! { // full pulling interval, so a transient startup error doesn't leave the // embeddings DB uninitialized for a whole day. pub static ref HUB_EMBEDDINGS_RETRY_INTERVAL_SECS: u64 = std::env::var("HUB_EMBEDDINGS_RETRY_INTERVAL_SECS").ok().map(|x| x.parse::().ok()).flatten().unwrap_or(60); + pub static ref RESOURCE_TYPE_EMBEDDINGS_CHECK_INTERVAL_SECS: u64 = std::env::var("RESOURCE_TYPE_EMBEDDINGS_CHECK_INTERVAL_SECS").ok().map(|x| x.parse::().ok()).flatten().unwrap_or(60); } #[cfg(feature = "embedding")] @@ -104,14 +95,12 @@ async fn query_hub_scripts( } } -#[cfg(feature = "embedding")] #[derive(Deserialize)] struct ResourceTypesQuery { text: String, limit: Option, } -#[cfg(feature = "embedding")] #[derive(Serialize)] pub struct ResourceTypeResult { name: String, @@ -138,24 +127,107 @@ fn trim_to_top_score( .take_while(|r| (top_score - score(r)) / top_score <= max_relative_drop) .collect() } -#[cfg(feature = "embedding")] async fn query_resource_types( + Extension(db): Extension, Query(query): Query, Path(w_id): Path, ) -> JsonResult> { - let embeddings_db = EMBEDDINGS_DB.read().await; - - if let Some(embeddings_db) = embeddings_db.as_ref() { - let results = embeddings_db - .query_resource_types(w_id, &query.text, query.limit) - .await?; - - Ok(Json(results)) - } else { - Err(windmill_common::error::Error::internal_err( - "Embeddings db not initialized".to_string(), - )) + #[cfg(feature = "embedding")] + if let Some(embeddings_db) = EMBEDDINGS_DB.read().await.as_ref() { + return Ok(Json( + embeddings_db + .query_resource_types(w_id, &query.text, query.limit) + .await?, + )); } + Ok(Json( + match_resource_types_by_text(&db, &w_id, &query.text, query.limit).await?, + )) +} + +/// Serves the search when there is no embeddings index: a build without the `embedding` +/// feature, or one whose index never loaded (air-gapped, `DISABLE_EMBEDDING`). The AI chat +/// has no other way to read the instance's resource types. +async fn match_resource_types_by_text( + db: &DB, + w_id: &str, + text: &str, + limit: Option, +) -> windmill_common::error::Result> { + let words: Vec = text + .to_lowercase() + .split(|c: char| !c.is_alphanumeric()) + .filter(|word| !word.is_empty()) + .map(str::to_string) + .collect(); + let rows: Vec<(String, String, Option)> = sqlx::query_as( + "SELECT workspace_id, name, description FROM resource_type WHERE workspace_id = $1 OR workspace_id = 'admins'", + ) + .bind(w_id) + .fetch_all(db) + .await?; + + let mut ranked: Vec<(f32, String, String)> = rows + .into_iter() + .map(|(workspace_id, name, description)| { + let score = text_match_score(&words, &name, description.as_deref().unwrap_or_default()); + (score, workspace_id, name) + }) + .filter(|(score, _, _)| *score > 0.0) + .collect(); + ranked.sort_by(|a, b| b.0.total_cmp(&a.0).then_with(|| a.2.cmp(&b.2))); + ranked.truncate(limit.unwrap_or(10).max(0) as usize); + + // Schemas are read for the kept rows only: a synced instance holds megabytes of them. + let (workspaces, names): (Vec<&str>, Vec<&str>) = ranked + .iter() + .map(|(_, workspace_id, name)| (workspace_id.as_str(), name.as_str())) + .unzip(); + let mut schemas: Vec<(String, String, Option)> = sqlx::query_as( + "SELECT workspace_id, name, schema FROM resource_type WHERE (workspace_id, name) IN (SELECT * FROM unnest($1::text[], $2::text[]))", + ) + .bind(&workspaces) + .bind(&names) + .fetch_all(db) + .await?; + + Ok(ranked + .into_iter() + .map(|(score, workspace_id, name)| { + let schema = schemas + .iter_mut() + .find(|(w, n, _)| *w == workspace_id && *n == name) + .and_then(|(_, _, schema)| schema.take()); + ResourceTypeResult { score, name, schema } + }) + .collect()) +} + +/// A word found in the name counts twice a word found in the description: names are what +/// a query for a service spells out ("postgres" in `postgresql`, "sheets" in `gsheets`). +/// A word under 3 characters ("s3", "ai") would sit inside too many names, so it counts only +/// as a whole name or one of its `_`-separated parts. +fn text_match_score(words: &[String], name: &str, description: &str) -> f32 { + let name = name.to_lowercase(); + let description = description.to_lowercase(); + words + .iter() + .map(|word| { + let short = word.len() < 3; + let in_name = if short { + name.split('_').any(|part| part == word) + } else { + name.contains(word.as_str()) + }; + if in_name { + 2.0 + } else if !short && description.contains(word.as_str()) { + 1.0 + } else { + 0.0 + } + }) + .sum() } #[cfg(feature = "embedding")] @@ -288,17 +360,60 @@ impl ModelInstance { pub struct EmbeddingsDb { db: Db, model_instance: Arc, + /// Kept from the last full fill, so the resource types can be re-indexed between fills + /// without downloading the hub's embeddings again. + hub_resource_type_embeddings: Arc>>, + /// The `resource_types_fingerprint` the resource types collection was built from. + resource_types_fingerprint: Option, + /// See `ResourceTypeIndex::custom_vectors`. + custom_resource_type_vectors: Arc>>, +} + +/// A built resource types collection, with what a later refresh needs to tell it is stale and +/// to reuse its vectors. +#[cfg(feature = "embedding")] +struct ResourceTypeIndex { + fingerprint: Option, + embeddings: Vec, + /// Vectors of the types the hub has none for, by the `name;description` they embed: a + /// refresh runs the model only on types that are new or changed, not on every custom type. + custom_vectors: Arc>>, } #[cfg(feature = "embedding")] impl EmbeddingsDb { + fn empty(model_instance: Arc) -> Self { + Self { + db: Db::new(), + model_instance, + hub_resource_type_embeddings: Arc::new(HashMap::new()), + resource_types_fingerprint: None, + custom_resource_type_vectors: Arc::new(HashMap::new()), + } + } + pub async fn new(pg_db: &Pool, model_instance: Arc) -> Result { - let db = Db::new(); - - let mut embeddings_db = Self { db, model_instance: model_instance.clone() }; - + let mut embeddings_db = Self::empty(model_instance); embeddings_db.fill_db(pg_db).await?; + Ok(embeddings_db) + } + /// The resource types alone, all embedded locally, for when the full fill cannot download + /// the hub's embeddings: an air-gapped instance, or a private hub serving none. Hub script + /// search keeps failing, since it has no collection to search. + async fn resource_types_only( + pg_db: &Pool, + model_instance: Arc, + ) -> Result { + let mut embeddings_db = Self::empty(model_instance); + let index = resource_type_index( + pg_db, + &embeddings_db.model_instance, + &embeddings_db.hub_resource_type_embeddings, + &embeddings_db.custom_resource_type_vectors, + ) + .await?; + embeddings_db.replace_resource_types(index)?; Ok(embeddings_db) } @@ -310,13 +425,6 @@ impl EmbeddingsDb { self.db .create_collection("scripts".to_string(), 384, Distance::Cosine)?; - if self.db.get_collection("resource_types").is_some() { - self.db.delete_collection("resource_types")?; - } - - self.db - .create_collection("resource_types".to_string(), 384, Distance::Cosine)?; - let hub_base_url = (**HUB_BASE_URL.load()).clone(); let response = match hub_base_url.as_str() { @@ -425,44 +533,40 @@ impl EmbeddingsDb { )); } let hub_resource_types = response.json::>().await?; + self.hub_resource_type_embeddings = Arc::new( + hub_resource_types + .into_iter() + .map(|rt| (rt.name, rt.embedding)) + .collect(), + ); - let resource_types: Vec = - sqlx::query_as!(ResourceType, "SELECT workspace_id, name, schema, description, created_by, edited_at, format_extension, is_fileset, display_name from resource_type ORDER BY name",) - .fetch_all(pg_db) - .await?; + let index = resource_type_index( + pg_db, + &self.model_instance, + &self.hub_resource_type_embeddings, + &self.custom_resource_type_vectors, + ) + .await?; + self.replace_resource_types(index) + } - for rt in resource_types { - let mut hm = HashMap::new(); - hm.insert("name".to_string(), rt.name.clone()); - if let Some(schema) = rt.schema.clone() { - hm.insert("schema".to_string(), serde_json::to_string(&schema)?); - } - hm.insert("workspace".to_string(), rt.workspace_id.clone()); - let hub_rt = hub_resource_types.iter().find(|hrt| hrt.name == rt.name); - - let vector = if let Some(hub_rt) = hub_rt { - hub_rt.embedding.clone() - } else { - self.model_instance - .clone() - .create_embedding(&format!( - "{};{}", - rt.name, - rt.description.unwrap_or_default() - )) - .await? - }; - - let embedding = Embedding { - id: format!("{}_{}", rt.workspace_id, rt.name), - vector, - metadata: Some(hm), - }; - - self.db - .insert_into_collection("resource_types", embedding)?; + fn replace_resource_types(&mut self, index: ResourceTypeIndex) -> Result<()> { + // Built aside and swapped in whole: an insert the collection refuses must not leave + // searches on a half-filled index. + const NEXT: &str = "resource_types_next"; + self.db.collections.remove(NEXT); + self.db + .create_collection(NEXT.to_string(), 384, Distance::Cosine)?; + for embedding in index.embeddings { + self.db.insert_into_collection(NEXT, embedding)?; } - + if let Some(next) = self.db.collections.remove(NEXT) { + self.db + .collections + .insert("resource_types".to_string(), next); + } + self.resource_types_fingerprint = index.fingerprint; + self.custom_resource_type_vectors = index.custom_vectors; Ok(()) } @@ -617,6 +721,101 @@ impl EmbeddingsDb { } } +/// Covers everything an indexed resource type is built from, whichever path wrote it: the +/// create and update routes, a hub sync's direct upserts, a delete. +/// +/// A sum of per-row hashes needs no sort. Don't go back to an ORDER BY aggregate: sorting +/// every schema spills to disk once they exceed work_mem, on every check of every server. +#[cfg(feature = "embedding")] +async fn resource_types_fingerprint(pg_db: &Pool) -> Result> { + Ok(sqlx::query_scalar( + "SELECT count(*)::text || ':' || coalesce(sum(('x' || left(md5(workspace_id || '/' || name || '/' || coalesce(description, '') || '/' || coalesce(schema::text, '')), 15))::bit(60)::bigint), 0)::text FROM resource_type", + ) + .fetch_one(pg_db) + .await?) +} + +/// The fingerprint is read before the rows: a write landing in between leaves it stale, so +/// the next check indexes again rather than keeping an index that misses the write. +#[cfg(feature = "embedding")] +async fn resource_type_index( + pg_db: &Pool, + model_instance: &Arc, + hub_embeddings: &HashMap>, + known_custom_vectors: &HashMap>, +) -> Result { + let fingerprint = resource_types_fingerprint(pg_db).await?; + let resource_types: Vec = + sqlx::query_as!(ResourceType, "SELECT workspace_id, name, schema, description, created_by, edited_at, format_extension, is_fileset, display_name from resource_type ORDER BY name",) + .fetch_all(pg_db) + .await?; + + let mut embeddings = Vec::with_capacity(resource_types.len()); + let mut custom_vectors = HashMap::new(); + for rt in resource_types { + let mut hm = HashMap::new(); + hm.insert("name".to_string(), rt.name.clone()); + if let Some(schema) = rt.schema.clone() { + hm.insert("schema".to_string(), serde_json::to_string(&schema)?); + } + hm.insert("workspace".to_string(), rt.workspace_id.clone()); + + let vector = match hub_embeddings.get(&rt.name) { + Some(vector) => vector.clone(), + None => { + let text = format!("{};{}", rt.name, rt.description.unwrap_or_default()); + let vector = match known_custom_vectors + .get(&text) + .or_else(|| custom_vectors.get(&text)) + { + Some(vector) => vector.clone(), + None => model_instance.clone().create_embedding(&text).await?, + }; + custom_vectors.insert(text, vector.clone()); + vector + } + }; + + embeddings.push(Embedding { + // Neither part can hold a `/`, so two types never share an id; with `_` between + // them, `acme_c` + `c_x` and `acme` + `c_c_x` would. + id: format!("{}/{}", rt.workspace_id, rt.name), + vector, + metadata: Some(hm), + }); + } + Ok(ResourceTypeIndex { fingerprint, embeddings, custom_vectors: Arc::new(custom_vectors) }) +} + +/// The full fill runs once a day, so a resource type created or synced in between would stay +/// unsearchable until then; this re-indexes the resource types alone when the table changed. +#[cfg(feature = "embedding")] +pub async fn refresh_resource_type_embeddings(pg_db: &Pool) -> Result<()> { + if EMBEDDINGS_DB.read().await.is_none() { + return Ok(()); + } + let fingerprint = resource_types_fingerprint(pg_db).await?; + let (model_instance, hub_embeddings, custom_vectors) = match EMBEDDINGS_DB.read().await.as_ref() + { + Some(db) if db.resource_types_fingerprint != fingerprint => ( + db.model_instance.clone(), + db.hub_resource_type_embeddings.clone(), + db.custom_resource_type_vectors.clone(), + ), + _ => return Ok(()), + }; + let index = + resource_type_index(pg_db, &model_instance, &hub_embeddings, &custom_vectors).await?; + if let Some(db) = EMBEDDINGS_DB.write().await.as_mut() { + // A full fill that landed meanwhile indexed the types from newer hub vectors than + // the ones this index was built from. + if Arc::ptr_eq(&db.hub_resource_type_embeddings, &hub_embeddings) { + db.replace_resource_types(index)?; + } + } + Ok(()) +} + #[cfg(feature = "embedding")] fn normalize_l2(v: &Tensor) -> Result { Ok(v.broadcast_div(&v.sqr()?.sum_keepdim(1)?.sqrt()?)?) @@ -630,6 +829,19 @@ pub fn load_embeddings_db(db: &Pool) -> () { .unwrap_or(false); if !disable_embedding { + let resource_types_db = db.clone(); + tokio::spawn(async move { + loop { + tokio::time::sleep(std::time::Duration::from_secs( + *RESOURCE_TYPE_EMBEDDINGS_CHECK_INTERVAL_SECS, + )) + .await; + if let Err(e) = refresh_resource_type_embeddings(&resource_types_db).await { + tracing::warn!("Failed to refresh resource type embeddings: {e:#}"); + } + } + }); + let db_clone = db.clone(); tokio::spawn(async move { // Keep retrying model init: a transient failure here must not @@ -664,6 +876,9 @@ pub fn load_embeddings_db(db: &Pool) -> () { backoff_secs = *HUB_EMBEDDINGS_RETRY_INTERVAL_SECS; *HUB_EMBEDDINGS_PULLING_INTERVAL_SECS } else { + if let Err(e) = index_resource_types_alone(&db_clone).await { + tracing::warn!("Failed to index the resource types alone: {e:#}"); + } let secs = backoff_secs; backoff_secs = backoff_secs .saturating_mul(2) @@ -696,7 +911,29 @@ pub async fn update_embeddings_db(db: &Pool) -> bool { } } +/// After a failed full fill, so a fill still downloading at startup is not raced. A full fill +/// that succeeds later replaces this index. #[cfg(feature = "embedding")] +async fn index_resource_types_alone(pg_db: &Pool) -> Result<()> { + if EMBEDDINGS_DB.read().await.is_some() { + return Ok(()); + } + let Some(model_instance) = MODEL_INSTANCE.read().await.clone() else { + return Ok(()); + }; + let started = std::time::Instant::now(); + let embeddings_db = EmbeddingsDb::resource_types_only(pg_db, model_instance).await?; + let mut current = EMBEDDINGS_DB.write().await; + if current.is_none() { + *current = Some(embeddings_db); + tracing::info!( + "Indexed the resource types alone in {:?}, without the hub's embeddings", + started.elapsed() + ); + } + Ok(()) +} + pub fn workspaced_service() -> Router { Router::new().route("/query_resource_types", get(query_resource_types)) } @@ -706,11 +943,6 @@ pub fn global_service() -> Router { Router::new().route("/query_hub_scripts", get(query_hub_scripts)) } -#[cfg(not(feature = "embedding"))] -pub fn workspaced_service() -> Router { - Router::new() -} - #[cfg(not(feature = "embedding"))] pub fn global_service() -> Router { Router::new() @@ -768,3 +1000,34 @@ mod tests { assert_eq!(trim_to_top_score(vec![0.42f32], 0.05, |s| *s), vec![0.42]); } } + +#[cfg(test)] +mod text_match_tests { + use super::text_match_score; + + // A query names the service, which a type's name only contains ("postgres" in + // `postgresql`): an exact comparison finds nothing for "postgres database". + #[test] + fn ranks_a_name_match_above_a_description_match() { + let words = vec!["postgres".to_string(), "database".to_string()]; + assert_eq!( + text_match_score(&words, "PostgreSQL", "PostgreSQL connection"), + 2.0 + ); + assert_eq!( + text_match_score(&words, "mysql", "MySQL database credentials"), + 1.0 + ); + assert_eq!(text_match_score(&words, "slack", "Slack bot token"), 0.0); + } + + // Many services go by a short name; matching it inside other names would rank `ms365` + // with `s3`. + #[test] + fn matches_a_short_word_only_as_a_whole_name_part() { + let words = vec!["s3".to_string()]; + assert_eq!(text_match_score(&words, "s3", "Amazon S3 bucket"), 2.0); + assert_eq!(text_match_score(&words, "aws_s3", ""), 2.0); + assert_eq!(text_match_score(&words, "ms365", "mentions s3"), 0.0); + } +} diff --git a/backend/windmill-api-flow-conversations/Cargo.toml b/backend/windmill-api-flow-conversations/Cargo.toml index dfb927e92e..d9e0c743ee 100644 --- a/backend/windmill-api-flow-conversations/Cargo.toml +++ b/backend/windmill-api-flow-conversations/Cargo.toml @@ -7,6 +7,9 @@ edition.workspace = true [lib] name = "windmill_api_flow_conversations" path = "src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [dependencies] windmill-api-auth.workspace = true diff --git a/backend/windmill-api-flows/Cargo.toml b/backend/windmill-api-flows/Cargo.toml index 3fc2c7b572..c0bb7ae5e2 100644 --- a/backend/windmill-api-flows/Cargo.toml +++ b/backend/windmill-api-flows/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_api_flows" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-api-flows/src/flows.rs b/backend/windmill-api-flows/src/flows.rs index 1007cfd5b1..fe4d8c37d4 100644 --- a/backend/windmill-api-flows/src/flows.rs +++ b/backend/windmill-api-flows/src/flows.rs @@ -20,7 +20,8 @@ use windmill_api_auth::{ require_owner_of_path, ApiAuthed, }; use windmill_common::workspaces::{ - check_deploy_rules, check_operator_can_build_flows, operator_can_build_flows, RuleCheckResult, + check_deploy_rules, check_operator_can_build, operator_builder_rights, BuilderKind, + RuleCheckResult, }; use windmill_common::{ user_drafts::{overlay_or_draft_only, DraftUserRef, UserDraftItemKind, WithDraftOverlay}, @@ -243,7 +244,7 @@ async fn list_flows( // Append the authed user's drafts at paths with no deployed flow; see scripts.rs. if lq.include_draft_only.unwrap_or(false) - && (!authed.is_operator || operator_can_build_flows(&db, &w_id).await?) + && (!authed.is_operator || operator_builder_rights(&db, &w_id).await?.flows) && offset == 0 && lq.path_start.is_none() && lq.path_exact.is_none() @@ -731,7 +732,14 @@ async fn create_flow( Path(w_id): Path, Json(mut nf): Json, ) -> Result<(StatusCode, String)> { - check_operator_can_build_flows(&db, &w_id, authed.is_operator, "create flows").await?; + check_operator_can_build( + &db, + &w_id, + authed.is_operator, + BuilderKind::Flows, + "create flows", + ) + .await?; check_scopes(&authed, || format!("flows:write:{}", nf.path))?; // A `<= 0` flow timeout is "unset", not a 0-second limit that kills every run instantly. @@ -797,6 +805,21 @@ async fn create_flow( nf.preserve_on_behalf_of = Some(true); } } + // Before `tx` opens, as every `db` read here must be: `user_db` wraps the same pool, so + // taking a second connection while holding `tx` lets concurrent deploys starve it. + let resolved_on_behalf_of = windmill_common::resolve_on_behalf_of( + nf.on_behalf_of_email.as_deref(), + nf.on_behalf_of.as_deref(), + nf.preserve_on_behalf_of.unwrap_or(false), + &authed, + &w_id, + &db, + ) + .await?; + // Written beside the principal only while a worker that still reads it may be live. + let legacy_on_behalf_of_email = + windmill_common::legacy_on_behalf_of_email(resolved_on_behalf_of.as_deref(), &w_id, &db) + .await?; let mut tx = user_db.clone().begin(&authed).await?; @@ -822,19 +845,6 @@ async fn create_flow( if restricts_steps { windmill_common::feature_usage::log_feature_usage("job_token_scopes", "deploy", "step:set"); } - let resolved_on_behalf_of = windmill_common::resolve_on_behalf_of( - nf.on_behalf_of_email.as_deref(), - nf.on_behalf_of.as_deref(), - nf.preserve_on_behalf_of.unwrap_or(false), - &authed, - &w_id, - &db, - ) - .await?; - // Written beside the principal only while a worker that still reads it may be live. - let legacy_on_behalf_of_email = - windmill_common::legacy_on_behalf_of_email(resolved_on_behalf_of.as_deref(), &w_id, &db) - .await?; sqlx::query!( r#"INSERT INTO flow ( workspace_id, path, summary, description, @@ -1344,7 +1354,14 @@ async fn update_flow( Path((w_id, flow_path)): Path<(String, StripPath)>, Json(ef): Json, ) -> Result { - check_operator_can_build_flows(&db, &w_id, authed.is_operator, "update flows").await?; + check_operator_can_build( + &db, + &w_id, + authed.is_operator, + BuilderKind::Flows, + "update flows", + ) + .await?; let flow_path = flow_path.to_path(); // The URL identifies the flow being updated; the body path is only needed to rename. let mut nf = ef.into_new_flow(flow_path); @@ -1374,6 +1391,20 @@ async fn update_flow( validate_flow(&nf, &authed, &db, &user_db, &w_id).await?; let authed = maybe_refresh_folders(&flow_path, &w_id, authed, &db).await; + // Before `tx` opens, for the reason given in `create_flow`. + let resolved_on_behalf_of = windmill_common::resolve_on_behalf_of( + nf.on_behalf_of_email.as_deref(), + nf.on_behalf_of.as_deref(), + nf.preserve_on_behalf_of.unwrap_or(false), + &authed, + &w_id, + &db, + ) + .await?; + // Written beside the principal only while a worker that still reads it may be live. + let legacy_on_behalf_of_email = + windmill_common::legacy_on_behalf_of_email(resolved_on_behalf_of.as_deref(), &w_id, &db) + .await?; let mut tx = user_db.clone().begin(&authed).await?; check_schedule_conflict(&mut tx, &w_id, flow_path).await?; @@ -1411,19 +1442,6 @@ async fn update_flow( if restricts_steps { windmill_common::feature_usage::log_feature_usage("job_token_scopes", "deploy", "step:set"); } - let resolved_on_behalf_of = windmill_common::resolve_on_behalf_of( - nf.on_behalf_of_email.as_deref(), - nf.on_behalf_of.as_deref(), - nf.preserve_on_behalf_of.unwrap_or(false), - &authed, - &w_id, - &db, - ) - .await?; - // Written beside the principal only while a worker that still reads it may be live. - let legacy_on_behalf_of_email = - windmill_common::legacy_on_behalf_of_email(resolved_on_behalf_of.as_deref(), &w_id, &db) - .await?; sqlx::query!( " @@ -2038,7 +2056,14 @@ async fn archive_flow_by_path( Path((w_id, path)): Path<(String, StripPath)>, Json(archived): Json, ) -> Result { - check_operator_can_build_flows(&db, &w_id, authed.is_operator, "archive flows").await?; + check_operator_can_build( + &db, + &w_id, + authed.is_operator, + BuilderKind::Flows, + "archive flows", + ) + .await?; let path = path.to_path(); check_scopes(&authed, || format!("flows:write:{}", path))?; if let RuleCheckResult::Blocked(msg) = check_deploy_rules( @@ -2179,7 +2204,14 @@ async fn delete_flow_by_path( Path((w_id, path)): Path<(String, StripPath)>, Query(query): Query, ) -> Result { - check_operator_can_build_flows(&db, &w_id, authed.is_operator, "delete flows").await?; + check_operator_can_build( + &db, + &w_id, + authed.is_operator, + BuilderKind::Flows, + "delete flows", + ) + .await?; let path = path.to_path(); check_scopes(&authed, || format!("flows:write:{}", path))?; if let RuleCheckResult::Blocked(msg) = check_deploy_rules( diff --git a/backend/windmill-api-groups/Cargo.toml b/backend/windmill-api-groups/Cargo.toml index 35443008f0..3887f3b03e 100644 --- a/backend/windmill-api-groups/Cargo.toml +++ b/backend/windmill-api-groups/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_api_groups" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-api-groups/src/groups.rs b/backend/windmill-api-groups/src/groups.rs index 0209af8585..860e486a75 100644 --- a/backend/windmill-api-groups/src/groups.rs +++ b/backend/windmill-api-groups/src/groups.rs @@ -238,6 +238,13 @@ async fn create_group( Json(ng): Json, ) -> Result { crate::check_demo_workspace_restriction(&authed, &w_id, "Group creation")?; + // Admins stay allowed: `wmill sync push` recreates exported groups through this endpoint. + if !authed.is_admin && windmill_common::RESERVED_GROUP_NAMES.contains(&ng.name.as_str()) { + return Err(Error::BadRequest(format!( + "Group name {} is reserved by Windmill; only an admin can create it", + ng.name + ))); + } let mut tx = user_db.begin(&authed).await?; check_name_conflict(&mut tx, &w_id, &ng.name).await?; @@ -470,26 +477,16 @@ async fn update_igroup( require_super_admin(&db, &authed).await?; let mut tx: Transaction<'_, Postgres> = db.begin().await?; - let exists_opt = sqlx::query("SELECT 1 FROM instance_group WHERE name = $1") - .bind(name.clone()) - .fetch_optional(&mut *tx) - .await?; - not_found_if_none(exists_opt, "instance_group", name.clone())?; + let old_role_opt = sqlx::query_scalar!( + "SELECT instance_role FROM instance_group WHERE name = $1 FOR UPDATE", + &name + ) + .fetch_optional(&mut *tx) + .await?; + let old_role = not_found_if_none(old_role_opt, "instance_group", name.clone())?; let validated_role = validate_instance_role(&igroup_update.instance_role)?; - // Fetch old role before updating so we can detect changes - let old_role = if igroup_update.instance_role.is_some() { - sqlx::query_scalar!( - "SELECT instance_role FROM instance_group WHERE name = $1", - &name - ) - .fetch_one(&mut *tx) - .await? - } else { - None - }; - sqlx::query("UPDATE instance_group SET summary = $1, instance_role = $2 WHERE name = $3") .bind(igroup_update.new_summary) .bind(&validated_role) @@ -497,8 +494,9 @@ async fn update_igroup( .execute(&mut *tx) .await?; - // If instance_role actually changed, propagate to all group members - if igroup_update.instance_role.is_some() && old_role != validated_role { + // An omitted or null instance_role is stored as NULL above, so it revokes like any other + // change: members must be recomputed whenever the stored role differs. + if old_role != validated_role { propagate_instance_group_roles(&name, &mut tx).await?; } @@ -664,21 +662,19 @@ async fn delete_igroup( // FOR UPDATE: the group row is the group-level mutex, taken before the workspace // advisory locks (see reconcile_workspace_instance_groups). - let group_role = sqlx::query_scalar!( + sqlx::query_scalar!( "SELECT instance_role FROM instance_group WHERE name = $1 FOR UPDATE", &name ) .fetch_optional(&mut *tx) - .await? - .flatten(); + .await?; - let affected_members: Vec = if group_role.is_some() { + // Collected whatever the group's current role: a member can still hold a role this group + // granted before it was cleared. + let affected_members: Vec = sqlx::query_scalar!("SELECT email FROM email_to_igroup WHERE igroup = $1", &name) .fetch_all(&mut *tx) - .await? - } else { - vec![] - }; + .await?; // Captured and advisory-locked before the settings update strips the group from them. #[cfg(feature = "private")] diff --git a/backend/windmill-api-inputs/Cargo.toml b/backend/windmill-api-inputs/Cargo.toml index 30d3f0d9f5..f5fbe3b0ea 100644 --- a/backend/windmill-api-inputs/Cargo.toml +++ b/backend/windmill-api-inputs/Cargo.toml @@ -7,6 +7,9 @@ edition.workspace = true [lib] name = "windmill_api_inputs" path = "src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [dependencies] windmill-api-auth.workspace = true diff --git a/backend/windmill-api-integration-tests/Cargo.toml b/backend/windmill-api-integration-tests/Cargo.toml index 69dbaeaaa2..8302b5b252 100644 --- a/backend/windmill-api-integration-tests/Cargo.toml +++ b/backend/windmill-api-integration-tests/Cargo.toml @@ -7,6 +7,9 @@ edition.workspace = true [lib] name = "windmill_api_integration_tests" path = "src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [features] default = [] diff --git a/backend/windmill-api-integration-tests/tests/agent_on_behalf_of.rs b/backend/windmill-api-integration-tests/tests/agent_on_behalf_of.rs new file mode 100644 index 0000000000..628614056c --- /dev/null +++ b/backend/windmill-api-integration-tests/tests/agent_on_behalf_of.rs @@ -0,0 +1,216 @@ +use serde_json::json; +use sqlx::{Pool, Postgres}; + +use windmill_test_utils::*; + +const AGENT: &str = "u/test-user-3/agent"; + +async fn post( + base_url: &str, + token: &str, + route: &str, + body: serde_json::Value, +) -> anyhow::Result<(u16, String)> { + let resp = reqwest::Client::new() + .post(format!("{base_url}/w/test-workspace/{route}")) + .header("Authorization", format!("Bearer {token}")) + .json(&body) + .send() + .await?; + Ok((resp.status().as_u16(), resp.text().await?)) +} + +async fn agent_identity(db: &Pool) -> anyhow::Result> { + Ok(sqlx::query_scalar::<_, Option>( + "SELECT value->>'on_behalf_of' FROM resource + WHERE workspace_id = 'test-workspace' AND path = $1", + ) + .bind(AGENT) + .fetch_one(db) + .await?) +} + +async fn job_identity(db: &Pool, id: &str) -> anyhow::Result<(String, String)> { + Ok( + sqlx::query_as("SELECT permissioned_as, created_by FROM v2_job WHERE id = $1::uuid") + .bind(id) + .fetch_one(db) + .await?, + ) +} + +/// The identity an agent runs as is in its value, which anyone who can write the agent writes: it +/// is kept only for an admin asking to keep it, and every other write makes it the writer's own, +/// so a writer cannot change what runs while it keeps running as someone else. It exists only +/// while the agent opts into running as it. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_agent_write_resets_identity(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let base_url = format!("http://localhost:{}/api", server.addr.port()); + let value = json!({ "system_prompt": "hi", "on_behalf_of": "u/test-user-2", + "run_on_behalf_of": true }); + + let (status, body) = post( + &base_url, + "SECRET_TOKEN", + "resources/create", + json!({ "path": AGENT, "resource_type": "ai_agent", "value": value, + "preserve_on_behalf_of": true }), + ) + .await?; + assert!((200..300).contains(&status), "create: {status} {body}"); + assert_eq!(agent_identity(&db).await?.as_deref(), Some("u/test-user-2")); + + // The agent's owner, not an admin, asking to keep it. + let (status, body) = post( + &base_url, + "SECRET_TOKEN_3", + &format!("resources/update/{AGENT}"), + json!({ "value": value, "preserve_on_behalf_of": true }), + ) + .await?; + assert!((200..300).contains(&status), "update: {status} {body}"); + assert_eq!(agent_identity(&db).await?.as_deref(), Some("u/test-user-3")); + + let mut off = value.clone(); + off["run_on_behalf_of"] = json!(false); + let (status, body) = post( + &base_url, + "SECRET_TOKEN", + &format!("resources/update/{AGENT}"), + json!({ "value": off, "preserve_on_behalf_of": true }), + ) + .await?; + assert!((200..300).contains(&status), "toggle off: {status} {body}"); + assert_eq!(agent_identity(&db).await?, None); + + Ok(()) +} + +/// Reading an agent is what allows running it. The run is the caller's unless the agent opts into +/// running as its identity: then `test-user-2`, a plain member, runs as `test-user-3`. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_agent_run_identity_and_needs_read(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let base_url = format!("http://localhost:{}/api", server.addr.port()); + + sqlx::query( + "INSERT INTO resource (workspace_id, path, value, resource_type, extra_perms, created_by) + VALUES ('test-workspace', $1, $2, 'ai_agent', '{}', 'test-user-3')", + ) + .bind(AGENT) + .bind(json!({ "system_prompt": "hi", "on_behalf_of": "u/test-user-3" })) + .execute(&db) + .await?; + + let run = format!("jobs/run/agent/{AGENT}"); + let (status, body) = post(&base_url, "SECRET_TOKEN_2", &run, json!({})).await?; + assert_eq!(status, 404, "an unreadable agent: {body}"); + + sqlx::query( + "UPDATE resource SET extra_perms = '{\"u/test-user-2\": false}' + WHERE workspace_id = 'test-workspace' AND path = $1", + ) + .bind(AGENT) + .execute(&db) + .await?; + let (status, body) = post( + &base_url, + "SECRET_TOKEN_2", + &run, + json!({ "user_message": "hi" }), + ) + .await?; + assert_eq!(status, 201, "a readable agent: {body}"); + assert_eq!( + job_identity(&db, &body).await?, + ("u/test-user-2".into(), "test-user-2".into()) + ); + + sqlx::query( + "UPDATE resource SET value = value || '{\"run_on_behalf_of\": true}' + WHERE workspace_id = 'test-workspace' AND path = $1", + ) + .bind(AGENT) + .execute(&db) + .await?; + let (status, body) = post( + &base_url, + "SECRET_TOKEN_2", + &run, + json!({ "user_message": "hi" }), + ) + .await?; + assert_eq!(status, 201, "an agent run on behalf of: {body}"); + assert_eq!( + job_identity(&db, &body).await?, + ("u/test-user-3".into(), "test-user-2".into()) + ); + + // The worker would resolve it with the identity's token, however the JSON spells the `$`. + for raw in [ + r#"{"user_message":"$var:u/test-user-3/secret"}"#, + r#"{"user_message":"\u0024var:u/test-user-3/secret"}"#, + ] { + let resp = reqwest::Client::new() + .post(format!("{base_url}/w/test-workspace/{run}")) + .header("Authorization", "Bearer SECRET_TOKEN_2") + .header("Content-Type", "application/json") + .body(raw) + .send() + .await?; + assert_eq!(resp.status().as_u16(), 400, "a reference in {raw}"); + } + + // The run takes its conversation outside the caller's row policy, so a reader must not + // continue another user's conversation; an admin still may, as the policy allows. + let chat = format!("{run}?memory_id=7d3f6a52-1c4e-4b8a-9f2d-0e5c6b7a8d91"); + let msg = json!({ "user_message": "hi" }); + let (status, body) = post(&base_url, "SECRET_TOKEN_3", &chat, msg.clone()).await?; + assert_eq!(status, 201, "the owner starts it: {body}"); + let (status, body) = post(&base_url, "SECRET_TOKEN_2", &chat, msg.clone()).await?; + assert_eq!(status, 400, "another reader: {body}"); + assert!(body.contains("another user"), "{body}"); + let (status, body) = post(&base_url, "SECRET_TOKEN", &chat, msg).await?; + assert_eq!( + status, 409, + "an admin passes ownership, held only by the running turn: {body}" + ); + + Ok(()) +} + +/// The identity is a username inside the value, so renaming the user has to move it there too. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_agent_identity_follows_user_rename(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let base_url = format!("http://localhost:{}/api", server.addr.port()); + + sqlx::query( + "INSERT INTO resource (workspace_id, path, value, resource_type, created_by) + VALUES ('test-workspace', $1, $2, 'ai_agent', 'test-user-3')", + ) + .bind(AGENT) + .bind(json!({ "run_on_behalf_of": true, "on_behalf_of": "u/test-user-2" })) + .execute(&db) + .await?; + let email: String = + sqlx::query_scalar("SELECT email FROM usr WHERE username = 'test-user-2' LIMIT 1") + .fetch_one(&db) + .await?; + + let resp = reqwest::Client::new() + .post(format!("{base_url}/users/rename/{email}")) + .header("Authorization", "Bearer SECRET_TOKEN") + .json(&json!({ "new_username": "renamed" })) + .send() + .await?; + let status = resp.status().as_u16(); + assert_eq!(status, 200, "rename: {}", resp.text().await?); + assert_eq!(agent_identity(&db).await?.as_deref(), Some("u/renamed")); + + Ok(()) +} diff --git a/backend/windmill-api-integration-tests/tests/agent_runs.rs b/backend/windmill-api-integration-tests/tests/agent_runs.rs deleted file mode 100644 index b0302187cb..0000000000 --- a/backend/windmill-api-integration-tests/tests/agent_runs.rs +++ /dev/null @@ -1,60 +0,0 @@ -use serde_json::json; -use sqlx::{Pool, Postgres}; - -use windmill_test_utils::*; - -const AGENT: &str = "u/test-user-3/agent"; - -async fn run(base_url: &str, token: &str) -> anyhow::Result<(u16, String)> { - let resp = reqwest::Client::new() - .post(format!( - "{base_url}/w/test-workspace/jobs/run/agent/{AGENT}" - )) - .header("Authorization", format!("Bearer {token}")) - .json(&json!({ "user_message": "hi" })) - .send() - .await?; - Ok((resp.status().as_u16(), resp.text().await?)) -} - -/// Reading an agent is what allows running it, and the run is the caller's own: `test-user-2`, a -/// plain member, runs `test-user-3`'s agent once it may read it, lending nobody's permissions. -#[sqlx::test(migrations = "../migrations", fixtures("base"))] -async fn test_agent_run_needs_read_and_runs_as_caller(db: Pool) -> anyhow::Result<()> { - initialize_tracing().await; - let server = ApiServer::start(db.clone()).await?; - let base_url = format!("http://localhost:{}/api", server.addr.port()); - - sqlx::query( - "INSERT INTO resource (workspace_id, path, value, resource_type, extra_perms, created_by) - VALUES ('test-workspace', $1, $2, 'ai_agent', '{}', 'test-user-3')", - ) - .bind(AGENT) - .bind(json!({ "system_prompt": "hi" })) - .execute(&db) - .await?; - - let (status, body) = run(&base_url, "SECRET_TOKEN_2").await?; - assert_eq!(status, 404, "an unreadable agent: {body}"); - - sqlx::query( - "UPDATE resource SET extra_perms = '{\"u/test-user-2\": false}' - WHERE workspace_id = 'test-workspace' AND path = $1", - ) - .bind(AGENT) - .execute(&db) - .await?; - let (status, body) = run(&base_url, "SECRET_TOKEN_2").await?; - assert_eq!(status, 201, "a readable agent: {body}"); - - let (permissioned_as, created_by) = sqlx::query_as::<_, (String, String)>( - "SELECT permissioned_as, created_by FROM v2_job WHERE id = $1::uuid", - ) - .bind(&body) - .fetch_one(&db) - .await?; - assert_eq!(permissioned_as, "u/test-user-2"); - assert_eq!(created_by, "test-user-2"); - - Ok(()) -} diff --git a/backend/windmill-api-integration-tests/tests/datatable_roles.rs b/backend/windmill-api-integration-tests/tests/datatable_roles.rs index 9800d97841..764cc3ac04 100644 --- a/backend/windmill-api-integration-tests/tests/datatable_roles.rs +++ b/backend/windmill-api-integration-tests/tests/datatable_roles.rs @@ -810,7 +810,7 @@ async fn a_data_table_under_roles_is_cloned_only_with_its_grants( // The copy an admin asks for goes ahead in an edition that replays grants, and is refused // before any database exists in one that does not. The fixture's database does not exist, so - // the dump fails either way — and leaves neither a database nor a fork behind. + // reading it fails either way — and leaves neither a database nor a fork behind. let resp = fork( "SECRET_TOKEN", json!({"name": "main", "new_dbname": target, "fork_behavior": "schema_only"}), @@ -820,7 +820,7 @@ async fn a_data_table_under_roles_is_cloned_only_with_its_grants( assert_ne!(resp.status(), 200); let body = resp.text().await?; #[cfg(all(feature = "private", feature = "enterprise"))] - assert!(body.contains("pg_dump"), "{body}"); + assert!(body.contains("\"dt_main\" does not exist"), "{body}"); #[cfg(not(all(feature = "private", feature = "enterprise")))] assert!(body.contains("Enterprise Edition"), "{body}"); assert!(!database_exists(&db, target).await?); @@ -981,6 +981,104 @@ async fn a_data_table_under_roles_is_not_copied_without_its_grants( Ok(()) } +#[sqlx::test(migrations = "../migrations", fixtures("base", "datatable_roles"))] +async fn data_tables_on_one_database_are_copied_together(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let shared = json!({"database": {"resource_type": "instance", "resource_path": "dt_shared"}}); + sqlx::query( + "UPDATE workspace_settings SET datatable = jsonb_set(jsonb_set(datatable, + '{datatables,a}', $1), '{datatables,b}', $1) WHERE workspace_id = 'test-workspace'", + ) + .bind(&shared) + .execute(&db) + .await?; + + // One copy is made for both, so it cannot be made two ways. + let resp = authed( + client().post(format!( + "http://localhost:{port}/api/w/test-workspace/workspaces/create_fork" + )), + "SECRET_TOKEN", + ) + .json( + &json!({"id": "wm-fork-pair", "name": "pair", "forked_datatables": [ + {"name": "a", "new_dbname": "wm_fork_pair__a", "fork_behavior": "schema_only"}, + {"name": "b", "new_dbname": "wm_fork_pair__b", "fork_behavior": "schema_and_data"} + ]}), + ) + .send() + .await?; + assert_eq!(resp.status(), 400); + assert!(resp.text().await?.contains("same database")); + assert!(!database_exists(&db, "wm_fork_pair__a").await?); + + // A fork's entries sharing a copy each count as a use of it: dropped together, neither blocks + // the other. + let copy = json!({"database": {"resource_type": "instance", "resource_path": "wm_fork_dt__a"}, + "forked_from": {"schema": {}}}); + sqlx::query( + "UPDATE workspace_settings SET datatable = jsonb_build_object('datatables', + jsonb_build_object('a', $1::jsonb, 'b', $1::jsonb)) WHERE workspace_id = 'wm-fork-dt'", + ) + .bind(©) + .execute(&db) + .await?; + sqlx::query( + "UPDATE global_settings SET value = jsonb_set(value, '{databases,wm_fork_dt__a}', + '{\"tag\": \"datatable\", \"workspace_id\": \"test-workspace\"}') + WHERE name = 'custom_instance_pg_databases'", + ) + .execute(&db) + .await?; + let errors: Vec = authed( + client().post(format!( + "http://localhost:{port}/api/w/wm-fork-dt/workspaces/drop_forked_datatable_databases" + )), + "SECRET_TOKEN", + ) + .json(&json!({"datatable_names": ["a", "b"]})) + .send() + .await? + .json() + .await?; + assert!(errors.is_empty(), "{errors:?}"); + let left: Value = sqlx::query_scalar( + "SELECT datatable->'datatables' FROM workspace_settings WHERE workspace_id = 'wm-fork-dt'", + ) + .fetch_one(&db) + .await?; + assert_eq!(left, json!({})); + + // Clones on one resource share its copy too: dropping it for one would take the other's data. + let copy = json!({"database": {"resource_type": "postgresql", "resource_path": "u/test-user/pg"}, + "forked_from": {"schema": {}}}); + sqlx::query( + "UPDATE workspace_settings SET datatable = jsonb_build_object('datatables', + jsonb_build_object('a', $1::jsonb, 'b', $1::jsonb)) WHERE workspace_id = 'wm-fork-dt'", + ) + .bind(©) + .execute(&db) + .await?; + let errors: Vec = authed( + client().post(format!( + "http://localhost:{port}/api/w/wm-fork-dt/workspaces/drop_forked_datatable_databases" + )), + "SECRET_TOKEN", + ) + .json(&json!({"datatable_names": ["a"]})) + .send() + .await? + .json() + .await?; + assert!( + errors.len() == 1 && errors[0].contains("still used by data tables 'b'"), + "{errors:?}" + ); + Ok(()) +} + /// The fork's `forked_from` for one of its entries; `None` whether it is absent or `null`. async fn forked_from_of(db: &Pool, name: &str) -> Option { sqlx::query_scalar::<_, Option>( @@ -1847,3 +1945,242 @@ async fn cleanup_waits_out_a_save_racing_it_for_an_instance_database( assert_eq!(users, vec!["test-workspace".to_string()]); Ok(()) } + +#[cfg(all(feature = "private", feature = "enterprise"))] +#[sqlx::test(migrations = "../migrations", fixtures("base", "datatable_roles"))] +async fn a_connection_naming_no_role_holds_the_default_one_and_its_identitys( + db: Pool, +) -> anyhow::Result<()> { + use windmill_common::workspaces::{ + get_datatable_resource_from_db, DatatableAccess, DatatableConnectAs, + }; + + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let suffix: String = uuid::Uuid::new_v4().simple().to_string()[..8].to_string(); + let names = [ + format!("wmtest_floor_{suffix}"), + format!("wmtest_emea_{suffix}"), + format!("wmtest_amer_{suffix}"), + ]; + let roles_url = format!("http://localhost:{port}/api/settings/datatable_roles"); + const MEMBER_LOGINS: &str = "SELECT m.rolname::text FROM pg_auth_members am + JOIN pg_roles r ON r.oid = am.roleid JOIN pg_roles m ON m.oid = am.member + WHERE r.rolname = $1 AND m.rolname LIKE 'wm\\_set\\_%'"; + + let connect_job = |owner: &'static str, role: Option<&'static str>, connect_as| { + let (permissioned_as, email) = match owner { + "test-user" => ("u/test-user", "test@windmill.dev"), + "test-user-2" => ("u/test-user-2", "test2@windmill.dev"), + _ => ("u/test-user-3", "test3@windmill.dev"), + }; + get_datatable_resource_from_db( + &db, + "test-workspace", + "main", + role, + DatatableAccess::PermissionedAs { permissioned_as, email, connect_as }, + ) + }; + // An app published by the workspace admin `test-user`, run by `viewer`, whose runnable + // connects as its viewer. + let connect = |role: Option<&'static str>, viewer: Option<&'static str>| { + connect_job("test-user", role, DatatableConnectAs::Viewer(viewer)) + }; + let set_permissions = |default_role: String, roles: Value| { + sqlx::query( + "UPDATE workspace_settings + SET datatable = jsonb_set(datatable, '{datatables,main,permissions}', $1) + WHERE workspace_id = 'test-workspace'", + ) + .bind(json!({ "default_role": default_role, "roles": roles })) + .execute(&db) + }; + + let outcome = async { + let mut ids = vec![]; + for name in &names { + let created: Value = authed(client().post(&roles_url), "SECRET_TOKEN") + .json(&json!({ "name": name })) + .send() + .await? + .error_for_status()? + .json() + .await?; + ids.push(created["id"].as_str().unwrap().to_string()); + } + // `test-user-2` is named by both regional roles, one of them through a group, and by + // `admin`; `test-user-3` by one; the workspace admin `test-user` by neither. + let roles = json!({ + "admin": {"tenants": ["u/test-user-2"]}, + (ids[0].as_str()): {"tenants": ["*"]}, + (ids[1].as_str()): {"tenants": ["u/test-user-2", "u/test-user-3"]}, + (ids[2].as_str()): {"tenants": ["g/analysts"]}, + }); + set_permissions(ids[0].clone(), roles.clone()).await?; + sqlx::query( + "INSERT INTO usr_to_group (workspace_id, usr, group_) + VALUES ('test-workspace', 'test-user-2', 'analysts')", + ) + .execute(&db) + .await?; + let member_of = |login: String| async { + let mut roles: Vec = sqlx::query_scalar( + "SELECT r.rolname::text FROM pg_auth_members am + JOIN pg_roles r ON r.oid = am.roleid JOIN pg_roles m ON m.oid = am.member + WHERE m.rolname = $1", + ) + .bind(login) + .fetch_all(&db) + .await?; + roles.sort(); + Ok::<_, anyhow::Error>(roles) + }; + + let all = connect(None, Some("test2@windmill.dev")).await?; + let login = all["user"].as_str().unwrap().to_string(); + assert!(login.starts_with("wm_set_"), "{login}"); + let mut expected = names.to_vec(); + expected.sort(); + assert_eq!( + member_of(login.clone()).await?, + expected, + "the login holds the default role and the viewer's, and not `admin`" + ); + assert_eq!(connect(None, Some("test2@windmill.dev")).await?, all); + + let two = connect(None, Some("test3@windmill.dev")).await?; + let mut expected = names[..2].to_vec(); + expected.sort(); + assert_eq!( + member_of(two["user"].as_str().unwrap().to_string()).await?, + expected + ); + + // A runnable that does not connect as its viewer holds its own identity's roles, whoever + // views it: here the publisher, an admin, who may use every role but adds only what + // names them, which is nothing. + assert_eq!( + connect_job("test-user", None, DatatableConnectAs::Job).await?["user"], + names[0].as_str(), + "the viewer's roles reached a job that does not connect as its viewer" + ); + // A job with no viewer, a schedule say, holds its owner's roles. + assert_eq!( + connect_job("test-user-2", None, DatatableConnectAs::Job).await?, + all + ); + assert_eq!( + connect(None, Some("test@windmill.dev")).await?["user"], + names[0].as_str() + ); + // Connecting as a viewer it does not have is refused rather than made as the job. + assert!(connect(None, None).await.is_err()); + // A named role is that role alone, whoever is viewing. + let named: &'static str = Box::leak(names[1].clone().into_boxed_str()); + assert_eq!( + connect(Some(named), Some("test2@windmill.dev")).await?["user"], + names[1].as_str() + ); + // A default of `admin` is the connection it always was: the viewer's roles are not added. + set_permissions("admin".to_string(), roles.clone()).await?; + let admin = connect(None, Some("test2@windmill.dev")).await?; + assert_eq!(admin, connect(Some("admin"), None).await?); + assert!(!admin["user"].as_str().unwrap().starts_with("wm_")); + + // With no default role the viewer's roles are all there is, the one open to everyone + // included, and a connection left with none is refused rather than resolved as anything. + set_permissions("$none".to_string(), roles.clone()).await?; + assert_eq!( + connect(None, Some("test3@windmill.dev")).await?, + two, + "no default changes nothing for a viewer the roles name" + ); + assert_eq!( + connect_job("test-user-3", None, DatatableConnectAs::Job).await?, + two + ); + assert_eq!( + connect_job("test-user", None, DatatableConnectAs::Job).await?["user"], + names[0].as_str(), + "the role open to everyone names the admin too" + ); + assert!(connect(None, None).await.is_err()); + // The same holds for a default the job's own identity is not a tenant of. + let mut closed = roles.clone(); + closed[ids[0].as_str()] = json!({"tenants": []}); + set_permissions(ids[0].clone(), closed).await?; + assert_eq!( + connect_job("test-user-3", None, DatatableConnectAs::Job).await?["user"], + names[1].as_str() + ); + assert_eq!( + connect(None, Some("test3@windmill.dev")).await?["user"], + names[1].as_str() + ); + set_permissions(ids[0].clone(), roles).await?; + + // A set login nobody connects with any more is dropped, a recent one is kept, and a + // dropped one is made again for the next viewer who needs it. + let exists = || async { + sqlx::query_scalar::<_, bool>( + "SELECT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = $1)", + ) + .bind(&login) + .fetch_one(&db) + .await + }; + windmill_common::datatable_roles::sweep_unused_role_set_logins(&db).await?; + assert!(exists().await?, "a set login in use was swept"); + sqlx::query("UPDATE datatable_role_set SET last_used_at = now() - interval '31 days'") + .execute(&db) + .await?; + windmill_common::datatable_roles::sweep_unused_role_set_logins(&db).await?; + assert!(!exists().await?, "an unused set login was kept"); + assert_eq!( + connect(None, Some("test2@windmill.dev")).await?["user"], + login.as_str() + ); + + // A disabled role must not stay reachable through a login that is a member of it. + authed( + client().post(format!("{roles_url}/{}", ids[2])), + "SECRET_TOKEN", + ) + .json(&json!({ "enabled": false })) + .send() + .await? + .error_for_status()?; + let can_login: bool = + sqlx::query_scalar("SELECT rolcanlogin FROM pg_roles WHERE rolname = $1") + .bind(&login) + .fetch_one(&db) + .await?; + assert!(!can_login, "{login} still logs in with a disabled role"); + assert_eq!( + connect(None, Some("test2@windmill.dev")).await?["user"], + two["user"] + ); + Ok::<_, anyhow::Error>(()) + } + .await; + + // Roles are cluster-wide, so they outlive this test's throwaway database. + for name in &names { + let logins: Vec = sqlx::query_scalar(MEMBER_LOGINS) + .bind(name) + .fetch_all(&db) + .await + .unwrap_or_default(); + for login in logins { + let _ = sqlx::query(&format!("DROP ROLE IF EXISTS \"{login}\"")) + .execute(&db) + .await; + } + let _ = sqlx::query(&format!("DROP ROLE IF EXISTS \"{name}\"")) + .execute(&db) + .await; + } + outcome +} diff --git a/backend/windmill-api-integration-tests/tests/fork_clone_on_behalf_of.rs b/backend/windmill-api-integration-tests/tests/fork_clone_on_behalf_of.rs index bc6c10f1ee..10fc0a8028 100644 --- a/backend/windmill-api-integration-tests/tests/fork_clone_on_behalf_of.rs +++ b/backend/windmill-api-integration-tests/tests/fork_clone_on_behalf_of.rs @@ -62,14 +62,31 @@ async fn fork_with_public_app( /// An app policy's `on_behalf_of` is the identity anonymous and publisher executions queue jobs /// under, and the fork's endpoint outlives any revocation in the parent — so a creator who may -/// not preserve someone else's identity must not receive one by forking. `test-user-2` is a -/// plain member of the parent. +/// not preserve someone else's identity must not receive one by forking. The same goes for the +/// one an agent's value carries. `test-user-2` is a plain member of the parent. #[sqlx::test(migrations = "../migrations", fixtures("base"))] async fn test_fork_repoints_app_identity_for_unprivileged_creator( db: Pool, ) -> anyhow::Result<()> { + sqlx::query( + "INSERT INTO resource (workspace_id, path, value, resource_type, extra_perms, created_by) + VALUES ('test-workspace', 'u/test-user/agent', $1, 'ai_agent', '{}', 'test-user')", + ) + .bind(json!({ "system_prompt": "hi", "on_behalf_of": "u/test-user" })) + .execute(&db) + .await?; let (policy, custom_path) = fork_with_public_app(&db, "SECRET_TOKEN_2").await?; + assert_eq!( + sqlx::query_scalar::<_, String>( + "SELECT value->>'on_behalf_of' FROM resource + WHERE workspace_id = 'wm-fork-app' AND path = 'u/test-user/agent'" + ) + .fetch_one(&db) + .await?, + "u/test-user-2" + ); + assert_eq!(policy["on_behalf_of"], json!("u/test-user-2")); assert_eq!(policy["on_behalf_of_email"], json!("test2@windmill.dev")); // `execution_mode` rides along untouched — see `clone_apps`. @@ -312,8 +329,9 @@ async fn test_fork_keeps_only_resolvable_on_behalf_of(db: Pool) -> any Ok(()) } -/// Apps, schedules, triggers and their drafts cannot drop an identity the way scripts and flows -/// do, so one naming nobody in the fork goes to its creator while one that still resolves stays. +/// Apps, agents, schedules, triggers and their drafts cannot drop an identity the way scripts and +/// flows do, so one naming nobody in the fork goes to its creator while one that still resolves +/// stays. /// Forked as an admin, whose app policies the clone otherwise keeps. #[sqlx::test(migrations = "../migrations", fixtures("base"))] async fn test_fork_repoints_unresolvable_identities(db: Pool) -> anyhow::Result<()> { @@ -367,6 +385,13 @@ async fn test_fork_repoints_unresolvable_identities(db: Pool) -> anyho )) .execute(&db) .await?; + sqlx::query( + "INSERT INTO resource (workspace_id, path, value, resource_type, extra_perms, created_by) + VALUES ('test-workspace', 'u/test-user/stranger', $1, 'ai_agent', '{}', 'test-user')", + ) + .bind(json!({ "system_prompt": "hi", "on_behalf_of": "u/test-user-2" })) + .execute(&db) + .await?; sqlx::query( "INSERT INTO schedule (workspace_id, path, edited_by, schedule, script_path, email, permissioned_as, enabled) VALUES ('test-workspace', 'u/test-user/stranger', 'test-user', '0 0 * * * *', 'u/test-user/s', 'test2@windmill.dev', 'u/test-user-2', false)", @@ -424,6 +449,10 @@ async fn test_fork_repoints_unresolvable_identities(db: Pool) -> anyho text("SELECT value->>'permissioned_as' FROM draft WHERE workspace_id = 'wm-fork-repoint' AND typ = 'trigger_websocket'").await?, "u/test-user" ); + assert_eq!( + text("SELECT value->>'on_behalf_of' FROM resource WHERE workspace_id = 'wm-fork-repoint' AND path = 'u/test-user/stranger'").await?, + "u/test-user" + ); assert_eq!( text("SELECT permissioned_as || ' ' || email FROM schedule WHERE workspace_id = 'wm-fork-repoint'").await?, "u/test-user test@windmill.dev" diff --git a/backend/windmill-api-integration-tests/tests/fork_secret_replication_azure.rs b/backend/windmill-api-integration-tests/tests/fork_secret_replication_azure.rs index 19682de70a..855b45e2ca 100644 --- a/backend/windmill-api-integration-tests/tests/fork_secret_replication_azure.rs +++ b/backend/windmill-api-integration-tests/tests/fork_secret_replication_azure.rs @@ -14,14 +14,16 @@ //! (lowkey-vault), which the `AzureKeyVaultBackend` talks to via its //! static-token / self-signed-cert emulator mode. //! -//! Run it: +//! The test is `#[ignore]`d, so a plain `cargo test` skips it without creating +//! a database. Run it with `--ignored` (`AZURE_KV_URL` overrides the default +//! https://localhost:8443): //! ```bash //! podman run -d --name lowkey -p 8443:8443 \ //! -e LOWKEY_ARGS="--LOWKEY_VAULT_NAMES=default" \ //! docker.io/nagyesta/lowkey-vault:7.3.0 //! -//! RUN_AZURE_KV_TESTS=1 cargo test -p windmill-api-integration-tests \ -//! --features private,enterprise --test fork_secret_replication_azure -- --nocapture +//! cargo test -p windmill-api-integration-tests \ +//! --features private,enterprise --test fork_secret_replication_azure -- --ignored --nocapture //! ``` #[cfg(all(feature = "private", feature = "enterprise"))] @@ -55,11 +57,8 @@ mod azure_fork { } #[sqlx::test(migrations = "../migrations", fixtures("base"))] + #[ignore = "requires a lowkey-vault Azure Key Vault emulator at AZURE_KV_URL"] async fn migrated_secret_is_replicated_on_fork(db: Pool) -> anyhow::Result<()> { - if std::env::var("RUN_AZURE_KV_TESTS").as_deref() != Ok("1") { - eprintln!("skipping: set RUN_AZURE_KV_TESTS=1 and start lowkey-vault to run"); - return Ok(()); - } initialize_tracing().await; // The Azure KV emulator persists across runs; derive unique names per run diff --git a/backend/windmill-api-integration-tests/tests/groups.rs b/backend/windmill-api-integration-tests/tests/groups.rs index 26e5caeea1..20e866cc37 100644 --- a/backend/windmill-api-integration-tests/tests/groups.rs +++ b/backend/windmill-api-integration-tests/tests/groups.rs @@ -497,6 +497,72 @@ async fn test_remove_user_from_instance_group_rederives_role( Ok(()) } +/// Clearing an instance group's role, or deleting a group whose role was cleared out from under +/// its members, must take the instance-level role back from them. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_instance_group_role_revoked_on_clear_and_delete( + db: Pool, +) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let global_base = format!("http://localhost:{port}/api/groups"); + let email = "test2@windmill.dev"; + + let is_super_admin = || async { + sqlx::query_scalar::<_, bool>("SELECT super_admin FROM password WHERE email = $1") + .bind(email) + .fetch_one(&db) + .await + }; + + let resp = authed(client().post(format!("{global_base}/create"))) + .json(&json!({ "name": "admins_grp" })) + .send() + .await?; + assert_eq!(resp.status(), 200, "create: {}", resp.text().await?); + let resp = authed(client().post(format!("{global_base}/update/admins_grp"))) + .json(&json!({ "new_summary": "", "instance_role": "superadmin" })) + .send() + .await?; + assert_eq!(resp.status(), 200, "set role: {}", resp.text().await?); + let resp = authed(client().post(format!("{global_base}/adduser/admins_grp"))) + .json(&json!({ "email": email })) + .send() + .await?; + assert_eq!(resp.status(), 200, "adduser: {}", resp.text().await?); + assert!(is_super_admin().await?, "group should grant superadmin"); + + let resp = authed(client().post(format!("{global_base}/update/admins_grp"))) + .json(&json!({ "new_summary": "", "instance_role": null })) + .send() + .await?; + assert_eq!(resp.status(), 200, "update: {}", resp.text().await?); + assert!( + !is_super_admin().await?, + "clearing the group's role must revoke superadmin" + ); + + // A member left elevated while the group's stored role is already NULL. + sqlx::query( + "UPDATE password SET super_admin = true, role_source = 'instance_group' WHERE email = $1", + ) + .bind(email) + .execute(&db) + .await?; + + let resp = authed(client().delete(format!("{global_base}/delete/admins_grp"))) + .send() + .await?; + assert_eq!(resp.status(), 200, "delete: {}", resp.text().await?); + assert!( + !is_super_admin().await?, + "deleting a role-cleared group must revoke superadmin" + ); + + Ok(()) +} + /// An overwrite import that moves a member from a dropped group to a retained one must keep /// their workspace data. /// @@ -1050,3 +1116,38 @@ async fn test_instance_group_member_that_is_not_an_email_is_skipped( Ok(()) } + +/// A non-admin who creates a reserved group first becomes its member and inherits every grant +/// Windmill later gives it. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_reserved_group_names_admin_only(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let base = format!( + "http://localhost:{}/api/w/test-workspace/groups", + server.addr.port() + ); + + for name in windmill_common::RESERVED_GROUP_NAMES { + let resp = client() + .post(format!("{base}/create")) + .header("Authorization", "Bearer SECRET_TOKEN_2") + .json(&json!({ "name": name })) + .send() + .await?; + assert_eq!(resp.status(), 400, "non-admin creating {name}"); + assert!(resp.text().await?.contains("reserved")); + + let resp = authed(client().post(format!("{base}/create"))) + .json(&json!({ "name": name })) + .send() + .await?; + assert_eq!( + resp.status(), + 200, + "admin creating {name}: {}", + resp.text().await? + ); + } + Ok(()) +} diff --git a/backend/windmill-api-integration-tests/tests/jobs_authed.rs b/backend/windmill-api-integration-tests/tests/jobs_authed.rs index c3da2f3fb9..2c5d2ee78e 100644 --- a/backend/windmill-api-integration-tests/tests/jobs_authed.rs +++ b/backend/windmill-api-integration-tests/tests/jobs_authed.rs @@ -702,3 +702,51 @@ async fn test_list_filtered_job_uuids_resolved_excludes_queue( Ok(()) } + +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_worker_is_draining_follows_the_job_worker(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + let job = Uuid::new_v4(); + sqlx::query( + "INSERT INTO v2_job (id, workspace_id, created_by, permissioned_as, kind, tag, args) + VALUES ($1, 'test-workspace', 'test-user', 'u/test-user', 'script', 'deno', '{}'::jsonb)", + ) + .bind(job) + .execute(&db) + .await?; + sqlx::query( + "INSERT INTO v2_job_queue (id, workspace_id, scheduled_for, tag, running, started_at, worker) + VALUES ($1, 'test-workspace', now(), 'deno', true, now(), 'wk-drain-test')", + ) + .bind(job) + .execute(&db) + .await?; + sqlx::query( + "INSERT INTO worker_ping (worker, worker_instance, ip, worker_group, wm_version) + VALUES ('wk-drain-test', 'host', 'NO IP', 'default', 'v0')", + ) + .execute(&db) + .await?; + + let url = format!("http://localhost:{port}/api/w/test-workspace/jobs/worker_is_draining/{job}"); + let draining = || async { + let resp = authed(client().get(&url)).send().await?; + anyhow::Ok(resp.json::().await?) + }; + assert!(!draining().await?); + + windmill_common::worker::set_worker_draining_query("wk-drain-test", &db).await?; + assert!(draining().await?); + + // A parked job keeps its last worker on the queue row without running on it. + sqlx::query("UPDATE v2_job_queue SET started_at = NULL WHERE id = $1") + .bind(job) + .execute(&db) + .await?; + assert!(!draining().await?); + + Ok(()) +} diff --git a/backend/windmill-api-integration-tests/tests/jobs_unauthed.rs b/backend/windmill-api-integration-tests/tests/jobs_unauthed.rs index fa8b6cb66f..5cb7d0dfb5 100644 --- a/backend/windmill-api-integration-tests/tests/jobs_unauthed.rs +++ b/backend/windmill-api-integration-tests/tests/jobs_unauthed.rs @@ -236,14 +236,17 @@ async fn test_jobs_unauthed_complex_reachability(db: Pool) -> anyhow:: "GET /get_log_file", ); - let resp = authed(client().post(format!("{base}/queue/cancel_persistent/u/test-user/fake"))) + // Unauthenticated, so the handler refuses before cancelling, which sleeps for seconds. + let resp = client() + .post(format!("{base}/queue/cancel_persistent/u/test-user/fake")) .json(&serde_json::json!({"reason": "test"})) .send() .await?; - assert_route_reachable( - resp.status().as_u16(), - &resp.text().await?, - "POST /queue/cancel_persistent", + let status = resp.status().as_u16(); + let body = resp.text().await?; + assert!( + status == 400 && body.contains("Cancelling persistent script require"), + "POST /queue/cancel_persistent did not reach its handler: {status} {body}" ); Ok(()) diff --git a/backend/windmill-api-integration-tests/tests/mcp_preprocessor_headers.rs b/backend/windmill-api-integration-tests/tests/mcp_preprocessor_headers.rs index 25942e845c..7ae631b5dc 100644 --- a/backend/windmill-api-integration-tests/tests/mcp_preprocessor_headers.rs +++ b/backend/windmill-api-integration-tests/tests/mcp_preprocessor_headers.rs @@ -127,7 +127,7 @@ async fn test_mcp_preprocessor_receives_the_callers_headers( .and_then(|list| { list.iter() .filter_map(|t| t["name"].as_str()) - .find(|n| n.contains("mcp__hdr__probe")) + .find(|n| *n == "mcp_hdr_probe") }) .ok_or_else(|| anyhow::anyhow!("the deployed script was not listed as a tool: {tools}"))? .to_string(); diff --git a/backend/windmill-api-integration-tests/tests/nested_dev_workspace.rs b/backend/windmill-api-integration-tests/tests/nested_dev_workspace.rs index a9549b91a8..fb92236ae1 100644 --- a/backend/windmill-api-integration-tests/tests/nested_dev_workspace.rs +++ b/backend/windmill-api-integration-tests/tests/nested_dev_workspace.rs @@ -432,13 +432,35 @@ async fn test_archive_takes_the_pairing_lock_for_a_standalone_workspace( .execute(&mut *held) .await?; - let finished = - tokio::time::timeout(std::time::Duration::from_secs(5), archive(port, "h-cand")).await; - assert!( - finished.is_err(), - "archive of a standalone workspace completed while its pairing lock was held: {finished:?}" - ); + let archiving = tokio::spawn(async move { archive(port, "h-cand").await }); + + let mut parked = false; + for _ in 0..400 { + let waiting: i64 = sqlx::query_scalar( + "SELECT count(*) FROM pg_stat_activity WHERE wait_event_type = 'Lock' \ + AND wait_event = 'advisory' AND datname = current_database() \ + AND query LIKE '%dev_workspace_pairing%' AND pid <> pg_backend_pid()", + ) + .fetch_one(&db) + .await?; + if waiting > 0 { + parked = true; + break; + } + assert!( + !archiving.is_finished(), + "archive of a standalone workspace completed while its pairing lock was held: {:?}", + archiving.await + ); + tokio::time::sleep(std::time::Duration::from_millis(25)).await; + } + assert!(parked, "archive never waited on the pairing lock"); held.rollback().await?; + let (status, body) = archiving.await?; + assert!( + status.is_success(), + "archive after the lock was released returned {status}: {body}" + ); Ok(()) } diff --git a/backend/windmill-api-integration-tests/tests/offboarding.rs b/backend/windmill-api-integration-tests/tests/offboarding.rs index 7bdeab924b..8dc8079096 100644 --- a/backend/windmill-api-integration-tests/tests/offboarding.rs +++ b/backend/windmill-api-integration-tests/tests/offboarding.rs @@ -90,6 +90,25 @@ async fn test_offboard_to_user(db: Pool) -> anyhow::Result<()> { .execute(&db) .await?; + // An agent records who it runs as inside its value, on a path the user does not own. + sqlx::query( + "INSERT INTO resource (workspace_id, path, value, resource_type, created_by) + VALUES ('test-workspace', 'f/shared/agent', $1, 'ai_agent', 'test-user')", + ) + .bind(json!({ "run_on_behalf_of": true, "on_behalf_of": "u/test-user-2" })) + .execute(&db) + .await?; + let preview: serde_json::Value = + authed(client().get(ws_url(port, "offboard_preview/test-user-2"))) + .send() + .await? + .json() + .await?; + assert_eq!( + preview["executing_on_behalf"]["resources"], + json!(["f/shared/agent"]) + ); + let resp = authed(client().post(ws_url(port, "offboard/test-user-2"))) .json(&json!({ "reassign_to": "u/test-user", @@ -100,6 +119,14 @@ async fn test_offboard_to_user(db: Pool) -> anyhow::Result<()> { .await?; assert_eq!(resp.status(), 200); + let agent_obo: Option = sqlx::query_scalar( + "SELECT value->>'on_behalf_of' FROM resource + WHERE path = 'f/shared/agent' AND workspace_id = 'test-workspace'", + ) + .fetch_one(&db) + .await?; + assert_eq!(agent_obo.as_deref(), Some("u/test-user")); + let body: serde_json::Value = resp.json().await?; assert!(body["conflicts"].as_array().map_or(true, |a| a.is_empty())); assert!(body["summary"].is_object()); @@ -117,7 +144,10 @@ async fn test_offboard_to_user(db: Pool) -> anyhow::Result<()> { .fetch_one(&db) .await?; assert_eq!( - (obo.on_behalf_of.as_deref(), obo.on_behalf_of_email.as_deref()), + ( + obo.on_behalf_of.as_deref(), + obo.on_behalf_of_email.as_deref() + ), (Some("u/test-user"), Some("test@windmill.dev")), "the reassignment moves the whole identity, not just the half this release reads" ); diff --git a/backend/windmill-api-integration-tests/tests/operator_builder_apps.rs b/backend/windmill-api-integration-tests/tests/operator_builder_apps.rs new file mode 100644 index 0000000000..7033d093f2 --- /dev/null +++ b/backend/windmill-api-integration-tests/tests/operator_builder_apps.rs @@ -0,0 +1,570 @@ +use serde_json::json; +use serial_test::serial; +use sqlx::{Pool, Postgres}; +use windmill_common::workspaces::invalidate_operator_rights_cache; +use windmill_test_utils::*; + +/// Every test here must be `#[serial]`: the rights cache is process-global and keyed by workspace id +/// alone, so parallel tests under this same id read each other's rights. +const WS: &str = "test-workspace"; + +fn client(token: &str) -> reqwest::Client { + let mut headers = reqwest::header::HeaderMap::new(); + headers.insert( + reqwest::header::AUTHORIZATION, + reqwest::header::HeaderValue::from_str(&format!("Bearer {token}")).unwrap(), + ); + reqwest::ClientBuilder::new() + .default_headers(headers) + .build() + .unwrap() +} + +async fn set_builder(db: &Pool, flows: bool, apps: bool) -> anyhow::Result<()> { + sqlx::query( + "UPDATE workspace_settings SET operator_settings = $1::text::jsonb WHERE workspace_id = $2", + ) + .bind(format!( + r#"{{"builder_flows": {flows}, "builder_apps": {apps}}}"# + )) + .bind(WS) + .execute(db) + .await?; + // The rights are read through a process-global 60s cache keyed by workspace id. + invalidate_operator_rights_cache(WS); + Ok(()) +} + +async fn add_script(db: &Pool, hash: i64, path: &str, owner: &str) -> anyhow::Result<()> { + sqlx::query( + "INSERT INTO script (workspace_id, hash, path, content, language, kind, created_by, schema, + summary, description, lock, extra_perms) + VALUES ($1, $2, $3, 'x', 'bun', 'script', $4, '{}', '', '', '', '{}')", + ) + .bind(WS) + .bind(hash) + .bind(path) + .bind(owner) + .execute(db) + .await?; + Ok(()) +} + +/// A full-code app is deployed multipart, the way the editor and the CLI use it. +fn raw_app_form(app: serde_json::Value) -> reqwest::multipart::Form { + reqwest::multipart::Form::new() + .part( + "app", + reqwest::multipart::Part::text(app.to_string()) + .mime_str("application/json") + .unwrap(), + ) + .part( + "js", + reqwest::multipart::Part::text("console.log(1)").file_name("app.js"), + ) +} + +fn raw_app(path: &str, mode: &str, runnable_path: &str) -> reqwest::multipart::Form { + raw_app_form(json!({ + "path": path, + "summary": "", + "value": {"files": {}, "runnables": {"r": { + "name": "r", "type": "runnableByPath", "runType": "script", + "path": runnable_path + }}}, + "policy": {"execution_mode": mode, "triggerables_v2": {}} + })) +} + +fn composition_flow(path: &str) -> serde_json::Value { + json!({ + "path": path, "summary": "", "description": "", "schema": {}, + "value": {"modules": [{ + "id": "a", + "value": {"type": "script", "path": "u/operator/some_script", "input_transforms": {}} + }]} + }) +} + +/// The app half of the builder boundary, plus the proof that the two rights are independent: a +/// gate reading "either" would authorize the kind its workspace never granted, which is the whole +/// point of splitting them. +#[sqlx::test(migrations = "../migrations", fixtures("base", "permissions_test"))] +#[serial] +async fn test_operator_builder_apps_boundary(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let api = format!("http://localhost:{port}/api/w/{WS}"); + let c = client("OPERATOR_TOKEN_1"); + + add_script(&db, 4241, "u/operator/some_script", "operator").await?; + // `permissions_test` gives the operator fixture no rights on `u/alice/**`. + add_script(&db, 4243, "u/alice/private", "alice").await?; + // A version shared with the operator, then archived, and a newer one at the same path that is + // not: the newer one is what runs. + add_script(&db, 4244, "u/alice/reused", "alice").await?; + sqlx::query( + "UPDATE script SET archived = true, extra_perms = '{\"u/operator\": false}', + created_at = now() - interval '1 day' WHERE hash = 4244", + ) + .execute(&db) + .await?; + add_script(&db, 4245, "u/alice/reused", "alice").await?; + + set_builder(&db, false, false).await?; + let resp = c + .post(format!("{api}/apps/create_raw")) + .multipart(raw_app( + "u/operator/a0", + "publisher", + "u/operator/some_script", + )) + .send() + .await?; + assert!( + !resp.status().is_success(), + "an operator without the builder right must not create a full-code app" + ); + + set_builder(&db, true, true).await?; + + // `*_raw_source` compiles caller-supplied sources with a bundler job on a worker. It sits + // beside `create_app_raw`, which builders MAY use, so it is the gate most likely to be opened + // by mistake later. + let resp = c + .post(format!("{api}/apps/create_raw_source")) + .json(&json!({ + "path": "u/operator/a1", "summary": "", + "value": {"files": {"index.ts": "console.log(1)"}, "runnables": {}}, + "policy": {"execution_mode": "publisher"} + })) + .send() + .await?; + assert!( + !resp.status().is_success(), + "a builder must not compile app sources on a worker" + ); + + // Low-code apps carry inline scripts, so they stay shut too. + let resp = c + .post(format!("{api}/apps/create")) + .json(&json!({ + "path": "u/operator/a2", "summary": "", + "value": {"grid": []}, "policy": {"execution_mode": "publisher"} + })) + .send() + .await?; + assert!( + !resp.status().is_success(), + "a builder must not create a low-code app" + ); + + let resp = c + .post(format!("{api}/apps/create_raw")) + .multipart(raw_app("u/operator/a3", "publisher", "u/alice/private")) + .send() + .await?; + assert!( + !resp.status().is_success(), + "a builder must not deploy an app referencing a runnable it cannot read" + ); + + let resp = c + .post(format!("{api}/apps/create_raw")) + .multipart(raw_app("u/operator/a4", "viewer", "u/operator/some_script")) + .send() + .await?; + assert!( + !resp.status().is_success(), + "a builder must not deploy a viewer-mode app: the policy stops bounding what it can invoke" + ); + + // Storage strips a NUL, turning this key into `inlineScript`. + let resp = c + .post(format!("{api}/apps/create_raw")) + .multipart(raw_app_form(json!({ + "path": "u/operator/a_nul", "summary": "", + "value": {"files": {}, "runnables": {"r": { + "type": "inline", + "inline\u{0}Script": {"content": "x", "language": "bun"} + }}}, + "policy": {"execution_mode": "publisher", "triggerables_v2": {}} + }))) + .send() + .await?; + assert_eq!( + resp.status(), + 403, + "a NUL in a key must not hide an inline script: {}", + resp.text().await? + ); + + let resp = c + .post(format!("{api}/apps/create_raw")) + .multipart(raw_app( + "u/operator/a5", + "publisher", + "u/operator/some_script", + )) + .send() + .await?; + assert!( + resp.status().is_success(), + "a builder must be able to deploy a full-code app over readable runnables: {}", + resp.text().await? + ); + let sandbox: Option = sqlx::query_scalar( + "SELECT (policy->>'sandbox')::boolean FROM app WHERE workspace_id = $1 AND path = $2", + ) + .bind(WS) + .bind("u/operator/a5") + .fetch_one(&db) + .await?; + assert_eq!( + sandbox, + Some(true), + "a builder-authored app must be stored sandboxed" + ); + + // `execute_component` looks up `:` with an unrestricted component string, so + // a key with a second colon still resolves at run time and must not slip past validation. + let resp = c + .post(format!("{api}/apps/create_raw")) + .multipart(raw_app_form(json!({ + "path": "u/operator/a6", "summary": "", + "value": {"files": {}, "runnables": {}}, + "policy": {"execution_mode": "publisher", "triggerables_v2": { + "x:y:script/u/alice/private": {"static_inputs": {}, "one_of_inputs": {}} + }} + }))) + .send() + .await?; + assert!( + !resp.status().is_success(), + "a multi-colon triggerable key must not hide an unreadable runnable from validation" + ); + + // The two rights are independent. + set_builder(&db, true, false).await?; + let resp = c + .post(format!("{api}/flows/create")) + .json(&composition_flow("u/operator/flows_only")) + .send() + .await?; + assert!( + resp.status().is_success(), + "flows-only must still create a flow: {}", + resp.text().await? + ); + let resp = c + .post(format!("{api}/apps/create_raw")) + .multipart(raw_app( + "u/operator/flows_only_app", + "publisher", + "u/operator/some_script", + )) + .send() + .await?; + assert!( + !resp.status().is_success(), + "flows-only must not deploy a full-code app" + ); + + set_builder(&db, false, true).await?; + let resp = c + .post(format!("{api}/flows/create")) + .json(&composition_flow("u/operator/apps_only")) + .send() + .await?; + assert!( + !resp.status().is_success(), + "apps-only must not create a flow" + ); + let resp = c + .post(format!("{api}/apps/create_raw")) + .multipart(raw_app( + "u/operator/apps_only_app", + "publisher", + "u/operator/some_script", + )) + .send() + .await?; + assert!( + resp.status().is_success(), + "apps-only must still deploy a full-code app: {}", + resp.text().await? + ); + + // The deploy panel saves access and frontend scopes through the settings-only endpoint. + for (body, expected) in [ + ( + json!({"policy": {"execution_mode": "anonymous", "triggerables_v2": {}}}), + 200, + ), + ( + json!({"policy": {"execution_mode": "publisher", "sandbox": false, "triggerables_v2": {}}}), + 403, + ), + ( + json!({"value": {"files": {}, "runnables": {}}, "policy": {"execution_mode": "publisher"}}), + 403, + ), + ] { + let resp = c + .post(format!("{api}/apps/update/u/operator/apps_only_app")) + .json(&body) + .send() + .await?; + let status = resp.status(); + assert_eq!( + status, + expected, + "settings update {body}: {}", + resp.text().await? + ); + } + let sandbox: Option = sqlx::query_scalar( + "SELECT (policy->>'sandbox')::boolean FROM app WHERE workspace_id = $1 AND path = $2", + ) + .bind(WS) + .bind("u/operator/apps_only_app") + .fetch_one(&db) + .await?; + assert_eq!( + sandbox, + Some(true), + "a settings update must not turn a builder app's sandbox off" + ); + + // The editor runs the runnables a draft names as whoever opens it, and its frontend code + // with their session unless the preview is sandboxed. + for (runnables, policy, expected) in [ + (json!({}), json!({"sandbox": true}), 200), + ( + json!({"a": {"type": "inline", "inlineScript": {"content": "x", "language": "bun"}}}), + json!({"sandbox": true}), + 403, + ), + (json!({}), json!({"sandbox": false}), 403), + ( + json!({}), + json!({"sandbox": true, "execution_mode": "viewer"}), + 403, + ), + (json!({}), json!(null), 403), + ( + json!({}), + json!({"sandbox": true, "on_behalf_of": "u/alice", "on_behalf_of_email": "alice@windmill.dev"}), + 403, + ), + ( + json!({}), + json!({"sandbox": true, "on_behalf_of": "u/operator"}), + 200, + ), + ( + json!({}), + json!({"sandbox": true, "triggerables": { + format!("{}script/u/operator/some_script", "a:".repeat(300)): {} + }}), + 400, + ), + ( + json!({"r": {"type": "runnableByPath", "runType": "script", "path": "u/operator/some_script"}}), + json!({"sandbox": true}), + 200, + ), + ( + json!({"r": {"type": "runnableByPath", "runType": "script", "path": "u/alice/private"}}), + json!({"sandbox": true}), + 403, + ), + ( + json!({"r": {"type": "runnableByPath", "runType": "script", "path": "u/alice/reused"}}), + json!({"sandbox": true}), + 403, + ), + ( + json!({"r": {"type": "path", "runType": "hubscript", "path": "hub/1/x/y"}}), + json!({"sandbox": true}), + 403, + ), + ( + json!({"r": {"type": "path", "runType": "script/u/alice", "path": "u/operator/some_script"}}), + json!({"sandbox": true}), + 400, + ), + ( + json!({"r": {"type": "path", "runType": "script", "path": ["u/alice/private"]}}), + json!({"sandbox": true}), + 400, + ), + ( + json!({"r": {"type": ["path"], "runType": "script", "path": "u/alice/private"}}), + json!({"sandbox": true}), + 400, + ), + ( + json!([{"type": "path", "runType": "script", "path": "u/alice/private"}]), + json!({"sandbox": true}), + 400, + ), + ( + json!({"r": {"type": "path", "runType": "script", "path": "u/operator/some_script", + "fields": {"x": {"type": "static", "value": {"type": "path", "path": "/srv/out"}}}}}), + json!({"sandbox": true}), + 200, + ), + ( + json!({}), + json!({"sandbox": true, "triggerables": {"x:rawscript/abc": {}}}), + 403, + ), + ( + json!({}), + json!({"sandbox": true, "triggerables": {"x:script/u/alice/private": {}}}), + 403, + ), + ( + json!({}), + json!({"sandbox": true, "triggerables_v2": { + "x:script/u/alice/private": {"static_inputs": {}, "one_of_inputs": {}}, + "y:rawscript/abc": {"static_inputs": {}, "one_of_inputs": {}} + }}), + 200, + ), + ] { + let resp = c + .post(format!("{api}/drafts/update/raw_app/u/operator/d1")) + .json(&json!({ + "value": {"files": {}, "runnables": runnables, "summary": "", "policy": policy}, + "force": true + })) + .send() + .await?; + let status = resp.status(); + assert_eq!( + status, + expected, + "raw app draft {runnables} {policy}: {}", + resp.text().await? + ); + } + + // The component preview runs a deployed runnable for a builder; inline code and hub + // scripts are unreviewed code. + for (preview, expected) in [ + (json!({"path": "script/u/operator/some_script"}), 200), + (json!({"path": "script/hub/1/x/y"}), 403), + ( + json!({"raw_code": {"content": "x", "language": "bun"}}), + 403, + ), + ] { + let mut body = json!({"component": "c", "args": {}, "force_viewer_static_fields": {}}); + body.as_object_mut() + .unwrap() + .extend(preview.as_object().unwrap().clone()); + let resp = c + .post(format!( + "{api}/apps_u/execute_component/u/operator/apps_only_app" + )) + .json(&body) + .send() + .await?; + let status = resp.status(); + assert_eq!( + status, + expected, + "component preview {preview}: {}", + resp.text().await? + ); + } + + // Delete and redeploy each serve both kinds; builder rights cover only full-code apps. + let resp = client("SECRET_TOKEN") + .post(format!("{api}/apps/create")) + .json(&json!({ + "path": "u/operator/low_code", "summary": "", + "value": {"grid": []}, "policy": {"execution_mode": "publisher"} + })) + .send() + .await?; + assert!(resp.status().is_success(), "{}", resp.text().await?); + let resp = c + .post(format!("{api}/apps/update_raw/u/operator/low_code")) + .multipart(raw_app_form(json!({ + "policy": {"execution_mode": "publisher", "triggerables_v2": {}} + }))) + .send() + .await?; + assert_eq!( + resp.status(), + 403, + "policy-only update of a low-code app: {}", + resp.text().await? + ); + // Deployment history restores a full-code version with allow_kind_change set. + let resp = c + .post(format!("{api}/apps/update_raw/u/operator/apps_only_app")) + .multipart(raw_app_form(json!({ + "value": {"files": {}, "runnables": {}}, + "policy": {"execution_mode": "publisher", "triggerables_v2": {}}, + "allow_kind_change": true + }))) + .send() + .await?; + assert_eq!( + resp.status(), + 200, + "restore of a full-code version: {}", + resp.text().await? + ); + for (path, expected) in [("low_code", 403), ("apps_only_app", 200)] { + let resp = c + .delete(format!("{api}/apps/delete/u/operator/{path}")) + .send() + .await?; + let status = resp.status(); + assert_eq!(status, expected, "delete {path}: {}", resp.text().await?); + } + + Ok(()) +} + +/// The readability check must not hold its RLS transaction while it takes a second connection, +/// or a one-connection pool (`DATABASE_CONNECTIONS=1`) stalls every builder draft naming a script. +#[sqlx::test(migrations = "../migrations", fixtures("base", "permissions_test"))] +#[serial] +async fn test_operator_builder_app_check_fits_one_connection( + pool_opts: sqlx::postgres::PgPoolOptions, + connect_opts: sqlx::postgres::PgConnectOptions, +) -> anyhow::Result<()> { + initialize_tracing().await; + let db = pool_opts + .max_connections(1) + .acquire_timeout(std::time::Duration::from_secs(5)) + .connect_with(connect_opts) + .await?; + let server = ApiServer::start(db.clone()).await?; + let api = format!("http://localhost:{}/api/w/{WS}", server.addr.port()); + add_script(&db, 4241, "u/operator/some_script", "operator").await?; + set_builder(&db, false, true).await?; + + let resp = client("OPERATOR_TOKEN_1") + .post(format!("{api}/drafts/update/raw_app/u/operator/d1")) + .json(&json!({ + "value": {"files": {}, "summary": "", "runnables": {"r": { + "name": "r", "type": "runnableByPath", "runType": "script", + "path": "u/operator/some_script" + }}, "policy": {"sandbox": true, "triggerables_v2": {}}}, + "force": true + })) + .send() + .await?; + let status = resp.status(); + assert_eq!(status, 200, "{}", resp.text().await?); + Ok(()) +} diff --git a/backend/windmill-api-integration-tests/tests/operator_manage_rights.rs b/backend/windmill-api-integration-tests/tests/operator_manage_rights.rs index ae1979f2fb..22901d1c87 100644 --- a/backend/windmill-api-integration-tests/tests/operator_manage_rights.rs +++ b/backend/windmill-api-integration-tests/tests/operator_manage_rights.rs @@ -4,10 +4,10 @@ use sqlx::{Pool, Postgres}; use windmill_common::workspaces::invalidate_operator_rights_cache; use windmill_test_utils::*; -/// Every test here must be `#[serial]`. The rights cache is process-global and keyed by workspace -/// id alone, while `sqlx::test` gives each test its own database under this same id — so two -/// running at once can answer each other's reads from one cached entry, and a withdrawal in one -/// database reads as granted in the other. +/// Every test here must be `#[serial]`, and start by dropping the cache entry. The rights cache is +/// process-global and keyed by workspace id alone, while `sqlx::test` gives each test its own +/// database under this same id — so two running at once can answer each other's reads from one +/// cached entry, and a withdrawal a test ends on reads as withdrawn in the next one's database. const WS: &str = "test-workspace"; fn operator_client() -> reqwest::Client { @@ -53,6 +53,7 @@ async fn set_settings(api: &str, body: serde_json::Value) -> anyhow::Result #[serial] async fn test_operator_manage_rights(db: Pool) -> anyhow::Result<()> { initialize_tracing().await; + invalidate_operator_rights_cache(WS); let server = ApiServer::start(db.clone()).await?; let port = server.addr.port(); let api = format!("http://localhost:{port}/api/w/{WS}"); @@ -145,6 +146,7 @@ async fn test_manage_triggers_covers_a_route_outside_the_shared_handler( db: Pool, ) -> anyhow::Result<()> { initialize_tracing().await; + invalidate_operator_rights_cache(WS); let server = ApiServer::start(db.clone()).await?; let port = server.addr.port(); let api = format!("http://localhost:{port}/api/w/{WS}"); @@ -213,3 +215,193 @@ async fn test_manage_triggers_covers_a_route_outside_the_shared_handler( Ok(()) } + +/// A draft is what the AI chat writes before it deploys, so an operator holding a manage right +/// may draft that kind, and only while they hold it. Builder rights are left off throughout: they +/// open flow drafts, and would otherwise be what admits these. +#[sqlx::test(migrations = "../migrations", fixtures("base", "permissions_test"))] +#[serial] +async fn test_manage_rights_admit_matching_drafts(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + invalidate_operator_rights_cache(WS); + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let api = format!("http://localhost:{port}/api/w/{WS}"); + let c = operator_client(); + + let save = async |kind: &str, path: &str| -> anyhow::Result<(u16, String)> { + let resp = c + .post(format!("{api}/drafts/update/{kind}/{path}")) + .json(&json!({ "value": { "path": path } })) + .send() + .await?; + Ok((resp.status().as_u16(), resp.text().await?)) + }; + let listed = async || -> anyhow::Result { + let resp = c.get(format!("{api}/drafts/list")).send().await?; + assert_eq!(resp.status(), 200); + Ok(resp.json().await?) + }; + let schedule_list_has_draft = async || -> anyhow::Result { + let resp = c + .get(format!("{api}/schedules/list?include_draft_only=true")) + .send() + .await?; + assert_eq!(resp.status(), 200); + let rows: Vec = resp.json().await?; + Ok(rows.iter().any(|r| r["path"] == "u/operator/sched_draft")) + }; + + let resp = c + .post(format!("{api}/drafts/update/trigger_schedule/u/operator/sched_draft")) + .json(&json!({ "value": { + "path": "u/operator/sched_draft", + "schedule": "0 0 12 * * *", + "timezone": "UTC", + "script_path": "f/system/hello", + "is_flow": false, + "args": {}, + "enabled": false + } })) + .send() + .await?; + assert_eq!(resp.status(), 200, "{}", resp.text().await?); + assert!(schedule_list_has_draft().await?); + let (status, body) = save("trigger_http", "u/operator/http_draft").await?; + assert_eq!(status, 200, "{body}"); + // The rights name schedules and triggers, nothing else. + let (status, body) = save("script", "u/operator/script_draft").await?; + assert_eq!(status, 403, "{body}"); + + let drafts = listed().await?; + assert_eq!(drafts.as_array().map(Vec::len), Some(2), "{drafts}"); + + assert_eq!( + set_settings(&api, json!({"manage_schedules": false})).await?, + 200 + ); + let (status, body) = save("trigger_schedule", "u/operator/sched_draft").await?; + assert_eq!(status, 403, "{body}"); + // The list follows the right too, as the app list follows `builder_apps`. + assert!(!schedule_list_has_draft().await?); + let (status, body) = save("trigger_http", "u/operator/http_draft").await?; + assert_eq!(status, 200, "{body}"); + + assert_eq!( + set_settings(&api, json!({"manage_triggers": false})).await?, + 200 + ); + let (status, body) = save("trigger_http", "u/operator/http_draft").await?; + assert_eq!(status, 403, "{body}"); + // Still listed, as their own, but no longer writable. + let drafts = listed().await?; + assert_eq!(drafts.as_array().map(Vec::len), Some(2), "{drafts}"); + assert!( + drafts + .as_array() + .unwrap() + .iter() + .all(|d| d["can_write"] == json!(false)), + "{drafts}" + ); + + Ok(()) +} + +/// Operators create resources and variables on their pages with no operator setting in the way, +/// so they may draft them in any workspace — even one that withdrew every manage right — and +/// deploying a secret variable draft goes through the create route like a direct write. +#[sqlx::test(migrations = "../migrations", fixtures("base", "permissions_test"))] +#[serial] +async fn test_operators_draft_resources_and_variables(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + invalidate_operator_rights_cache(WS); + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let api = format!("http://localhost:{port}/api/w/{WS}"); + let c = operator_client(); + + assert_eq!( + set_settings( + &api, + json!({"manage_schedules": false, "manage_triggers": false}) + ) + .await?, + 200 + ); + + let save = async |kind: &str, path: &str, value: serde_json::Value| { + let resp = c + .post(format!("{api}/drafts/update/{kind}/{path}")) + .json(&json!({ "value": value })) + .send() + .await?; + anyhow::Ok((resp.status().as_u16(), resp.text().await?)) + }; + + let (status, body) = save( + "resource", + "u/operator/res_draft", + json!({ "path": "u/operator/res_draft", "args": {}, "resource_type": "object" }), + ) + .await?; + assert_eq!(status, 200, "{body}"); + let (status, body) = save( + "variable", + "u/operator/secret_draft", + json!({ "path": "u/operator/secret_draft", "variable": { "value": "hunter2", "is_secret": true } }), + ) + .await?; + assert_eq!(status, 200, "{body}"); + let (status, body) = save("script", "u/operator/script_draft", json!({})).await?; + assert_eq!(status, 403, "{body}"); + + // The Resources and Variables pages list a draft that has never been deployed. + for (route, path) in [ + ("resources", "u/operator/res_draft"), + ("variables", "u/operator/secret_draft"), + ] { + let listed: serde_json::Value = c + .get(format!("{api}/{route}/list?include_draft_only=true")) + .send() + .await? + .json() + .await?; + assert!( + listed + .as_array() + .unwrap() + .iter() + .any(|r| r["path"] == path && r["draft_only"] == json!(true)), + "{route}: {listed}" + ); + } + + // Deploying a draft sends its stored value, the `$encrypted:` marker, to the create route. + let stored: String = sqlx::query_scalar( + "SELECT value::jsonb->'variable'->>'value' FROM draft + WHERE workspace_id = $1 AND path = 'u/operator/secret_draft'", + ) + .bind(WS) + .fetch_one(&db) + .await?; + assert!(stored.starts_with("$encrypted:"), "{stored}"); + let resp = c + .post(format!("{api}/variables/create")) + .json(&json!({ + "path": "u/operator/secret_draft", + "value": stored, + "is_secret": true, + "description": "", + })) + .send() + .await?; + assert_eq!(resp.status(), 201, "{}", resp.text().await?); + let resp = c + .get(format!("{api}/variables/get_value/u/operator/secret_draft")) + .send() + .await?; + assert_eq!(resp.json::().await?, "hunter2"); + + Ok(()) +} diff --git a/backend/windmill-api-integration-tests/tests/preview_on_behalf_of.rs b/backend/windmill-api-integration-tests/tests/preview_on_behalf_of.rs new file mode 100644 index 0000000000..a1bb7876c6 --- /dev/null +++ b/backend/windmill-api-integration-tests/tests/preview_on_behalf_of.rs @@ -0,0 +1,135 @@ +//! A preview's `on_behalf_of` runs request-supplied code as another account, so it must +//! change the job's identity for admins and be refused for everyone else. + +use serde_json::json; +use sqlx::{Pool, Postgres}; +use uuid::Uuid; +use windmill_common::auth::create_jwt_token; +use windmill_common::db::Authed; +use windmill_test_utils::*; + +/// `route` is under `/api/w/test-workspace/`. +async fn post(port: u16, token: &str, route: &str, body: serde_json::Value) -> (u16, String) { + let resp = reqwest::Client::new() + .post(format!("http://localhost:{port}/api/w/test-workspace/{route}")) + .header("Authorization", format!("Bearer {token}")) + .json(&body) + .send() + .await + .unwrap(); + (resp.status().as_u16(), resp.text().await.unwrap()) +} + +async fn identity(db: &Pool, id: &str) -> (String, String) { + sqlx::query_as("SELECT permissioned_as, permissioned_as_email FROM v2_job WHERE id = $1") + .bind(Uuid::parse_str(id).unwrap()) + .fetch_one(db) + .await + .unwrap() +} + +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_preview_on_behalf_of(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + let script = |obo: &str| { + json!({ + "content": "export function main() { return 1; }", + "language": "deno", + "args": {}, + "on_behalf_of": obo, + }) + }; + let flow = |obo: &str| json!({ "value": {"modules": []}, "args": {}, "on_behalf_of": obo }); + // The app editor's preview of an inline runnable. + let app = |obo: &str| { + json!({ + "args": {}, + "component": "c", + "raw_code": { "language": "deno", "content": "export function main() { return 1; }" }, + "force_viewer_static_fields": {}, + "on_behalf_of": obo, + }) + }; + let app_route = "apps_u/execute_component/u/test-user/app"; + + for (route, body) in [ + ("jobs/run/preview", script("test2@windmill.dev")), + ("jobs/run/preview_flow", flow("u/test-user-2")), + (app_route, app("u/test-user-2")), + ] { + let (status, id) = post(port, "SECRET_TOKEN", route, body).await; + assert!((200..300).contains(&status), "{route}: {status} {id}"); + assert_eq!( + identity(&db, &id).await, + ( + "u/test-user-2".to_string(), + "test2@windmill.dev".to_string() + ), + "{route}" + ); + let logs: String = sqlx::query_scalar("SELECT logs FROM job_logs WHERE job_id = $1") + .bind(Uuid::parse_str(&id).unwrap()) + .fetch_one(&db) + .await?; + assert!( + logs.starts_with("Preview run on behalf of u/test-user-2 (test2@windmill.dev), requested by test@windmill.dev"), + "{route}: {logs}" + ); + } + + for (route, body) in [ + ("jobs/run/preview", script("test@windmill.dev")), + ("jobs/run/preview_flow", flow("u/test-user")), + (app_route, app("u/test-user")), + ] { + let (status, body) = post(port, "SECRET_TOKEN_2", route, body).await; + assert_eq!(status, 403, "{route}: {body}"); + } + + let (status, id) = post(port, "SECRET_TOKEN_2", "jobs/run/preview", script("u/test-user-2")).await; + assert_eq!(status, 201, "{id}"); + assert_eq!(identity(&db, &id).await.0, "u/test-user-2"); + + // Reading data as the end user is the direct caller's own choice. A job token's end user is + // whoever ran that job, so a job's code must not be able to ask for it. + set_jwt_secret().await; + let job_token = create_jwt_token( + Authed { + email: "test@windmill.dev".to_string(), + username: "test-user".to_string(), + is_admin: true, + is_operator: false, + groups: vec![], + folders: vec![], + scopes: None, + token_prefix: None, + }, + "test-workspace", + 3600, + Some(Uuid::new_v4()), + Some("ephemeral-script".to_string()), + None, + None, + ) + .await?; + let viewer_data = json!({ + "content": "export function main() { return 1; }", + "language": "deno", + "args": {}, + "viewer_data_access": true, + }); + for (token, expected) in [("SECRET_TOKEN", true), (job_token.as_str(), false)] { + let (status, id) = post(port, token, "jobs/run/preview", viewer_data.clone()).await; + assert_eq!(status, 201, "{id}"); + let stamped: bool = + sqlx::query_scalar("SELECT viewer_data_access FROM job_perms WHERE job_id = $1") + .bind(Uuid::parse_str(&id).unwrap()) + .fetch_one(&db) + .await?; + assert_eq!(stamped, expected, "job token: {}", !expected); + } + + Ok(()) +} diff --git a/backend/windmill-api-integration-tests/tests/resources.rs b/backend/windmill-api-integration-tests/tests/resources.rs index 9c167ef70c..ebca295339 100644 --- a/backend/windmill-api-integration-tests/tests/resources.rs +++ b/backend/windmill-api-integration-tests/tests/resources.rs @@ -648,6 +648,15 @@ async fn test_interpolated_references_need_the_token_scopes( read_probe(json!({"v": "$var:u/test-user/secret"}), with_var.clone()).await; assert_eq!((status, body.as_str()), (200, r#"{"v":"CANARY"}"#)); + // A wildcard resource pattern extends to the variables it matches, and only to those. + let wildcard = mint(json!(["resources:read:u/test-user/*"])).await; + let (status, body) = + read_probe(json!({"v": "$var:u/test-user/secret"}), wildcard.clone()).await; + assert_eq!((status, body.as_str()), (200, r#"{"v":"CANARY"}"#)); + let elsewhere = mint(json!(["resources:read:u/test-user/probe,f/other/*"])).await; + let (status, body) = read_probe(json!({"v": "$var:u/test-user/secret"}), elsewhere).await; + assert_eq!(status, 403, "{body}"); + // The resource's own linked secrets (at its path, or `_`) are part of it. for (path, value) in [ ("u/test-user/probe", "LINKED"), @@ -751,6 +760,65 @@ async fn test_resource_cache_handles_job_context(db: Pool) -> anyhow:: Ok(()) } +/// Without an embeddings index the resource type search reads the table, so it has to apply the +/// same scope as the index: the workspace's own types and the global ones in `admins`, never +/// another workspace's. +#[sqlx::test(migrations = "../migrations", fixtures("base"))] +async fn test_resource_type_search_without_embeddings(db: Pool) -> anyhow::Result<()> { + initialize_tracing().await; + let server = ApiServer::start(db.clone()).await?; + let port = server.addr.port(); + + sqlx::query("INSERT INTO workspace (id, name, owner) VALUES ('other-workspace', 'other-workspace', 'test-user')") + .execute(&db) + .await?; + for (workspace, name, description) in [ + ( + "test-workspace", + "c_acme_billing", + "Acme internal billing API", + ), + ( + "other-workspace", + "c_other_billing", + "Another workspace's billing API", + ), + ] { + sqlx::query( + "INSERT INTO resource_type (workspace_id, name, schema, description, created_by) VALUES ($1, $2, '{}'::jsonb, $3, 'test-user')", + ) + .bind(workspace) + .bind(name) + .bind(description) + .execute(&db) + .await?; + } + + let search = |text: &str| { + let url = format!( + "http://localhost:{port}/api/w/test-workspace/embeddings/query_resource_types?text={text}" + ); + async move { + let resp = authed(client().get(url)).send().await.unwrap(); + assert_eq!(resp.status(), 200); + resp.json::>() + .await + .unwrap() + .into_iter() + .map(|rt| rt["name"].as_str().unwrap().to_string()) + .collect::>() + } + }; + + let billing = search("billing").await; + assert_eq!(billing.first().map(String::as_str), Some("c_acme_billing")); + assert!(!billing.contains(&"c_other_billing".to_string())); + // `ai_skill` is seeded in `admins` by the migrations. + assert!(search("skill").await.contains(&"ai_skill".to_string())); + + Ok(()) +} + #[cfg(feature = "mcp")] #[sqlx::test(migrations = "../migrations", fixtures("base", "resources_test"))] async fn test_mcp_tools(db: Pool) -> anyhow::Result<()> { diff --git a/backend/windmill-api-jobs/Cargo.toml b/backend/windmill-api-jobs/Cargo.toml index dad6469947..ca4153ac44 100644 --- a/backend/windmill-api-jobs/Cargo.toml +++ b/backend/windmill-api-jobs/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_api_jobs" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-api-jobs/src/execution.rs b/backend/windmill-api-jobs/src/execution.rs index ce6cfc185d..da77acbf7c 100644 --- a/backend/windmill-api-jobs/src/execution.rs +++ b/backend/windmill-api-jobs/src/execution.rs @@ -245,6 +245,43 @@ pub async fn unclaimable_run_lineage( Ok(referenced) } +/// `WM_END_USER_EMAIL` of a run started through a `/jobs/run*` route. `WM_EMAIL` names the +/// runnable's `on_behalf_of` identity when it has one, so this is the only place the caller's +/// address reaches the job. A job's own `WM_TOKEN` passes on the end user of that job, and a run +/// a trigger fired has no end user. +pub async fn run_end_user_email( + db: &DB, + w_id: &str, + authed: &ApiAuthed, + trigger: Option<&TriggerMetadata>, +) -> error::Result> { + if trigger.is_some() { + return Ok(None); + } + match authed.job_id { + Some(job_id) => Ok(windmill_common::auth::get_job_perms(db, &job_id, w_id) + .await? + .and_then(|p| p.end_user_email)), + None => Ok(Some(authed.email.clone())), + } +} + +/// [`run_end_user_email`] of an inline run of the caller's own code, and whether its data table +/// connections are made as that end user: they are when the calling job's are, since the code is +/// that job's own. +pub async fn run_inline_preview_end_user( + db: &DB, + w_id: &str, + authed: &ApiAuthed, +) -> error::Result<(Option, bool)> { + match authed.job_id { + Some(job_id) => Ok(windmill_common::auth::get_job_perms(db, &job_id, w_id) + .await? + .map_or((None, false), |p| (p.end_user_email, p.viewer_data_access))), + None => Ok((Some(authed.email.clone()), false)), + } +} + #[cfg(feature = "enterprise")] pub async fn check_license_key_valid() -> error::Result<()> { use windmill_common::ee_oss::LICENSE_KEY_VALID; @@ -909,6 +946,7 @@ pub async fn handle_chat_conversation_messages( w_id, flow_path, &authed.username, + authed.is_admin, &user_message, memory_id, is_test, @@ -1013,6 +1051,7 @@ pub async fn run_flow<'c>( ) }; + let end_user_email = run_end_user_email(db, w_id, authed, trigger.as_ref()).await?; let scope_ceiling = windmill_api_auth::caller_scope_ceiling(db, authed).await?; let (uuid, mut tx) = push( &db, @@ -1048,7 +1087,7 @@ pub async fn run_flow<'c>( None, push_authed.as_ref(), false, - None, + end_user_email, authed.trigger_or_fallback(trigger), run_query.suspended_mode, scope_ceiling.as_deref(), @@ -1244,6 +1283,7 @@ pub async fn push_script_job_by_path_into_queue<'c>( ) }; + let end_user_email = run_end_user_email(&db, &w_id, &authed, trigger.as_ref()).await?; let scope_ceiling = windmill_api_auth::caller_scope_ceiling(&db, &authed).await?; let (uuid, tx) = push( &db, @@ -1277,7 +1317,7 @@ pub async fn push_script_job_by_path_into_queue<'c>( }, push_authed.as_ref(), false, - None, + end_user_email, authed.trigger_or_fallback(trigger), run_query.suspended_mode, scope_ceiling.as_deref(), diff --git a/backend/windmill-api-jobs/src/jobs_export.rs b/backend/windmill-api-jobs/src/jobs_export.rs index b2b69367bc..c426497cf0 100644 --- a/backend/windmill-api-jobs/src/jobs_export.rs +++ b/backend/windmill-api-jobs/src/jobs_export.rs @@ -434,6 +434,7 @@ pub async fn import_completed_jobs( pub async fn import_queued_jobs( authed: ApiAuthed, + Extension(db): Extension, Extension(user_db): Extension, Path(w_id): Path, Json(jobs): Json>, @@ -468,7 +469,9 @@ pub async fn import_queued_jobs( let mut tx = user_db.begin(&authed).await?; - for job in jobs { + for mut job in jobs { + // A fork's admin is whoever created it, so an imported tag is as untrusted as a pushed one. + job.tag = windmill_queue::tags::apply_dev_workspace_suffix(job.tag, &w_id, &db).await?; sqlx::query!( r#" INSERT INTO v2_job ( @@ -622,6 +625,21 @@ pub async fn delete_jobs( let mut tx = user_db.begin(&authed).await?; + // job_ids are request-supplied, and resume_job, v2_job_runtime, v2_job_status, + // concurrency_key and zombie_job_counter have no workspace_id: keep only this workspace's + // jobs, or a workspace admin could erase another workspace's rows by passing its job ids. + // (Side-table list kept in sync with windmill_common::jobs::delete_jobs.) + let job_ids = sqlx::query_scalar!( + "SELECT id FROM v2_job WHERE workspace_id = $1 AND id = ANY($2)", + &w_id, + &job_ids + ) + .fetch_all(&mut *tx) + .await?; + if job_ids.is_empty() { + return Ok("No jobs to delete".to_string()); + } + let logs_deleted = sqlx::query!( "DELETE FROM job_logs WHERE workspace_id = $1 AND job_id = ANY($2)", &w_id, @@ -690,14 +708,8 @@ pub async fn delete_jobs( .await? .rows_affected(); - // job_ids are request-supplied, so scope every side-table delete to the workspace exactly - // like the v2_job delete below — otherwise a workspace admin could erase another - // workspace's side rows by passing foreign job ids. zombie_job_counter and - // flow_conversation_message have no workspace_id, so scope them via v2_job / their conversation. - // (Side-table list kept in sync with windmill_common::jobs::delete_jobs.) let zombie_deleted = sqlx::query!( - "DELETE FROM zombie_job_counter WHERE job_id IN (SELECT id FROM v2_job WHERE workspace_id = $1 AND id = ANY($2))", - &w_id, + "DELETE FROM zombie_job_counter WHERE job_id = ANY($1)", &job_ids ) .execute(&mut *tx) diff --git a/backend/windmill-api-npm-proxy/Cargo.toml b/backend/windmill-api-npm-proxy/Cargo.toml index d6e123abe3..e5d326e660 100644 --- a/backend/windmill-api-npm-proxy/Cargo.toml +++ b/backend/windmill-api-npm-proxy/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_api_npm_proxy" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-api-openapi/Cargo.toml b/backend/windmill-api-openapi/Cargo.toml index 24a6f2aed8..97d11f1f0d 100644 --- a/backend/windmill-api-openapi/Cargo.toml +++ b/backend/windmill-api-openapi/Cargo.toml @@ -7,6 +7,9 @@ edition.workspace = true [lib] name = "windmill_api_openapi" path = "src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [dependencies] windmill-api-auth.workspace = true diff --git a/backend/windmill-api-schedule/Cargo.toml b/backend/windmill-api-schedule/Cargo.toml index 5017985820..f7a612c628 100644 --- a/backend/windmill-api-schedule/Cargo.toml +++ b/backend/windmill-api-schedule/Cargo.toml @@ -7,6 +7,9 @@ edition.workspace = true [lib] name = "windmill_api_schedule" path = "src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [features] default = [] diff --git a/backend/windmill-api-schedule/src/lib.rs b/backend/windmill-api-schedule/src/lib.rs index 855f687431..fb935e0b5c 100644 --- a/backend/windmill-api-schedule/src/lib.rs +++ b/backend/windmill-api-schedule/src/lib.rs @@ -916,7 +916,6 @@ async fn list_schedule( // Append the authed user's draft-only schedules; see scripts.rs. if lsq.include_draft_only.unwrap_or(false) - && !authed.is_operator && offset == 0 && lsq.path.is_none() && lsq.is_flow.is_none() @@ -927,6 +926,13 @@ async fn list_schedule( && lsq.summary.is_none() && lsq.broad_filter.is_none() && lsq.label.is_none() + && (!authed.is_operator + || windmill_common::workspaces::operator_can_draft( + &db, + &w_id, + UserDraftItemKind::TriggerSchedule, + ) + .await?) { let draft_only_rows = fetch_draft_only_list_rows( &db, @@ -1492,7 +1498,8 @@ async fn set_default_error_handler( } else { windmill_api_settings::delete_global_setting(&db, key.as_str()).await?; } - windmill_api_settings::audit_setting_write(&db, &authed, &key, value.as_ref()).await?; + windmill_audit::instance_config::audit_setting_write(&db, &authed, &key, value.as_ref(), None) + .await?; if payload.override_existing { // The rewrite and its history rows go in one transaction: on separate diff --git a/backend/windmill-api-scripts/Cargo.toml b/backend/windmill-api-scripts/Cargo.toml index 72353c6f1b..73bbfd49bb 100644 --- a/backend/windmill-api-scripts/Cargo.toml +++ b/backend/windmill-api-scripts/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_api_scripts" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-api-scripts/src/scripts.rs b/backend/windmill-api-scripts/src/scripts.rs index f622c4bb91..4bbe372254 100644 --- a/backend/windmill-api-scripts/src/scripts.rs +++ b/backend/windmill-api-scripts/src/scripts.rs @@ -900,7 +900,7 @@ async fn is_noop_deploy_against_parent( parent: &Script, resolved_on_behalf_of: Option<&str>, resolved_job_token_scopes: Option<&[String]>, - db: &DB, + tx: &mut Transaction<'_, Postgres>, ) -> Result { if parent.archived || parent.deleted { return Ok(false); @@ -1056,12 +1056,13 @@ async fn is_noop_deploy_against_parent( return Ok(false); } + let parent_settings = windmill_common::runnable_settings::from_handle( + parent.runnable_settings.runnable_settings_handle, + &mut **tx, + ) + .await?; let (parent_debouncing, parent_concurrency) = - windmill_common::runnable_settings::prefetch_cached_from_handle( - parent.runnable_settings.runnable_settings_handle, - db, - ) - .await?; + windmill_common::runnable_settings::prefetch_cached_tx(&parent_settings, tx).await?; if concurrency_settings != &parent_concurrency { return Ok(false); } @@ -1130,6 +1131,69 @@ fn lock_hash_entry(path: &str, lock: &str) -> [(String, i64); 1] { [(path.to_string(), hash_script(lock))] } +/// The principal a deploy would store, and the address written beside it only while a worker +/// that still reads that address may be live. +async fn resolve_deploy_identity( + on_behalf_of_email: Option<&str>, + on_behalf_of: Option<&str>, + preserve: bool, + authed: &ApiAuthed, + w_id: &str, + db: &DB, +) -> Result<(Option, Option)> { + let resolved = windmill_common::resolve_on_behalf_of( + on_behalf_of_email, + on_behalf_of, + preserve, + authed, + w_id, + db, + ) + .await?; + let legacy_email = + windmill_common::legacy_on_behalf_of_email(resolved.as_deref(), w_id, db).await?; + Ok((resolved, legacy_email)) +} + +/// Lineage reads must see versions the caller cannot, yet run on the deploy's own connection, +/// after the row locks that make them sound: lifting RLS for them is what stands in for asking +/// the pool, which while `tx` is held is a hold-and-wait. Every lift must be undone before `tx` +/// is handed on, or the rest of the deploy writes unscoped. +async fn set_lineage_reads_unscoped( + tx: &mut Transaction<'_, Postgres>, + authed: &ApiAuthed, + unscoped: bool, +) -> Result<()> { + // An admin's transaction already runs as `windmill_admin`. + if !authed.is_admin { + let role = if unscoped { + "SET LOCAL ROLE windmill_admin" + } else { + "SET LOCAL ROLE windmill_user" + }; + sqlx::query(role).execute(&mut **tx).await?; + } + Ok(()) +} + +/// The folder's default identity for `path` and what deploying under it would store. +async fn resolve_folder_default_identity( + authed: &ApiAuthed, + w_id: &str, + path: &str, + db: &DB, +) -> Result, Option))>> { + let Some((email, permissioned_as)) = + windmill_common::folders::resolve_folder_default_on_behalf_of(db, w_id, path).await? + else { + return Ok(None); + }; + let identity = + resolve_deploy_identity(Some(&email), Some(&permissioned_as), true, authed, w_id, db) + .await?; + Ok(Some((email, permissioned_as, identity))) +} + /// The `dbt://` relation both halves of a deploy have to agree on: a whole /// `//`, under a warehouse this workspace configures. /// @@ -1341,38 +1405,24 @@ async fn create_script_internal<'c>( let skip_draft_deletion = ns.skip_draft_deletion.unwrap_or(false); let authed = maybe_refresh_folders(&ns.path, &w_id, authed, &db).await; - let mut tx: Transaction<'_, Postgres> = user_db.begin(&authed).await?; - - // Apply folder default_permissioned_as the first time a script is deployed - // at this path. Check inside the transaction to avoid TOCTOU with concurrent deploys. + // Everything read from `db` happens before `tx` opens: `user_db` wraps the same pool, so a + // deploy taking a second connection while holding `tx` lets N concurrent deploys hold the + // whole pool between them and each wait out the acquire timeout for one more. let explicit_preserve = (ns.on_behalf_of_email.is_some() || ns.on_behalf_of.is_some()) && ns.preserve_on_behalf_of.unwrap_or(false) && windmill_common::can_preserve_on_behalf_of(&authed); - if !explicit_preserve && windmill_common::can_preserve_on_behalf_of(&authed) { - let path_already_exists = sqlx::query_scalar!( - "SELECT EXISTS(SELECT 1 FROM script WHERE path = $1 AND workspace_id = $2)", - &ns.path, - &w_id - ) - .fetch_one(&mut *tx) - .await? - .unwrap_or(false); - if !path_already_exists { - if let Some((default_email, default_permissioned_as)) = - windmill_common::folders::resolve_folder_default_on_behalf_of(&db, &w_id, &ns.path) - .await? - { - ns.on_behalf_of_email = Some(default_email); - ns.on_behalf_of = Some(default_permissioned_as); - ns.preserve_on_behalf_of = Some(true); - } - } - } - let authed_principal = windmill_common::users::username_to_permissioned_as(&authed.username); + // Held rather than raised: a rule naming a principal that no longer exists fails here, and + // must fail only a first deploy, which is all the default applies to. + let folder_default = + if !explicit_preserve && windmill_common::can_preserve_on_behalf_of(&authed) { + resolve_folder_default_identity(&authed, &w_id, &ns.path, &db).await + } else { + Ok(None) + }; // Resolved here rather than at the INSERT so the no-op check below compares the identity // that would actually be stored: the parent row holds only the principal, while a // preserving push may name that same principal by address alone. - let resolved_on_behalf_of = windmill_common::resolve_on_behalf_of( + let requested_identity = resolve_deploy_identity( ns.on_behalf_of_email.as_deref(), ns.on_behalf_of.as_deref(), ns.preserve_on_behalf_of.unwrap_or(false), @@ -1381,10 +1431,46 @@ async fn create_script_internal<'c>( &db, ) .await?; - // Written beside the principal only while a worker that still reads it may be live. - let legacy_on_behalf_of_email = - windmill_common::legacy_on_behalf_of_email(resolved_on_behalf_of.as_deref(), &w_id, &db) - .await?; + // Not on `tx`: these inserts are cached as written, which a rolled-back deploy would undo. + let runnable_settings_handle = windmill_common::runnable_settings::insert_rs( + RunnableSettings { + debouncing_settings: ns.debouncing_settings.insert_cached(&db).await?, + concurrency_settings: ns.concurrency_settings.insert_cached(&db).await?, + retry_settings: None, + }, + &db, + ) + .await?; + + let mut tx: Transaction<'_, Postgres> = user_db.begin(&authed).await?; + + // Apply folder default_permissioned_as the first time a script is deployed + // at this path. Check inside the transaction to avoid TOCTOU with concurrent deploys. + let path_already_exists = match folder_default { + Ok(None) => true, + _ => sqlx::query_scalar!( + "SELECT EXISTS(SELECT 1 FROM script WHERE path = $1 AND workspace_id = $2)", + &ns.path, + &w_id + ) + .fetch_one(&mut *tx) + .await? + .unwrap_or(false), + }; + let (resolved_on_behalf_of, legacy_on_behalf_of_email) = if path_already_exists { + requested_identity + } else { + match folder_default? { + Some((default_email, default_permissioned_as, identity)) => { + ns.on_behalf_of_email = Some(default_email); + ns.on_behalf_of = Some(default_permissioned_as); + ns.preserve_on_behalf_of = Some(true); + identity + } + None => requested_identity, + } + }; + let authed_principal = windmill_common::users::username_to_permissioned_as(&authed.username); // When auto_parent is set, serialize concurrent creates for the same (workspace, path) // so the clashing_script query always sees the latest committed head. if ns.auto_parent.unwrap_or(false) { @@ -1467,66 +1553,70 @@ async fn create_script_internal<'c>( // nothing being live there, so a parentless deploy onto a live path still meets the // path conflict the match below raises. let mut parent_adopted_from_retired_path = false; - if ns.parent_hash.is_none() && clashing_script.is_none() { - // Locked, not merely read: a competing deploy chaining onto this same candidate - // takes `FOR UPDATE` on it before inserting, so holding the row is what serializes - // the two. Probe first and the child still uncommitted reads as absent. - let candidate = sqlx::query_scalar::<_, i64>( + // Locked, not merely read: a competing deploy chaining onto this same candidate + // takes `FOR UPDATE` on it before inserting, so holding the row is what serializes + // the two. Probe first and the child still uncommitted reads as absent. + let adoption_candidate = if ns.parent_hash.is_none() && clashing_script.is_none() { + sqlx::query_scalar::<_, i64>( "SELECT hash FROM script WHERE path = $1 AND workspace_id = $2 \ ORDER BY created_at DESC LIMIT 1 FOR UPDATE", ) .bind(&ns.path) .bind(&w_id) .fetch_optional(&mut *tx) - .await?; + .await? + } else { + None + }; + set_lineage_reads_unscoped(&mut tx, &authed, true).await?; + if let Some(hash) = adoption_candidate { // Adoptable only if nothing already descends from it: a rename leaves its source // path holding a version whose child lives at the destination, and a second child // forks a lineage the guard below requires to be linear. Nothing adoptable means a // fresh lineage, which has no parent to vary its hash and can still collide. - ns.parent_hash = match candidate { - Some(hash) => sqlx::query_scalar!( - "SELECT 1 FROM script WHERE parent_hashes[1] = $1 AND workspace_id = $2", - hash, - &w_id - ) - .fetch_optional(&db) - .await? - .is_none() - .then_some(ScriptHash(hash)), - None => None, - }; + ns.parent_hash = sqlx::query_scalar!( + "SELECT 1 FROM script WHERE parent_hashes[1] = $1 AND workspace_id = $2", + hash, + &w_id + ) + .fetch_optional(&mut *tx) + .await? + .is_none() + .then_some(ScriptHash(hash)); parent_adopted_from_retired_path = ns.parent_hash.is_some(); } // Absent keeps the previous version's value, read once the parent is settled (a rename // adopts its source head above), so a client unaware of the setting cannot drop a // restriction by redeploying or renaming. - let resolved_job_token_scopes: Option> = match (&ns.job_token_scopes, &ns.parent_hash) { - (Some(Some(scopes)), _) => { - windmill_common::min_version::MIN_VERSION_SUPPORTS_JOB_TOKEN_SCOPES - .assert() - .await?; - Some(windmill_common::scopes::validate_job_token_scopes(scopes)?) - } - (Some(None), _) => None, - (None, Some(parent_hash)) => sqlx::query_scalar!( - "SELECT job_token_scopes FROM script WHERE hash = $1 AND workspace_id = $2", - parent_hash.0, - &w_id - ) - .fetch_optional(&db) - .await? - .flatten(), - (None, None) => sqlx::query_scalar!( - "SELECT job_token_scopes FROM script WHERE path = $1 AND workspace_id = $2 \ + let resolved_job_token_scopes: Option> = + match (&ns.job_token_scopes, &ns.parent_hash) { + (Some(Some(scopes)), _) => { + windmill_common::min_version::MIN_VERSION_SUPPORTS_JOB_TOKEN_SCOPES + .assert() + .await?; + Some(windmill_common::scopes::validate_job_token_scopes(scopes)?) + } + (Some(None), _) => None, + (None, Some(parent_hash)) => sqlx::query_scalar!( + "SELECT job_token_scopes FROM script WHERE hash = $1 AND workspace_id = $2", + parent_hash.0, + &w_id + ) + .fetch_optional(&mut *tx) + .await? + .flatten(), + (None, None) => sqlx::query_scalar!( + "SELECT job_token_scopes FROM script WHERE path = $1 AND workspace_id = $2 \ AND deleted = false ORDER BY created_at DESC LIMIT 1", - &ns.path, - &w_id - ) - .fetch_optional(&db) - .await? - .flatten(), - }; + &ns.path, + &w_id + ) + .fetch_optional(&mut *tx) + .await? + .flatten(), + }; + set_lineage_reads_unscoped(&mut tx, &authed, false).await?; ns.job_token_scopes = Some(resolved_job_token_scopes.clone()); // Before hashing, so the hash and the no-op check see the schema that gets stored. @@ -1610,14 +1700,16 @@ async fn create_script_internal<'c>( // Unscoped, and sound only under the lock above: linearity is a property of the // lineage, not of what this caller may read. A child can sit where they cannot // see it — a folder they renamed it into, or grants an adopting deploy reset — - // and asked through `tx` it reads as absent, letting the fork through. + // and asked through a scoped `tx` it reads as absent, letting the fork through. + set_lineage_reads_unscoped(&mut tx, &authed, true).await?; let clashing_hash_o = sqlx::query_scalar!( "SELECT hash FROM script WHERE parent_hashes[1] = $1 AND workspace_id = $2", p_hash.0, &w_id ) - .fetch_optional(&db) + .fetch_optional(&mut *tx) .await?; + set_lineage_reads_unscoped(&mut tx, &authed, false).await?; if let Some(clashing_hash) = clashing_hash_o { // Named only when the caller could already read it. The probe above has to be @@ -1662,7 +1754,7 @@ async fn create_script_internal<'c>( &ps, resolved_on_behalf_of.as_deref(), resolved_job_token_scopes.as_deref(), - &db, + &mut tx, ) .await? { @@ -2207,16 +2299,6 @@ async fn create_script_internal<'c>( auto_kind }; - let runnable_settings_handle = windmill_common::runnable_settings::insert_rs( - RunnableSettings { - debouncing_settings: ns.debouncing_settings.insert_cached(&db).await?, - concurrency_settings: ns.concurrency_settings.insert_cached(&db).await?, - retry_settings: None, - }, - &db, - ) - .await?; - let ( guarded_concurrent_limit, guarded_concurrency_time_window_s, @@ -4266,12 +4348,6 @@ async fn delete_script_by_path( check_scopes(&authed, || format!("scripts:write:{}", path))?; - if path == "u/admin/hub_sync" && w_id == "admins" { - return Err(Error::BadRequest( - "Cannot delete the global setup app".to_string(), - )); - } - if let RuleCheckResult::Blocked(msg) = check_deploy_rules( &w_id, AuditAuthorable::username(&authed), @@ -4445,12 +4521,6 @@ async fn delete_scripts_bulk( require_admin(authed.is_admin, &authed.username)?; - if request.paths.contains(&"u/admin/hub_sync".to_string()) && w_id == "admins" { - return Err(Error::BadRequest( - "Cannot delete the global setup app".to_string(), - )); - } - if let RuleCheckResult::Blocked(msg) = check_deploy_rules( &w_id, AuditAuthorable::username(&authed), diff --git a/backend/windmill-api-settings/Cargo.toml b/backend/windmill-api-settings/Cargo.toml index 0ec99ef6d0..816a2223ac 100644 --- a/backend/windmill-api-settings/Cargo.toml +++ b/backend/windmill-api-settings/Cargo.toml @@ -7,13 +7,15 @@ edition.workspace = true [lib] name = "windmill_api_settings" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] enterprise = ["license"] private = ["windmill-common/private", "windmill-audit/private"] parquet = ["windmill-common/parquet", "windmill-object-store/parquet"] -license = ["dep:rsa"] +license = ["dep:rsa", "dep:ed25519-dalek"] [dependencies] windmill-ai = { workspace = true, default-features = false } @@ -38,4 +40,5 @@ uuid.workspace = true base64.workspace = true sha2.workspace = true rsa = { workspace = true, optional = true } +ed25519-dalek = { workspace = true, optional = true } windmill-object-store.workspace = true diff --git a/backend/windmill-api-settings/src/lib.rs b/backend/windmill-api-settings/src/lib.rs index c79b596617..96c1be32c9 100644 --- a/backend/windmill-api-settings/src/lib.rs +++ b/backend/windmill-api-settings/src/lib.rs @@ -29,7 +29,12 @@ mod log_cleanup; mod storage_usage; use windmill_api_auth::{require_devops_role, require_super_admin, ApiAuthed}; -use windmill_audit::{audit_oss::audit_log, ActionKind}; +use windmill_audit::{ + audit_oss::audit_log, + instance_config::{audit_setting_write, InstanceConfigAuditor}, + ActionKind, +}; +use windmill_common::hub_resource_types::{self, SyncSource}; use windmill_common::utils::HTTP_CLIENT_PERMISSIVE as HTTP_CLIENT; use windmill_common::DB; @@ -58,10 +63,10 @@ use windmill_common::{ error::{self, pg_error_message, JsonResult, Result}, get_database_url, global_settings::{ - ACCENT_COLOR_SETTING, AI_CONFIG_SETTING, APP_WORKSPACED_ROUTE_SETTING, - AUTOMATE_USERNAME_CREATION_SETTING, CRITICAL_ALERT_MUTE_UI_SETTING, CUSTOM_TAGS_SETTING, - DEFAULT_TAGS_WORKSPACES_SETTING, DISABLE_HUB_SETTING, EMAIL_DOMAIN_SETTING, ENV_SETTINGS, - EXTERNAL_INSTANCE_PG_SETTING, + ACCENT_COLOR_SETTING, AI_CONFIG_SETTING, API_BASE_URL_SETTING, + APP_WORKSPACED_ROUTE_SETTING, AUTOMATE_USERNAME_CREATION_SETTING, + CRITICAL_ALERT_MUTE_UI_SETTING, CUSTOM_TAGS_SETTING, DEFAULT_TAGS_WORKSPACES_SETTING, + DISABLE_HUB_SETTING, EMAIL_DOMAIN_SETTING, ENV_SETTINGS, EXTERNAL_INSTANCE_PG_SETTING, GITHUB_APP_WEBHOOK_BASE_URL_SETTING, HTTP_ROUTE_DEFAULT_ALLOWED_ORIGINS_SETTING, HTTP_ROUTE_WORKSPACED_ROUTE_SETTING, HUB_ACCESSIBLE_URL_SETTING, HUB_BASE_URL_SETTING, INSTANCE_BANNER_SETTING, MAX_RETENTION_OVERRIDE_WORKSPACES, @@ -127,6 +132,15 @@ async fn get_instance_ui( )) } +/// Whether email notifications can go out, for the workspace admins who configure email +/// handlers and cannot read `smtp_settings` itself (it holds the password). Asks the same +/// resolver the senders use, so SMTP set through `SMTP_*` env vars counts too. +async fn get_smtp_configured(Extension(db): Extension, _authed: ApiAuthed) -> JsonResult { + Ok(Json( + SMTP_ENABLED && windmill_common::server::is_smtp_configured(&db).await?, + )) +} + pub fn global_service() -> Router { #[warn(unused_mut)] let r = Router::new() @@ -147,6 +161,7 @@ pub fn global_service() -> Router { ) .route("/instance_config/yaml", get(get_instance_config_yaml)) .route("/test_smtp", post(test_email)) + .route("/smtp_configured", get(get_smtp_configured)) .route("/test_license_key", post(test_license_key)) .route("/send_stats", post(send_stats)) .route("/get_stats", get(get_stats)) @@ -832,50 +847,7 @@ pub async fn set_global_setting( require_super_admin(&db, &authed).await?; let value = value.value.unwrap_or(serde_json::Value::Null); set_global_setting_internal(&db, key.clone(), value.clone()).await?; - audit_setting_write(&db, &authed, &key, Some(&value)).await -} - -/// A setting is recorded by name, with its value only when that is a boolean or a number. -/// Any other shape can carry a credential (a registry URL, a webhook, a header map), and no -/// list of secret-bearing settings stays complete as settings are added. -/// -/// AUTHORIZATION: records a write, checks nothing. The caller must have established that -/// `authed` may change instance settings before performing the write this records. -pub async fn audit_setting_write( - db: &DB, - authed: &ApiAuthed, - key: &str, - value: Option<&serde_json::Value>, -) -> error::Result<()> { - let deleted = match value { - None | Some(serde_json::Value::Null) => true, - Some(serde_json::Value::String(s)) => s.trim().is_empty(), - Some(_) => false, - }; - let recorded = match value { - Some(v @ (serde_json::Value::Bool(_) | serde_json::Value::Number(_))) => { - Some(v.to_string()) - } - _ => None, - }; - audit_log( - db, - authed, - if deleted { - "global_settings.delete" - } else { - "global_settings.update" - }, - if deleted { - ActionKind::Delete - } else { - ActionKind::Update - }, - "global", - Some(key), - recorded.as_deref().map(|v| [("value", v)].into()), - ) - .await + audit_setting_write(&db, &authed, &key, Some(&value), None).await } async fn audit_instance_action( @@ -944,6 +916,7 @@ pub async fn set_global_setting_internal( run_setting_pre_write_hook(db, &key, &value).await?; + let turns_on = value.as_bool() == Some(true); match value { serde_json::Value::Null => { if instance_config::PROTECTED_SETTINGS.contains(&key.as_str()) { @@ -977,6 +950,21 @@ pub async fn set_global_setting_internal( } }; + if key == windmill_common::global_settings::DEV_WORKSPACE_ISOLATION_SETTING { + windmill_common::feature_usage::log_feature_usage( + "dev_workspace_isolation", + "toggle", + if turns_on { "on" } else { "off" }, + ); + } + if key == windmill_common::global_settings::DEV_WORKSPACE_ISOLATION_SKIP_NON_DEV_FORKS_SETTING { + windmill_common::feature_usage::log_feature_usage( + "dev_workspace_isolation", + "skip_non_dev_forks_toggle", + if turns_on { "on" } else { "off" }, + ); + } + if should_bump_instance_ai_revision { bump_instance_ai_config_revision(); } @@ -1003,6 +991,14 @@ async fn run_setting_pre_write_hook( value: &serde_json::Value, ) -> error::Result<()> { match key { + windmill_common::global_settings::DEV_WORKSPACE_TAG_SUFFIX_SETTING => match value { + serde_json::Value::Null => {} + serde_json::Value::String(s) if s.trim().is_empty() => {} + suffix => windmill_common::global_settings::validate_dev_workspace_tag_suffix(suffix) + .map_err(|e| { + error::Error::BadRequest(format!("The dev workspace tag suffix {e}")) + })?, + }, // The instance AI config is written as an untyped blob through this generic // endpoint, so it never passes the typed check the workspace handler applies. // Rates that reach a cost total unbounded would make it negative or infinite. @@ -1238,26 +1234,22 @@ async fn run_setting_pre_write_hook( } } } - GITHUB_APP_WEBHOOK_BASE_URL_SETTING => { - // A bad value here yields a webhook GitHub can never deliver to, and the + GITHUB_APP_WEBHOOK_BASE_URL_SETTING | API_BASE_URL_SETTING => { + // A bad webhook base yields a webhook GitHub can never deliver to, and the // failure only shows up much later as "falling back to polling" on a - // repository — so reject it at the boundary instead. + // repository; a bad API base puts an unreachable URL in front of every user. + // So reject both at the boundary instead. match value { // Clearing (delete row) is handled by the caller; allow it through. serde_json::Value::Null => {} serde_json::Value::String(s) if s.trim().is_empty() => {} serde_json::Value::String(s) => { - windmill_common::global_settings::validate_webhook_base_url(s).map_err( - |e| { - error::Error::BadRequest(format!( - "{GITHUB_APP_WEBHOOK_BASE_URL_SETTING}: {e}" - )) - }, - )?; + windmill_common::global_settings::validate_webhook_base_url(s) + .map_err(|e| error::Error::BadRequest(format!("{key}: {e}")))?; } _ => { return Err(error::Error::BadRequest(format!( - "{GITHUB_APP_WEBHOOK_BASE_URL_SETTING} must be a URL string" + "{key} must be a URL string" ))); } } @@ -1286,6 +1278,13 @@ async fn run_setting_pre_write_hook( v => windmill_common::global_settings::validate_accent_color(v) .map_err(|e| error::Error::BadRequest(format!("{ACCENT_COLOR_SETTING}: {e}")))?, }, + windmill_common::global_settings::AGENT_WORKLOAD_IDENTITY_ISSUERS_SETTING => { + if !value.is_null() { + let key = windmill_common::global_settings::AGENT_WORKLOAD_IDENTITY_ISSUERS_SETTING; + windmill_common::agent_workload_identity::validate_issuers_value(value) + .map_err(|e| error::Error::BadRequest(format!("{key}: {e}")))?; + } + } _ => {} } Ok(()) @@ -1370,61 +1369,17 @@ async fn set_instance_config( run_setting_pre_write_hook(&db, key, value).await?; } } + let auditor = InstanceConfigAuditor { db: &db, author: &authed, source: None }; // The external-instance write removes its own key from the diff. - let external = settings_diff - .upserts - .get(EXTERNAL_INSTANCE_PG_SETTING) - .cloned() - .map(Some) - .or_else(|| { - settings_diff - .deletes - .iter() - .any(|k| k == EXTERNAL_INSTANCE_PG_SETTING) - .then_some(None) - }); windmill_common::external_instance_pg::write_external_instance_pg_from_diff( &db, &mut settings_diff, + &auditor, ) .await?; - if let Some(value) = external { - audit_setting_write(&db, &authed, EXTERNAL_INSTANCE_PG_SETTING, value.as_ref()).await?; - } - - // Applied and audited one setting at a time: the writes are not transactional, so a - // batch that fails midway must not leave the settings it did write unrecorded. - let instance_config::SettingsDiff { upserts, deletes, mut previous_values, unchanged_count } = - settings_diff; - let steps = upserts - .into_iter() - .map(|(k, v)| (k, Some(v))) - .chain(deletes.into_iter().map(|k| (k, None))) - .map(Some) - .chain(std::iter::once(None)); - for step in steps { - let mut diff = instance_config::SettingsDiff::default(); - match &step { - Some((key, value)) => { - if let Some(previous) = previous_values.remove(key) { - diff.previous_values.insert(key.clone(), previous); - } - match value { - Some(value) => { - diff.upserts.insert(key.clone(), value.clone()); - } - None => diff.deletes.push(key.clone()), - } - } - None => diff.unchanged_count = unchanged_count, - } - instance_config::apply_settings_diff(&db, &diff) - .await - .map_err(|e| error::Error::internal_err(e.to_string()))?; - if let Some((key, value)) = &step { - audit_setting_write(&db, &authed, key, value.as_ref()).await?; - } - } + instance_config::apply_settings_diff(&db, &settings_diff, &auditor) + .await + .map_err(|e| error::Error::internal_err(e.to_string()))?; if ai_config_changed { bump_instance_ai_config_revision(); @@ -1454,37 +1409,13 @@ async fn set_instance_config( .collect(); let configs_diff = instance_config::diff_worker_configs(¤t_wc, &desired_wc, ApplyMode::Merge); - let steps = configs_diff - .upserts - .into_iter() - .map(|(g, c)| (g, Some(c))) - .chain(configs_diff.deletes.into_iter().map(|g| (g, None))); - for (group, config) in steps { - let mut diff = instance_config::ConfigsDiff::default(); - let (operation, action_kind) = match config { - Some(config) => { - diff.upserts.insert(group.clone(), config); - ("worker_config.update", ActionKind::Update) - } - None => { - diff.deletes.push(group.clone()); - ("worker_config.delete", ActionKind::Delete) - } - }; - instance_config::apply_configs_diff(&db, &diff) - .await - .map_err(|e| error::Error::internal_err(e.to_string()))?; - audit_log( - &db, - &authed, - operation, - action_kind, - "global", - Some(&format!("worker__{group}")), - None, - ) - .await?; - } + instance_config::apply_configs_diff( + &db, + &configs_diff, + &InstanceConfigAuditor { db: &db, author: &authed, source: None }, + ) + .await + .map_err(|e| error::Error::internal_err(e.to_string()))?; } Ok(()) @@ -2576,95 +2507,6 @@ pub async fn get_jwks() -> JsonResult { Ok(Json(JwksResponse { keys: vec![] })) } -#[derive(serde::Deserialize, serde::Serialize)] -struct CachedResourceType { - #[allow(dead_code)] - id: i64, - name: String, - schema: Option, - #[allow(dead_code)] - app: String, - description: Option, - /// Doubly optional, and read through a wrapping deserializer: this struct also - /// decodes the on-disk cache, where an absent key means "written before the - /// column, leave the stored extension alone" and an explicit null means the hub - /// dropped it. Plain serde folds both into `None`. - #[serde( - default, - deserialize_with = "windmill_common::more_serde::double_option" - )] - format_extension: Option>, - /// Doubly optional like `format_extension`: no key leaves the stored name alone, an explicit - /// null (the hub naming nothing) clears it. - #[serde( - default, - deserialize_with = "windmill_common::more_serde::double_option" - )] - display_name: Option>, -} - -#[derive(serde::Deserialize)] -struct HubResourceTypeRaw { - id: i64, - name: String, - schema: Option, - app: String, - description: Option, - #[serde(default)] - format_extension: Option, - #[serde( - default, - deserialize_with = "windmill_common::more_serde::double_option" - )] - display_name: Option>, -} - -async fn fetch_resource_types_from_hub() -> error::Result> { - let response = HTTP_CLIENT - .get(format!( - "{}/resource_types/list", - windmill_common::DEFAULT_HUB_BASE_URL - )) - .header("Accept", "application/json") - .send() - .await - .map_err(|e| error::Error::InternalErr(format!("Failed to fetch from hub: {}", e)))?; - - if !response.status().is_success() { - return Err(error::Error::InternalErr(format!( - "Hub returned status {}", - response.status() - ))); - } - - let raw_types: Vec = response - .json() - .await - .map_err(|e| error::Error::InternalErr(format!("Failed to parse hub response: {}", e)))?; - - Ok(raw_types - .into_iter() - .filter_map(|rt| { - let schema = match rt.schema { - Some(s) => match serde_json::from_str(&s) { - Ok(v) => Some(v), - Err(_) => return None, - }, - None => None, - }; - Some(CachedResourceType { - id: rt.id, - name: rt.name, - schema, - app: rt.app, - description: rt.description, - format_extension: Some(rt.format_extension), - display_name: rt.display_name, - }) - }) - .collect()) -} - #[derive(serde::Deserialize)] struct SyncResourceTypesQuery { name: Option, @@ -2677,118 +2519,45 @@ async fn sync_cached_resource_types( ) -> error::Result { require_super_admin(&db, &authed).await?; - use windmill_common::worker::HUB_RT_CACHE_DIR; - let cache_path = format!("{}/resource_types.json", *HUB_RT_CACHE_DIR); + let outcome = hub_resource_types::sync(&db).await?; - // Manual sync is hub-first so it lands newly-published hub types on demand. The - // on-disk cache is only a fallback for when the hub is unreachable (airgapped - // installs / network error); refreshing it is left to the daily cache-rt cron and - // the startup sync in main.rs, which own the offline path. - let (resource_types, from_hub) = match fetch_resource_types_from_hub().await { - Ok(types) => { - tracing::info!("Fetched {} resource types live from the hub", types.len()); - (types, true) - } - Err(hub_err) => { - tracing::warn!( - "Live hub fetch failed ({hub_err}), falling back to on-disk cache at {cache_path}" - ); - match tokio::fs::read_to_string(&cache_path).await { - Ok(content) => { - let parsed = serde_json::from_str::>(&content) - .map_err(|e| { - error::Error::InternalErr(format!( - "Failed to parse cached resource types: {}", - e - )) - })?; - (parsed, false) - } - Err(_) => return Err(hub_err), - } - } - }; - - let mut synced_count = 0; - - for rt in &resource_types { - // A name too long for the column counts as absent, leaving the stored one alone: one bad - // entry must not fail the upsert and end the rest of the sync. - let display_name = match &rt.display_name { - Some(Some(name)) if name.chars().count() > 100 => None, - other => other.clone(), + if !outcome.changed.is_empty() { + let source = match outcome.source { + SyncSource::Hub => "hub", + SyncSource::ImageCache => "image_cache", }; - let exists: Option = sqlx::query_scalar!( - "SELECT EXISTS(SELECT 1 FROM resource_type WHERE workspace_id = 'admins' AND name = $1 AND schema IS NOT DISTINCT FROM $2 AND description IS NOT DISTINCT FROM $3 AND ($5 IS NOT TRUE OR format_extension IS NOT DISTINCT FROM $4) AND ($7 IS NOT TRUE OR display_name IS NOT DISTINCT FROM $6))", - &rt.name, - rt.schema.as_ref(), - rt.description.as_deref(), - rt.format_extension.clone().flatten(), - rt.format_extension.is_some(), - display_name.clone().flatten(), - display_name.is_some(), + let changed = outcome.changed.join(", "); + audit_log( + &db, + &authed, + "resource_types.sync", + ActionKind::Update, + "admins", + None, + Some([("source", source), ("changed", changed.as_str())].into()), ) - .fetch_one(&db) .await?; - - if exists.unwrap_or(false) { - continue; - } - - sqlx::query!( - // Whether the payload carried the key at all is what decides: present - // (even as null) is authoritative and may clear, absent means a cache - // written before the column and must leave the stored value alone. - "INSERT INTO resource_type (workspace_id, name, schema, description, format_extension, display_name, edited_at) - VALUES ('admins', $1, $2, $3, $4, $6, now()) - ON CONFLICT (workspace_id, name) DO UPDATE - SET schema = EXCLUDED.schema, description = EXCLUDED.description, - -- A fileset is a set of files, so it cannot also be one file. - -- Create and update reject the pair; this writer bypasses both, so - -- it declines the extension rather than persisting the forbidden - -- combination onto a same-named local fileset. - format_extension = CASE - WHEN resource_type.is_fileset THEN NULL - WHEN $5 THEN EXCLUDED.format_extension - ELSE resource_type.format_extension END, - display_name = CASE WHEN $7 THEN EXCLUDED.display_name ELSE resource_type.display_name END, - edited_at = now()", - &rt.name, - rt.schema.as_ref(), - rt.description.as_deref(), - rt.format_extension.clone().flatten(), - rt.format_extension.is_some(), - display_name.clone().flatten(), - display_name.is_some(), - ) - .execute(&db) - .await?; - - synced_count += 1; } // If a specific type was requested and is still absent after syncing, surface an // explicit not-found instead of a silent "Synced 0". Word it by source so the // cache-fallback path does not claim it checked the hub. if let Some(name) = name.as_deref() { - if !resource_types.iter().any(|rt| rt.name == name) { - let source = if from_hub { - "on the hub" - } else { - "in the cached resource types (hub unreachable)" + if !outcome.listed.iter().any(|listed| listed == name) { + let source = match outcome.source { + SyncSource::Hub => "on the hub", + SyncSource::ImageCache => "in the cached resource types (hub unavailable)", }; return Err(error::Error::NotFound(format!( - "resource type '{}' not found {}", - name, source + "resource type '{name}' not found {source}" ))); } } - Ok(format!( - "Synced {} resource types ({} unchanged)", - synced_count, - resource_types.len() - synced_count - )) + Ok(match outcome.source { + SyncSource::Hub => outcome.summary(), + SyncSource::ImageCache => format!("{}, the hub being unavailable", outcome.summary()), + }) } #[cfg(test)] diff --git a/backend/windmill-api-sse/Cargo.toml b/backend/windmill-api-sse/Cargo.toml index b8127c3d36..d70f760163 100644 --- a/backend/windmill-api-sse/Cargo.toml +++ b/backend/windmill-api-sse/Cargo.toml @@ -7,6 +7,9 @@ edition.workspace = true [lib] name = "windmill_api_sse" path = "src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [features] default = [] diff --git a/backend/windmill-api-users/Cargo.toml b/backend/windmill-api-users/Cargo.toml index 13ab8143d8..cfd683434c 100644 --- a/backend/windmill-api-users/Cargo.toml +++ b/backend/windmill-api-users/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_api_users" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-api-users/src/users.rs b/backend/windmill-api-users/src/users.rs index ac9defcd53..9c853d8ef8 100644 --- a/backend/windmill-api-users/src/users.rs +++ b/backend/windmill-api-users/src/users.rs @@ -490,7 +490,7 @@ async fn list_user_usage( " SELECT usr.email, usage.executions FROM usr, LATERAL ( - SELECT COALESCE(SUM(c.duration_ms + 1000)/1000 , 0)::BIGINT executions + SELECT COALESCE(SUM(COALESCE((c.extras->>'wac_last_segment_ms')::bigint, c.duration_ms) + 1000)/1000 , 0)::BIGINT executions FROM v2_job_completed c JOIN v2_job j USING (id) WHERE j.workspace_id = $1 AND j.kind NOT IN ('flow', 'flowpreview', 'flownode', 'singlestepflow') @@ -2120,6 +2120,15 @@ async fn change_user_email( .execute(&mut *tx) .await?; + sqlx::query( + "UPDATE resource SET value = jsonb_set(value, '{on_behalf_of}', to_jsonb($1::text)) + WHERE resource_type = 'ai_agent' AND value->>'on_behalf_of' = $2", + ) + .bind(&new_principal) + .bind(&old_principal) + .execute(&mut *tx) + .await?; + sqlx::query!( "UPDATE script SET on_behalf_of = $1 WHERE on_behalf_of = $2", &new_principal, diff --git a/backend/windmill-api-workers/Cargo.toml b/backend/windmill-api-workers/Cargo.toml index 8e54d84e77..fd87b8f4be 100644 --- a/backend/windmill-api-workers/Cargo.toml +++ b/backend/windmill-api-workers/Cargo.toml @@ -7,10 +7,14 @@ edition.workspace = true [lib] name = "windmill_api_workers" path = "src/lib.rs" +# src/ has no unit tests or doctests: remove both lines before adding one, or cargo test never runs it. +test = false +doctest = false [dependencies] windmill-api-auth.workspace = true windmill-common = { workspace = true, default-features = false } +windmill-queue.workspace = true axum.workspace = true chrono.workspace = true serde.workspace = true diff --git a/backend/windmill-api-workers/src/lib.rs b/backend/windmill-api-workers/src/lib.rs index 0102f1b033..2e224beb06 100644 --- a/backend/windmill-api-workers/src/lib.rs +++ b/backend/windmill-api-workers/src/lib.rs @@ -21,7 +21,11 @@ use windmill_common::{ jobs::{HIDE_WORKERS_FOR_NON_ADMINS, TAGS_ARE_SENSITIVE}, queue_metrics::{read_queue_metrics_series, QueueMetricsSeries}, utils::{paginate, Pagination}, - worker::{ALL_TAGS, CUSTOM_TAGS_PER_WORKSPACE, DEFAULT_TAGS, DEFAULT_TAGS_PER_WORKSPACE}, + worker::{ + ALL_TAGS, CUSTOM_TAGS_PER_WORKSPACE, DEFAULT_TAGS, DEFAULT_TAGS_PER_WORKSPACE, + DEV_WORKSPACE_ISOLATION, DEV_WORKSPACE_ISOLATION_SKIP_NON_DEV_FORKS, + DEV_WORKSPACE_TAG_SUFFIX, + }, workspaces::workspace_with_fork_ancestors, DB, }; @@ -37,10 +41,12 @@ pub fn global_service() -> Router { "/is_default_tags_per_workspace", get(get_default_tags_per_workspace), ) + .route("/dev_workspace_isolation", get(get_dev_workspace_isolation)) .route("/get_default_tags", get(get_default_tags)) .route("/queue_metrics", get(get_queue_metrics)) .route("/queue_metrics_series", get(get_queue_metrics_series)) .route("/queue_status", get(get_queue_status)) + .route("/runnable_stats", get(get_runnable_stats)) .route("/queue_counts", get(get_queue_counts)) .route("/queue_running_counts", get(get_queue_running_counts)) .route( @@ -86,6 +92,7 @@ struct WorkerPing { job_isolation: Option, #[serde(skip_serializing_if = "Option::is_none")] native_mode: Option, + draining: bool, } // #[derive(Serialize, Deserialize)] @@ -118,7 +125,7 @@ async fn list_worker_pings( WorkerPing, "SELECT worker, worker_instance, EXTRACT(EPOCH FROM (now() - ping_at))::integer as last_ping, started_at, ip, jobs_executed, CASE WHEN $4 IS TRUE THEN current_job_id ELSE NULL END as last_job_id, CASE WHEN $4 IS TRUE THEN current_job_workspace_id ELSE NULL END as last_job_workspace_id, - custom_tags, worker_group, wm_version, occupancy_rate, occupancy_rate_15s, occupancy_rate_5m, occupancy_rate_30m, memory, vcpus, memory_usage, wm_memory_usage, job_isolation, native_mode + custom_tags, worker_group, wm_version, occupancy_rate, occupancy_rate_15s, occupancy_rate_5m, occupancy_rate_30m, memory, vcpus, memory_usage, wm_memory_usage, job_isolation, native_mode, draining FROM worker_ping WHERE ($1::integer IS NULL AND ping_at > now() - interval '5 minute') OR (ping_at > now() - ($1 || ' seconds')::interval) ORDER BY ping_at desc LIMIT $2 OFFSET $3", @@ -184,7 +191,18 @@ async fn exists_workers_with_tags( let chain = workspace_with_fork_ancestors(&db, workspace).await?; let custom_tags = CUSTOM_TAGS_PER_WORKSPACE.load(); let allowed_tags = custom_tags.to_string_vec(Some(&chain)); - tags.retain(|t| allowed_tags.contains(t)); + // A dev workspace's jobs run on the suffixed form of the tags it may use. + let dev_suffix = windmill_queue::tags::dev_workspace_suffix_for(workspace, &db) + .await + .ok() + .flatten(); + tags.retain(|t| { + allowed_tags.contains(t) + || dev_suffix.as_deref().is_some_and(|s| { + t.strip_suffix(s) + .is_some_and(|b| allowed_tags.iter().any(|a| a == b)) + }) + }); } else { // No workspace provided and not superadmin - return empty return Ok(Json(std::collections::HashMap::new())); @@ -257,6 +275,22 @@ async fn get_default_tags_per_workspace() -> JsonResult { )) } +#[derive(Serialize)] +struct DevWorkspaceIsolation { + enabled: bool, + suffix: String, + skip_non_dev_forks: bool, +} + +async fn get_dev_workspace_isolation() -> JsonResult { + Ok(Json(DevWorkspaceIsolation { + enabled: DEV_WORKSPACE_ISOLATION.load(std::sync::atomic::Ordering::Relaxed), + suffix: DEV_WORKSPACE_TAG_SUFFIX.load().to_string(), + skip_non_dev_forks: DEV_WORKSPACE_ISOLATION_SKIP_NON_DEV_FORKS + .load(std::sync::atomic::Ordering::Relaxed), + })) +} + async fn get_default_tags() -> JsonResult> { Ok(Json(DEFAULT_TAGS.clone())) } @@ -298,6 +332,81 @@ async fn get_queue_metrics( Ok(Json(queue_metrics)) } +#[derive(Deserialize)] +struct RunnableStatsQuery { + window_secs: Option, + worker_group: Option, + workspace: Option, + order_by: Option, + limit: Option, +} + +#[derive(Serialize)] +struct RunnableStats { + workspace_id: String, + runnable_path: String, + worker_group: String, + job_count: i64, + total_duration_ms: i64, + max_memory_peak: i32, + sum_memory_peak: i64, + memory_sample_count: i64, + total_cpu_ms: i64, +} + +async fn get_runnable_stats( + authed: ApiAuthed, + Extension(db): Extension, + Query(query): Query, +) -> JsonResult> { + require_devops_role(&db, &authed).await?; + + let window = query.window_secs.unwrap_or(24 * 3600).clamp( + 3600, + windmill_common::runnable_job_stats::RETENTION_DAYS * 24 * 3600, + ); + // Rows are hourly buckets keyed by their start, so the bucket the window begins in + // is included whole. + let from_hour = (chrono::Utc::now().timestamp() - window) / 3600 * 3600; + let order_by = match query.order_by.as_deref() { + Some("max_memory") => "max_memory", + Some("cpu") => "cpu", + _ => "total_duration", + }; + + let rows = sqlx::query_as!( + RunnableStats, + r#" + SELECT workspace_id, runnable_path, worker_group, + SUM(job_count)::bigint AS "job_count!", + SUM(total_duration_ms)::bigint AS "total_duration_ms!", + MAX(max_memory_peak) AS "max_memory_peak!", + SUM(sum_memory_peak)::bigint AS "sum_memory_peak!", + SUM(memory_sample_count)::bigint AS "memory_sample_count!", + SUM(total_cpu_ms)::bigint AS "total_cpu_ms!" + FROM runnable_job_stats + WHERE hour >= $1 + AND ($2::text IS NULL OR worker_group = $2) + AND ($3::text IS NULL OR workspace_id = $3) + GROUP BY workspace_id, runnable_path, worker_group + ORDER BY CASE $4::text + WHEN 'max_memory' THEN MAX(max_memory_peak)::numeric + WHEN 'cpu' THEN SUM(total_cpu_ms) + ELSE SUM(total_duration_ms) + END DESC, workspace_id, runnable_path, worker_group + LIMIT $5 + "#, + from_hour, + query.worker_group, + query.workspace, + order_by, + query.limit.unwrap_or(100).clamp(1, 1000), + ) + .fetch_all(&db) + .await?; + Ok(Json(rows)) +} + #[derive(Deserialize)] struct QueueMetricsSeriesQuery { window_secs: Option, diff --git a/backend/windmill-api-workspaces/Cargo.toml b/backend/windmill-api-workspaces/Cargo.toml index 9f05a26f28..646536a9ec 100644 --- a/backend/windmill-api-workspaces/Cargo.toml +++ b/backend/windmill-api-workspaces/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_api_workspaces" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] diff --git a/backend/windmill-api-workspaces/src/datatable_clone.rs b/backend/windmill-api-workspaces/src/datatable_clone.rs index 6083b7b619..1e6c6b55c2 100644 --- a/backend/windmill-api-workspaces/src/datatable_clone.rs +++ b/backend/windmill-api-workspaces/src/datatable_clone.rs @@ -28,16 +28,22 @@ use windmill_common::workspaces::{ use windmill_common::{PgDatabase, DB}; use crate::datatable_acl::connect_with_notices; +use crate::datatable_migrations::{ + lock_migration_runs_on, read_applied_migrations, write_applied_migrations, AppliedMigrations, +}; use crate::datatable_permissions::ensure_reaches_governing_datatable; use crate::workspaces::{ - create_database_on_server, ensure_datatable_is_clonable, pg_dump_database, pg_import_dump, - DumpFile, PgDumpOptions, + copy_database_settings, create_database_on_server, ensure_datatable_is_clonable, + pg_dump_database, pg_import_dump, DumpFile, PgDumpOptions, }; -/// A database this request created and filled for one data table of the fork. +/// A database this request created and filled for the data tables of the fork on one source +/// database. pub(crate) struct MadeCopy { - /// The data table's name, in the parent and in the fork. - pub(crate) name: String, + /// The data tables' names, in the parent and in the fork, the one it was made for first. Data + /// tables on one database share its copy: a resource-backed fork has one resource for them all + /// to be pointed through. + pub(crate) names: Vec, pub(crate) dbname: String, pub(crate) behavior: DataTableForkBehavior, /// The database the source resolved to when it was copied. @@ -237,6 +243,7 @@ pub(crate) async fn authorize_copies( parent_w_id: &str, requests: &[CopyRequest<'_>], ) -> Result<()> { + let mut sources: Vec<(&CopyRequest<'_>, GoverningDatatable)> = Vec::new(); for request in requests { match request.behavior { DataTableForkBehavior::KeepOriginal => { @@ -265,9 +272,50 @@ pub(crate) async fn authorize_copies( let governing = ensure_datatable_is_clonable(db, parent_w_id, request.name).await?; ensure_reaches_governing_datatable(db, parent_w_id, request.name, &governing, authed) .await?; - if governing.datatable.permissions.is_some() { + let under_roles = governing.datatable.permissions.is_some(); + if under_roles { crate::datatable_replay_oss::ensure_replay()?; } + if let Some((first, first_governing)) = sources + .iter() + .find(|(_, earlier)| same_source(earlier, &governing)) + { + ensure_shares_copy(first.name, first.behavior, request)?; + if first_governing.datatable.permissions.is_some() != under_roles { + return Err(Error::BadRequest(format!( + "Data tables '{}' and '{}' use the same database, which the fork copies once, \ + but only one of them is under roles", + first.name, request.name + ))); + } + } + sources.push((request, governing)); + } + Ok(()) +} + +/// Whether two data tables are on one database. A resource is the governing workspace's. +fn same_source(a: &GoverningDatatable, b: &GoverningDatatable) -> bool { + same_database(&a.datatable.database, &b.datatable.database) + && (a.workspace_id == b.workspace_id + || a.datatable + .database + .as_ref() + .is_some_and(|d| d.resource_type.is_windmill_managed())) +} + +/// Data tables on one database get one copy, made as the first of them asks. +fn ensure_shares_copy( + first: &str, + behavior: DataTableForkBehavior, + request: &CopyRequest<'_>, +) -> Result<()> { + if behavior != request.behavior { + return Err(Error::BadRequest(format!( + "Data tables '{}' and '{}' use the same database, which the fork copies once: fork \ + them with the same behavior", + first, request.name + ))); } Ok(()) } @@ -281,10 +329,28 @@ pub(crate) async fn make_copies( requests: &[CopyRequest<'_>], ) -> Result> { authorize_copies(db, authed, parent_w_id, requests).await?; - let mut copies = Vec::with_capacity(requests.len()); + let mut copies: Vec = Vec::with_capacity(requests.len()); + // What each copy was made from, by index. + let mut sources: Vec = Vec::with_capacity(requests.len()); for request in requests { + // Checked again by the fork against the copy's `source_database`, under the locks. + let governing = match ensure_datatable_is_clonable(db, parent_w_id, request.name).await { + Ok(governing) => governing, + Err(e) => return Err(drop_copies_after(db, copies, e).await), + }; + let shared = sources.iter().position(|s| same_source(s, &governing)); + if let Some(c) = shared { + if let Err(e) = ensure_shares_copy(&copies[c].names[0], copies[c].behavior, request) { + return Err(drop_copies_after(db, copies, e).await); + } + copies[c].names.push(request.name.to_string()); + continue; + } match make_copy(db, authed, parent_w_id, request).await { - Ok(copy) => copies.push(copy), + Ok(copy) => { + copies.push(copy); + sources.push(governing); + } Err(e) => return Err(drop_copies_after(db, copies, e).await), } } @@ -336,8 +402,8 @@ async fn drop_copy(db: &DB, source_database: &DataTableDatabase, dbname: &str) - Ok(()) } DataTableCatalogResourceType::Postgresql => { - // On a server of the workspace's own, where a resource edited meanwhile can already name it - // and nothing locks such an edit: dropping it could take someone's data. + // On a server of the workspace's own, where a resource edited meanwhile can already name it + // and nothing locks such an edit: dropping it could take someone's data. Err(Error::BadRequest( "kept on its PostgreSQL server, where it may already be in use; drop it there once \ it is not, before forking the same data table under this id again" @@ -392,20 +458,25 @@ async fn make_copy( (server, Some(snapshot)) }; + let schema_only = request.behavior == DataTableForkBehavior::SchemaOnly; + let migrations_lock = if schema_only { + Some(lock_migration_runs_on(db, &server, request.name).await?) + } else { + None + }; // Dumped before the database exists, so a source that cannot be read leaves nothing behind. // Ownership never carries over: the restore runs as the target's connection user. Grants do, // except on a cluster Windmill manages, which plants its own and where the replay below is what // reproduces the roles'. let dump = pg_dump_database( &server, - PgDumpOptions { - schema_only: request.behavior == DataTableForkBehavior::SchemaOnly, - no_owner: true, - no_acl: managed, - ..Default::default() - }, + PgDumpOptions { schema_only, no_owner: true, no_acl: managed, ..Default::default() }, ) .await?; + let applied = match migrations_lock { + Some(client) => Some(read_applied_migrations(&client).await?), + None => None, + }; match source_database.resource_type { DataTableCatalogResourceType::Instance => { @@ -444,11 +515,12 @@ async fn make_copy( &server, &target, &dump, + applied.as_ref(), ) .await; match filled { Ok(replayed) => Ok(MadeCopy { - name: request.name.to_string(), + names: vec![request.name.to_string()], dbname: request.dbname.to_string(), behavior: request.behavior, source_database, @@ -484,8 +556,12 @@ async fn fill( source: &PgDatabase, target: &PgDatabase, dump: &DumpFile, + applied: Option<&AppliedMigrations>, ) -> Result { pg_import_dump(target, dump).await?; + if let Some(applied) = applied { + write_applied_migrations(db, target, applied).await?; + } // Held until the replay commits: a role renamed or dropped meanwhile would change what the // replay names, and a settings save could move the source onto another database or put it under @@ -554,6 +630,7 @@ async fn fill( })?; } tx.commit().await?; + copy_database_settings(db, source, target).await?; Ok(replayed) } diff --git a/backend/windmill-api-workspaces/src/datatable_migration_scope.rs b/backend/windmill-api-workspaces/src/datatable_migration_scope.rs new file mode 100644 index 0000000000..ea98bc7309 --- /dev/null +++ b/backend/windmill-api-workspaces/src/datatable_migration_scope.rs @@ -0,0 +1,319 @@ +/* + * Author: Ruben Fiszel + * Copyright: Windmill Labs, Inc 2022 + * This file and its contents are licensed under the AGPLv3 License. + * Please see the included NOTICE for copyright information and + * LICENSE-AGPL for a copy of the license. + */ + +//! A data table migration's scope: the schemas it declares it touches, written as a +//! `-- schemas sales, billing` annotation in its up SQL. A migration that declares none applies to +//! the whole database. +//! +//! Scope decides ordering, not access: a migration waits on every earlier migration whose scope +//! overlaps its own, and its rollback on every later overlapping one. A whole-database migration +//! overlaps everything, so it is a barrier; migrations on disjoint schemas do not wait on each +//! other. Nothing checks that the SQL stays inside its declared scope. + +use std::collections::HashSet; + +use windmill_common::error::{Error, Result}; + +/// The schemas a migration declares, lowercased, or `None` for the whole database. +pub(crate) type Scope = Option>; + +const KEYWORD: &str = "schemas"; + +/// Read the `-- schemas a, b` annotation from the leading comment block of `code`, the way +/// `SqlAnnotations::datatable_role` reads `-- role`. A leading comment whose first word is +/// `schemas` is an annotation attempt, and a malformed one is an error rather than a silent +/// whole-database scope. +/// +/// Names are lowercased: SQL folds unquoted identifiers, and two migrations spelling one schema +/// `Sales` and `sales` must still be ordered against each other. A false overlap only costs +/// waiting; a false disjointness lets a migration run before one it depends on. +pub(crate) fn parse_migration_schemas(code: &str) -> Result { + for line in code.lines() { + let line = line.trim(); + if line.is_empty() { + continue; + } + if !line.starts_with("--") { + break; + } + let body = line[2..].trim_start(); + let Some(after) = body + .get(..KEYWORD.len()) + .filter(|kw| kw.eq_ignore_ascii_case(KEYWORD)) + .map(|_| &body[KEYWORD.len()..]) + else { + continue; + }; + if !after.is_empty() + && !after.starts_with(char::is_whitespace) + && !after.starts_with([':', '=']) + { + continue; + } + let after = after.trim_start(); + let after = after.strip_prefix([':', '=']).unwrap_or(after).trim(); + let after = after.strip_suffix(';').unwrap_or(after); + let mut schemas: Vec = vec![]; + for piece in after.split(',') { + let name = piece.trim(); + if !is_annotatable_schema_name(name) { + return Err(Error::BadRequest(format!( + "Malformed data table migration scope annotation: `{line}`. Write it as \ + `-- schemas , ` on a line of its own, where each name is \ + letters, digits, '_', '$' or '-', or leave it out for a migration that \ + applies to the whole database. A comment in the leading block that starts \ + with the word 'schemas' is read as this annotation; move it below the first \ + statement if it is prose." + ))); + } + let name = name.to_ascii_lowercase(); + if !schemas.contains(&name) { + schemas.push(name); + } + } + return Ok(Some(schemas)); + } + Ok(None) +} + +/// Whether `name` can be written in a `-- schemas` annotation. +fn is_annotatable_schema_name(name: &str) -> bool { + !name.is_empty() + && name.len() <= 63 + && name + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '$' | '-')) +} + +pub(crate) fn scopes_overlap(a: &Scope, b: &Scope) -> bool { + match (a, b) { + (Some(a), Some(b)) => a.iter().any(|s| b.contains(s)), + _ => true, + } +} + +/// One migration of a data table's chain, as ordering sees it. +pub(crate) struct ChainEntry { + pub(crate) timestamp: i64, + pub(crate) name: String, + /// A malformed annotation counts as the whole database, so it orders conservatively. It is + /// refused only when a migration is written: one stored before scopes existed may open with + /// prose that starts with the word, and must keep running as it always did. + pub(crate) scope: Scope, +} + +impl ChainEntry { + pub(crate) fn new(timestamp: i64, name: String, code_up: &str) -> Self { + let scope = parse_migration_schemas(code_up).unwrap_or(None); + Self { timestamp, name, scope } + } + + fn label(&self) -> String { + format!("{} ({})", self.timestamp, self.name) + } +} + +/// Why `later` has to wait for `earlier`, for an error message. +fn overlap_reason(later: &ChainEntry, earlier: &ChainEntry) -> String { + match (&later.scope, &earlier.scope) { + (_, None) => format!("{} applies to the whole database", earlier.label()), + (None, _) => format!("{} applies to the whole database", later.label()), + (Some(a), Some(b)) => { + let shared: Vec<&str> = a + .iter() + .filter(|s| b.contains(s)) + .map(String::as_str) + .collect(); + format!("both touch schema {}", shared.join(", ")) + } + } +} + +/// Which pending migrations one run applies. +pub(crate) enum RunSelection { + /// Every pending migration, or those up to and including a version. + UpTo(Option), + /// One version. + Only(i64), + /// The pending migrations that declare this schema. A whole-database one is never part of + /// it: running for one schema must not change the others. + Schema(String), +} + +/// The chain indices one run applies, in order, or why it cannot start. Every selected migration +/// needs each earlier overlapping migration applied or applied by this same run, so the whole run +/// is refused before anything is applied rather than stopping half-way. +/// +/// `Only` is exempt: it is the explicit out-of-order run, which the editors confirm with the user +/// (through `blocked_by`) before asking for it. +pub(crate) fn plan_run( + chain: &[ChainEntry], + applied: &HashSet, + selection: &RunSelection, +) -> Result> { + let pending = |i: usize| !applied.contains(&chain[i].timestamp); + let selected: Vec = (0..chain.len()) + .filter(|&i| { + pending(i) + && match selection { + RunSelection::UpTo(None) => true, + RunSelection::UpTo(Some(up_to)) => chain[i].timestamp <= *up_to, + RunSelection::Only(version) => chain[i].timestamp == *version, + RunSelection::Schema(schema) => { + chain[i].scope.as_ref().is_some_and(|s| s.contains(schema)) + } + } + }) + .collect(); + if matches!(selection, RunSelection::Only(_)) { + return Ok(selected); + } + let in_run: HashSet = selected.iter().copied().collect(); + for &i in &selected { + let blocker = (0..i).find(|&j| { + pending(j) && !in_run.contains(&j) && scopes_overlap(&chain[i].scope, &chain[j].scope) + }); + if let Some(j) = blocker { + return Err(Error::BadRequest(format!( + "Migration {} cannot run before {}, which is not applied yet: {}. Apply it first, \ + or run all pending migrations.", + chain[i].label(), + chain[j].label(), + overlap_reason(&chain[i], &chain[j]), + ))); + } + } + Ok(selected) +} + +/// The earliest pending migration `chain[i]` has to wait for, when it is pending; the latest +/// applied migration that has to be rolled back before it, when it is applied. +pub(crate) fn blocked_by(chain: &[ChainEntry], applied: &HashSet, i: usize) -> Option { + let is_applied = |j: usize| applied.contains(&chain[j].timestamp); + let overlaps = |j: usize| scopes_overlap(&chain[i].scope, &chain[j].scope); + if is_applied(i) { + (i + 1..chain.len()) + .rev() + .find(|&j| is_applied(j) && overlaps(j)) + } else { + (0..i).find(|&j| !is_applied(j) && overlaps(j)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn s(names: &[&str]) -> Scope { + Some(names.iter().map(|n| n.to_string()).collect()) + } + + #[test] + fn schemas_annotation_is_read_from_the_leading_comment_block() { + let p = |code| parse_migration_schemas(code).unwrap(); + assert_eq!(p("-- schemas sales\nBEGIN;"), s(&["sales"])); + assert_eq!( + p("-- role analyst\n-- Schemas: Sales, billing,sales;\nBEGIN;"), + s(&["sales", "billing"]) + ); + assert_eq!(p("-- schemas=a\nBEGIN;"), s(&["a"])); + assert_eq!(p("BEGIN;\n-- schemas sales"), None); + assert_eq!(p("-- schemasx sales\nBEGIN;"), None); + assert_eq!(p("-- up migration: x\nBEGIN;"), None); + for malformed in [ + "-- schemas\nBEGIN;", + "-- schemas:\nBEGIN;", + "-- schemas sales billing\nBEGIN;", + "-- schemas: changes for the orders table\nBEGIN;", + "-- schemas a,,b\nBEGIN;", + "-- schemas a.b\nBEGIN;", + ] { + assert!(parse_migration_schemas(malformed).is_err(), "{malformed}"); + } + } + + fn chain(entries: &[(i64, Scope)]) -> Vec { + entries + .iter() + .map(|(t, scope)| ChainEntry { + timestamp: *t, + name: format!("m{t}"), + scope: scope.clone(), + }) + .collect() + } + + fn versions(c: &[ChainEntry], idx: Vec) -> Vec { + idx.into_iter().map(|i| c[i].timestamp).collect() + } + + #[test] + fn a_run_waits_only_on_overlapping_earlier_migrations() { + let c = chain(&[ + (1, None), + (2, s(&["sales"])), + (3, s(&["billing"])), + (4, s(&["sales", "billing"])), + (5, None), + (6, s(&["sales"])), + ]); + let applied: HashSet = [1].into(); + + // Disjoint schemas don't wait on each other; a cross-schema migration waits on both, a + // whole-database one on everything. + assert_eq!(blocked_by(&c, &applied, 2).map(|j| c[j].timestamp), None); + assert_eq!(blocked_by(&c, &applied, 3).map(|j| c[j].timestamp), Some(2)); + assert_eq!(blocked_by(&c, &applied, 4).map(|j| c[j].timestamp), Some(2)); + // An explicit single run is the confirmed override. + assert_eq!( + versions(&c, plan_run(&c, &applied, &RunSelection::Only(4)).unwrap()), + vec![4] + ); + + // Running for a schema takes what declares it, refuses past a pending whole-database + // migration, and refuses when a selected migration also needs another schema's. + let for_schema = + |a: &HashSet, x: &str| plan_run(&c, a, &RunSelection::Schema(x.into())); + let err = for_schema(&applied, "sales").unwrap_err().to_string(); + assert!(err.contains("4 (m4)") && err.contains("3 (m3)"), "{err}"); + let applied: HashSet = [1, 3].into(); + let err = for_schema(&applied, "sales").unwrap_err().to_string(); + assert!( + err.contains("5 (m5)") && err.contains("whole database"), + "{err}" + ); + let applied: HashSet = [1, 3, 5].into(); + assert_eq!( + versions(&c, for_schema(&applied, "sales").unwrap()), + vec![2, 4, 6] + ); + // Everything pending in order needs no check: each earlier pending one is in the run. + assert_eq!( + versions( + &c, + plan_run(&c, &[1].into(), &RunSelection::UpTo(None)).unwrap() + ), + vec![2, 3, 4, 5, 6] + ); + } + + #[test] + fn a_rollback_waits_on_later_overlapping_migrations() { + let c = chain(&[ + (1, None), + (2, s(&["sales"])), + (3, s(&["billing"])), + (4, s(&["sales"])), + ]); + let applied: HashSet = [1, 2, 3, 4].into(); + let blocker = |i| blocked_by(&c, &applied, i).map(|j| c[j].timestamp); + assert_eq!(blocker(2), None); + assert_eq!(blocker(1), Some(4)); + assert_eq!(blocker(0), Some(4)); + } +} diff --git a/backend/windmill-api-workspaces/src/datatable_migrations.rs b/backend/windmill-api-workspaces/src/datatable_migrations.rs index e63e69d4d5..839b449f37 100644 --- a/backend/windmill-api-workspaces/src/datatable_migrations.rs +++ b/backend/windmill-api-workspaces/src/datatable_migrations.rs @@ -10,6 +10,9 @@ //! management, and the workspace-merge diff helper. Split out of `workspaces.rs` //! to keep that file focused on core workspace configuration. +use crate::datatable_migration_scope::{ + blocked_by, parse_migration_schemas, plan_run, ChainEntry, RunSelection, +}; use crate::workspaces::{ managed_datatable_kind, pg_dump_database, strip_unreplayable_dump_lines, ItemComparison, PgDumpOptions, @@ -165,6 +168,19 @@ fn ensure_not_operator(authed: &ApiAuthed) -> Result<()> { Ok(()) } +/// Whether new migrations declare a scope, which the editors push for but do not require. +fn log_migration_scope(scope: &crate::datatable_migration_scope::Scope) { + windmill_common::feature_usage::log_feature_usage( + "datatable", + "migration_scope", + if scope.is_some() { + "scoped" + } else { + "whole_database" + }, + ); +} + #[derive(Serialize)] struct AppliedMigration { version: i64, @@ -182,8 +198,11 @@ struct RunDatatableMigrationsQuery { up_to: Option, /// When set, apply only this specific migration version (if not already /// applied), ignoring any other pending migrations. Takes precedence over - /// `up_to`. + /// `up_to` and `schema`. only: Option, + /// When set, apply only the pending migrations that declare this schema in their + /// `-- schemas` annotation. Takes precedence over `up_to`. + schema: Option, } /// Build the `database` argument for a migration job. Both resource-backed and @@ -509,6 +528,127 @@ async fn hold_migration_lock( } } +/// The `_wm_migrations` rows of a database a schema-only copy is being made of, read with +/// [`lock_migration_runs_on`] held so they describe the schema the dump captured. +pub(crate) struct AppliedMigrations { + /// `None` when the source has no `_wm_migrations`. + schema: Option, + datatables: Vec, + versions: Vec, + installed_at: Vec, +} + +/// Hold the migration-run lock on database `pg`, for a copy whose schema has to agree with the +/// `_wm_migrations` rows it carries. The lock is per database, whichever data table names it. +pub(crate) async fn lock_migration_runs_on( + db: &DB, + pg: &PgDatabase, + label: &str, +) -> Result { + let (client, connection) = pg.connect(Some(db)).await?; + tokio::spawn(async move { + if let Err(e) = connection.await { + tracing::error!("Datatable connection error: {}", e); + } + }); + hold_migration_lock(&client, label, MIGRATION_LOCK_WAIT_SECS).await?; + Ok(client) +} + +/// Read every `_wm_migrations` row of the database `client` is connected to, along with the +/// schema the table is in: the copy is written to by a connection whose `search_path` need not +/// resolve the way this one does. +pub(crate) async fn read_applied_migrations( + client: &tokio_postgres::Client, +) -> Result { + let read_err = |e: tokio_postgres::Error| { + Error::internal_err(format!( + "Failed to read _wm_migrations: {}", + pg_error_message(&e) + )) + }; + let schema: Option = client + .query_one( + "SELECT n.nspname::text FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace \ + RIGHT JOIN (SELECT to_regclass('_wm_migrations')::oid AS oid) t ON c.oid = t.oid", + &[], + ) + .await + .map_err(read_err)? + .get(0); + let mut applied = + AppliedMigrations { schema, datatables: vec![], versions: vec![], installed_at: vec![] }; + let Some(schema) = applied.schema.as_deref() else { + return Ok(applied); + }; + let rows = client + .query( + &format!( + // ISO 8601 in UTC: `::text` follows the session's `DateStyle`, which the copy's + // session need not parse the same way. + "SELECT datatable, version, \ + to_char(installed_at AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US') \ + FROM {}._wm_migrations", + render_db_quoted_identifier(schema, DbType::Postgresql) + ), + &[], + ) + .await + .map_err(read_err)?; + for row in rows { + applied.datatables.push(row.get(0)); + applied.versions.push(row.get(1)); + applied.installed_at.push(row.get(2)); + } + Ok(applied) +} + +/// Write the rows [`read_applied_migrations`] read into a copy restored from a schema-only dump, +/// which brings `_wm_migrations` over empty: without them the copy reports every migration its +/// schema already holds as pending, and running them fails on objects that exist. +pub(crate) async fn write_applied_migrations( + db: &DB, + target: &PgDatabase, + applied: &AppliedMigrations, +) -> Result<()> { + let Some(schema) = applied.schema.as_deref() else { + return Ok(()); + }; + if applied.versions.is_empty() { + return Ok(()); + } + let (client, connection) = target.connect(Some(db)).await?; + tokio::spawn(async move { + if let Err(e) = connection.await { + tracing::error!("Datatable connection error: {}", e); + } + }); + client + .execute( + &format!( + "INSERT INTO {}._wm_migrations (datatable, version, installed_at) \ + SELECT d, v, i::timestamp AT TIME ZONE 'UTC' \ + FROM unnest($1::text[], $2::bigint[], $3::text[]) AS t(d, v, i) \ + ON CONFLICT DO NOTHING", + render_db_quoted_identifier(schema, DbType::Postgresql) + ), + &[ + &applied.datatables, + &applied.versions, + &applied.installed_at, + ], + ) + .await + .map_err(|e| { + Error::internal_err(format!( + "Failed to copy _wm_migrations into '{}': {}", + target.dbname, + pg_error_message(&e) + )) + })?; + Ok(()) +} + /// Whether `e` is the lock wait running out, as opposed to the database being unreachable. fn is_migration_lock_busy(e: &Error) -> bool { matches!(e, Error::Generic(StatusCode::CONFLICT, _)) @@ -541,7 +681,9 @@ async fn read_applied_versions_on_client( /// Each migration runs as a normal Windmill `postgresql` job (permissioned as /// the requester, labelled `datatable_migration`); applied versions are then /// recorded in the data table's own `_wm_migrations` table, so only migrations -/// not recorded there are run, in ascending `timestamp` order. +/// not recorded there are run, in ascending `timestamp` order. A run for one +/// schema is refused while an earlier migration its selection overlaps is pending +/// (see `datatable_migration_scope`). async fn run_datatable_migrations( authed: ApiAuthed, Extension(db): Extension, @@ -587,30 +729,29 @@ async fn run_datatable_migrations( let applied_versions = read_applied_versions_on_client(&client, &datatable_name).await?; + let selection = if let Some(only) = query.only { + RunSelection::Only(only) + } else if let Some(schema) = query.schema.as_deref() { + RunSelection::Schema(schema.to_ascii_lowercase()) + } else { + RunSelection::UpTo(query.up_to) + }; // How the user scoped the run, for the counter emitted on the first migration // that lands below. - let scope = if query.only.is_some() { - "only" - } else if query.up_to.is_some() { - "up_to" - } else { - "all" + let scope = match selection { + RunSelection::Only(_) => "only", + RunSelection::Schema(_) => "schema", + RunSelection::UpTo(Some(_)) => "up_to", + RunSelection::UpTo(None) => "all", }; + let chain: Vec = migrations + .iter() + .map(|m| ChainEntry::new(m.timestamp, m.name.clone(), &m.code_up)) + .collect(); + let plan = plan_run(&chain, &applied_versions, &selection)?; let mut applied = Vec::new(); - for m in migrations { - if let Some(only) = query.only { - // Run a single specific migration, skipping every other one. - if m.timestamp != only { - continue; - } - } else if query.up_to.is_some_and(|up_to| m.timestamp > up_to) { - // Migrations are ordered ascending, so once we pass `up_to` we're done. - break; - } - if applied_versions.contains(&m.timestamp) { - continue; - } + for m in plan.into_iter().map(|i| &migrations[i]) { ensure_migration_role_allowed( &db, &w_id, @@ -642,7 +783,7 @@ async fn run_datatable_migrations( pg_error_message(&e) )) })?; - applied.push(AppliedMigration { version: m.timestamp, name: m.name }); + applied.push(AppliedMigration { version: m.timestamp, name: m.name.clone() }); // One event per run that moved the data table forward, emitted on the // first migration that lands rather than after the loop: a later one // failing returns early, and that run still advanced the data table. A @@ -865,6 +1006,13 @@ struct DatatableMigrationWithStatus { #[serde(skip_serializing_if = "Option::is_none")] code_down: Option, status: DatatableMigrationRunStatus, + /// The schemas its `-- schemas` annotation declares; absent for the whole database. + #[serde(skip_serializing_if = "Option::is_none")] + schemas: Option>, + /// When not run: the earliest pending migration that has to be applied before it. When run: + /// the latest applied migration that has to be rolled back before it. + #[serde(skip_serializing_if = "Option::is_none")] + blocked_by: Option, } #[derive(Serialize)] @@ -880,7 +1028,11 @@ struct DatatableMigrationsStatusResult { /// Whether the SQL-migrations feature is enabled for a data table. Honors the /// explicit `migrations_enabled` flag; when unset (data tables predating the /// feature) it is considered enabled only if migrations already exist. -async fn datatable_migrations_enabled(db: &DB, w_id: &str, datatable_name: &str) -> Result { +pub(crate) async fn datatable_migrations_enabled( + db: &DB, + w_id: &str, + datatable_name: &str, +) -> Result { let flag: Option = sqlx::query_scalar!( "SELECT (ws.datatable->'datatables'->$2->>'migrations_enabled')::boolean \ FROM workspace_settings ws WHERE ws.workspace_id = $1", @@ -977,9 +1129,14 @@ async fn datatable_migrations_status( Err(e) => (None, Some(e.to_string())), }; + let chain: Vec = defs + .iter() + .map(|m| ChainEntry::new(m.timestamp, m.name.clone(), &m.code_up)) + .collect(); let migrations = defs .into_iter() - .map(|m| { + .enumerate() + .map(|(i, m)| { let status = match &applied { Some(set) if set.contains(&m.timestamp) => DatatableMigrationRunStatus::Ran, Some(_) => DatatableMigrationRunStatus::NotRun, @@ -991,6 +1148,11 @@ async fn datatable_migrations_status( code_up: m.code_up, code_down: m.code_down, status, + schemas: chain[i].scope.clone(), + blocked_by: applied + .as_ref() + .and_then(|set| blocked_by(&chain, set, i)) + .map(|j| chain[j].timestamp), } }) .collect(); @@ -1329,6 +1491,7 @@ async fn create_datatable_migration( ensure_not_operator(&authed)?; validate_datatable_path_segment(&datatable_name)?; validate_migration_name(&payload.name)?; + let scope = parse_migration_schemas(&payload.code_up)?; ensure_datatable_migrations_enabled(&db, &w_id, &datatable_name).await?; ensure_may_edit_migration( &db, @@ -1375,6 +1538,7 @@ async fn create_datatable_migration( .await?; windmill_common::feature_usage::log_feature_usage("datatable", "migration_created", "manual"); + log_migration_scope(&scope); Ok(Json(DatatableMigration { datatable: datatable_name, @@ -1577,6 +1741,16 @@ async fn upsert_datatable_migration( if unchanged { return Ok(upserted_message); } + // Only up SQL being written is held to the annotation: a stored up that opens with prose + // starting with the word `schemas` predates scopes, and must still accept a down added to it. + let up_changed = existing + .as_ref() + .is_none_or(|existing| existing.code_up != payload.code_up); + let scope = if up_changed { + parse_migration_schemas(&payload.code_up)? + } else { + None + }; ensure_may_edit_migration( &db, &w_id, @@ -1705,6 +1879,9 @@ async fn upsert_datatable_migration( "edited" }, ); + if existing.is_none() { + log_migration_scope(&scope); + } Ok(upserted_message) } diff --git a/backend/windmill-api-workspaces/src/lib.rs b/backend/windmill-api-workspaces/src/lib.rs index c437d7e2b4..8d37fdf194 100644 --- a/backend/windmill-api-workspaces/src/lib.rs +++ b/backend/windmill-api-workspaces/src/lib.rs @@ -4,6 +4,7 @@ pub mod data_metrics; pub mod datatable_acl; pub mod datatable_acl_oss; pub mod datatable_clone; +pub mod datatable_migration_scope; pub mod datatable_migrations; pub mod datatable_permissions; pub mod datatable_permissions_oss; diff --git a/backend/windmill-api-workspaces/src/remote_deploy.rs b/backend/windmill-api-workspaces/src/remote_deploy.rs index 3e701cbf14..a0f922a607 100644 --- a/backend/windmill-api-workspaces/src/remote_deploy.rs +++ b/backend/windmill-api-workspaces/src/remote_deploy.rs @@ -25,11 +25,11 @@ use axum::{ }; use chrono::{DateTime, Utc}; use lazy_static::lazy_static; -use magic_crypt::MagicCrypt256; use regex::Regex; use serde::{Deserialize, Serialize}; use windmill_api_auth::{is_effectively_unscoped, ApiAuthed, Tokened}; use windmill_audit::{audit_oss::audit_log, ActionKind}; +use windmill_common::variables::WorkspaceCrypt; use windmill_common::{ auth::hash_token, error::{error_source_chain, Error, Result}, @@ -676,8 +676,8 @@ async fn proxy( pub(crate) async fn reencrypt_tokens( conn: &mut sqlx::PgConnection, w_id: &str, - old: &MagicCrypt256, - new: &MagicCrypt256, + old: &WorkspaceCrypt, + new: &WorkspaceCrypt, ) -> Result<()> { let rows = sqlx::query!( "SELECT email, token FROM remote_deploy_token diff --git a/backend/windmill-api-workspaces/src/workspaces.rs b/backend/windmill-api-workspaces/src/workspaces.rs index efc108453d..eb00c4106d 100644 --- a/backend/windmill-api-workspaces/src/workspaces.rs +++ b/backend/windmill-api-workspaces/src/workspaces.rs @@ -515,6 +515,11 @@ struct CreateWorkspaceFork { /// fork namespace + read-defer. #[serde(default)] shared_ducklakes: Vec, + /// Workspace storages the fork reads and writes at the parent's keys (`_default_` for the + /// primary one). Every other storage is isolated: the fork writes under its own prefix + /// and reads through to the parent's objects. + #[serde(default)] + shared_storages: Vec, /// Create the fork as a persistent dev workspace: the id is not required to carry the /// `wm-fork-` prefix, and at most one dev workspace may exist per parent. #[serde(default)] @@ -1765,6 +1770,43 @@ async fn set_slack_oauth_config( "Both client ID and client secret are required".to_string(), )); } + // A settings.yaml pulled by `wmill sync` holds the secret encrypted, and a CLI that + // predates the settings document pushes it here as it reads it. One encrypted under another + // workspace's key keeps the stored secret, as the settings document does, so that CLI's push + // does not abort over it. + let mut req = req; + if let Some(ciphertext) = req + .slack_oauth_client_secret + .strip_prefix(windmill_common::variables::SETTINGS_ENCRYPTED_PREFIX) + { + match windmill_common::variables::build_crypt(&db, &w_id) + .await? + .decrypt_str(ciphertext) + { + Ok(plain) => req.slack_oauth_client_secret = plain, + Err(_) => { + let stored = sqlx::query_scalar!( + "SELECT slack_oauth_client_secret FROM workspace_settings WHERE workspace_id = $1", + &w_id + ) + .fetch_optional(&db) + .await? + .flatten(); + tracing::warn!( + workspace_id = %w_id, + "Slack client secret left unchanged: it is encrypted with another workspace's key" + ); + match stored { + Some(stored) => req.slack_oauth_client_secret = stored, + None => { + return Ok("Slack OAuth config left unchanged: the client secret is \ + encrypted with another workspace's key" + .to_string()) + } + } + } + } + } let mut tx = db.begin().await?; @@ -2094,6 +2136,38 @@ async fn edit_dbt_warehouses( Ok("Updated the workspace's dbt warehouses".to_string()) } +/// A fork's isolated storage is purged at deletion from the storage recorded at creation: under +/// another location, its objects would outlive the fork untracked, and a same-id fork would +/// read them. +async fn reject_isolated_storage_repoint( + tx: &mut Transaction<'_, Postgres>, + w_id: &str, + new_lfs: &serde_json::Value, +) -> Result<()> { + let rows = sqlx::query!( + "SELECT storage, storage_ref FROM fork_storage_namespace WHERE workspace_id = $1", + w_id + ) + .fetch_all(&mut **tx) + .await?; + for row in rows { + let new_ref = windmill_common::fork_storage::lfs_entry(new_lfs, &row.storage) + .and_then(windmill_common::workspaces::lfs_entry_storage_ref); + if new_ref.is_some_and(|r| r != row.storage_ref) { + let name = if row.storage.is_empty() { + windmill_types::s3::DEFAULT_STORAGE + } else { + row.storage.as_str() + }; + return Err(Error::BadRequest(format!( + "storage `{name}` is isolated from the parent in this fork, so where it points \ + cannot be changed" + ))); + } + } + Ok(()) +} + async fn edit_large_file_storage_config( authed: ApiAuthed, Extension(db): Extension, @@ -2131,6 +2205,15 @@ async fn edit_large_file_storage_config( windmill_types::s3::DEFAULT_STORAGE ))); } + if lfs_config + .secondary_storage + .contains_key(windmill_types::s3::BUCKET_ADDRESSED_SEGMENT) + { + return Err(Error::BadRequest(format!( + "`{}` is reserved by the S3 proxy and cannot name a secondary storage", + windmill_types::s3::BUCKET_ADDRESSED_SEGMENT + ))); + } if !windmill_common::workspaces::filesystem_storage_allowed() { let named = std::iter::once(("primary storage", &lfs_config.large_file_storage)).chain( @@ -2152,6 +2235,7 @@ async fn edit_large_file_storage_config( let serialized_lfs_config = serde_json::to_value::(lfs_config) .map_err(|err| Error::internal_err(err.to_string()))?; + reject_isolated_storage_repoint(&mut tx, &w_id, &serialized_lfs_config).await?; // A workspace whose AI session backups fell back to the instance store leaves it // here: the generation moves on, so nothing it left in any instance store is read @@ -2248,6 +2332,9 @@ struct DataTableListItem { /// at its parent. Its permissions apply here, and only its admins may edit them. #[serde(skip_serializing_if = "Option::is_none")] governing_workspace_id: Option, + /// The workspace owning the database this entry points at, when it is not this workspace. + #[serde(skip_serializing_if = "Option::is_none")] + database_workspace_id: Option, /// Whether the governing entry is under roles. permissioned: bool, } @@ -2277,6 +2364,8 @@ async fn list_datatables( resource_path: database.resource_path.clone(), governing_workspace_id: (governing.governing_workspace_id() != w_id) .then(|| governing.governing_workspace_id().to_string()), + database_workspace_id: (governing.workspace_id != w_id) + .then(|| governing.workspace_id.clone()), permissioned: governing.datatable.permissions.is_some(), }); } @@ -2325,6 +2414,9 @@ struct DataTableTables { /// What the role the listing connected as may create. can_create_schema: bool, creatable_schemas: Vec, + /// Whether its schema is kept as versioned migrations, which a change made with plain SQL + /// would bypass. + migrations_enabled: bool, } #[derive(Deserialize)] @@ -2570,8 +2662,17 @@ async fn list_one_datatable_tables( default_role: windmill_common::datatable_roles::ADMIN_DATATABLE_ROLE.to_string(), can_create_schema: false, creatable_schemas: vec![], + migrations_enabled: false, }; let result: Result<()> = async { + // Read from the workspace settings alone, so it is known even when the database is not + // reachable. + entry.migrations_enabled = crate::datatable_migrations::datatable_migrations_enabled( + db, + w_id, + &entry.datatable_name, + ) + .await?; let governing = resolve_governing_datatable(db, w_id, &entry.datatable_name).await?; entry.instance = governing.role_cluster().is_some(); let usable = @@ -3582,6 +3683,97 @@ pub(crate) async fn pg_import_dump(target_db: &PgDatabase, dump_file: &DumpFile) Ok(()) } +/// Carry the source database's own settings (`ALTER DATABASE ... SET`) over to a copy. `pg_dump` +/// only emits them with `--create`, so a copy otherwise resolves unqualified names, its +/// `_wm_migrations` included, through the server's default `search_path` rather than the source's. +/// A setting the copy's connection may not set is skipped with a warning rather than failing it. +/// Called once nothing else writes to the copy, which a copied read-only default would refuse. +pub(crate) async fn copy_database_settings( + db: &DB, + source: &PgDatabase, + target: &PgDatabase, +) -> Result<()> { + let (source_client, connection) = source.connect(Some(db)).await?; + tokio::spawn(async move { + if let Err(e) = connection.await { + tracing::error!("Datatable connection error: {}", e); + } + }); + let settings: Vec = source_client + .query( + "SELECT unnest(setconfig) FROM pg_db_role_setting WHERE setrole = 0 \ + AND setdatabase = (SELECT oid FROM pg_database WHERE datname = current_database())", + &[], + ) + .await + .map_err(|e| { + Error::internal_err(format!( + "Failed to read the settings of database '{}': {}", + source.dbname, + pg_error_message(&e) + )) + })? + .iter() + .map(|row| row.get(0)) + .collect(); + drop(source_client); + if settings.is_empty() { + return Ok(()); + } + + let (mut client, connection) = target.connect(Some(db)).await?; + tokio::spawn(async move { + if let Err(e) = connection.await { + tracing::error!("Datatable connection error: {}", e); + } + }); + let quoted_db = render_db_quoted_identifier(&target.dbname, DbType::Postgresql); + for setting in settings { + let Some((name, value)) = setting.split_once('=') else { + continue; + }; + if name.is_empty() + || !name + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.') + { + tracing::warn!( + "Not copying database setting '{name}' to '{}'", + target.dbname + ); + continue; + } + let quoted_name = name + .split('.') + .map(|part| render_db_quoted_identifier(part, DbType::Postgresql)) + .collect::>() + .join("."); + // `FROM CURRENT` takes the value in the stored text form, which `SET name TO value` would + // need re-quoted per setting type. Set transaction-locally: a session-wide `role` or + // `default_transaction_read_only` would make every later `ALTER DATABASE` fail. + let applied = async { + let tx = client.transaction().await?; + tx.execute("SELECT set_config($1, $2, true)", &[&name, &value]) + .await?; + tx.batch_execute(&format!( + "ALTER DATABASE {quoted_db} SET {quoted_name} FROM CURRENT" + )) + .await?; + tx.commit().await + } + .await; + if let Err(e) = applied { + tracing::warn!( + "Could not copy setting '{name}' of database '{}' to '{}': {}", + source.dbname, + target.dbname, + pg_error_message(&e) + ); + } + } + Ok(()) +} + #[derive(Deserialize)] struct CreatePgDatabaseRequest { /// The datatable source to determine connection info: 'datatable://name' or '$res:path' @@ -3845,12 +4037,33 @@ async fn import_pg_database( // the ACLs are user intent (`REVOKE ... FROM PUBLIC`) and dropping them widens access. let no_acl = target_kind.is_some() || source_kind.is_some(); + // Only a database made to be a copy takes on the source's bookkeeping and settings: without an + // override the target is a data table's own live database, whose settings are its owner's. + let fresh_copy = req.target_dbname_override.is_some(); + let migrations_lock = if schema_only && fresh_copy { + Some( + crate::datatable_migrations::lock_migration_runs_on(&db, &source_pg, &req.source) + .await?, + ) + } else { + None + }; let dump_file = pg_dump_database( &source_pg, PgDumpOptions { schema_only, no_owner: true, no_acl, ..Default::default() }, ) .await?; + let applied = match migrations_lock { + Some(client) => Some(crate::datatable_migrations::read_applied_migrations(&client).await?), + None => None, + }; pg_import_dump(&target_pg, &dump_file).await?; + if let Some(applied) = applied { + crate::datatable_migrations::write_applied_migrations(&db, &target_pg, &applied).await?; + } + if fresh_copy { + copy_database_settings(&db, &source_pg, &target_pg).await?; + } if let Some(tx) = fork_lock { tx.commit().await?; } @@ -6317,8 +6530,8 @@ async fn set_encryption_key( async fn reencrypt_git_sync_secrets( conn: &mut sqlx::PgConnection, w_id: &str, - old: &magic_crypt::MagicCrypt256, - new: &magic_crypt::MagicCrypt256, + old: &windmill_common::variables::WorkspaceCrypt, + new: &windmill_common::variables::WorkspaceCrypt, ) -> Result<()> { let Some((mut credentials, mut git_sync)) = sqlx::query_as::<_, (serde_json::Value, Option)>( @@ -6969,7 +7182,7 @@ async fn clone_workspace_data( clone_resource_types(tx, source_workspace_id, target_workspace_id).await?; // Clone resources - clone_resources(tx, source_workspace_id, target_workspace_id).await?; + clone_resources(tx, source_workspace_id, target_workspace_id, authed).await?; // Clone variables (including external secret backend replication) clone_variables(tx, db, source_workspace_id, target_workspace_id).await?; @@ -7506,18 +7719,30 @@ async fn clone_resource_types( Ok(()) } +/// An agent's value carries the identity it runs as, re-pointed at the fork's creator when they +/// may not preserve someone else's, as `clone_apps` does an app's policy. The rest is swept by +/// `repoint_unresolvable_cloned_identities` once the fork's membership is final. async fn clone_resources( tx: &mut Transaction<'_, Postgres>, source_workspace_id: &str, target_workspace_id: &str, + authed: &ApiAuthed, ) -> Result<()> { + let repoint = (!windmill_common::can_preserve_on_behalf_of(authed)) + .then(|| username_to_permissioned_as(&authed.username)); sqlx::query!( "INSERT INTO resource (workspace_id, path, value, description, resource_type, extra_perms, edited_at, created_by) - SELECT $2, path, value, description, resource_type, extra_perms, edited_at, created_by + SELECT $2, path, + CASE WHEN $3::text IS NOT NULL AND resource_type = 'ai_agent' + AND jsonb_typeof(value) = 'object' AND value ? 'on_behalf_of' + THEN jsonb_set(value, '{on_behalf_of}', to_jsonb($3::text)) + ELSE value END, + description, resource_type, extra_perms, edited_at, created_by FROM resource WHERE workspace_id = $1", source_workspace_id, target_workspace_id, + repoint, ) .execute(&mut **tx) .await?; @@ -8004,6 +8229,18 @@ async fn repoint_unresolvable_cloned_identities( .await?; } + sqlx::query(&format!( + "UPDATE resource SET value = jsonb_set(value, '{{on_behalf_of}}', to_jsonb($2::text)) + WHERE workspace_id = $1 AND resource_type = 'ai_agent' + AND jsonb_typeof(value) = 'object' AND value ? 'on_behalf_of' + AND NOT ({})", + principal_resolves_sql("(value->>'on_behalf_of')") + )) + .bind(target_workspace_id) + .bind(&principal) + .execute(&mut **tx) + .await?; + // `email` is still written for workers that predate `permissioned_as`. sqlx::query(&format!( "UPDATE schedule SET permissioned_as = $2, email = $3 @@ -8386,7 +8623,7 @@ async fn clone_apps( // Clone app scripts with recomputed hashes let app_scripts = sqlx::query!( - "SELECT app, hash, lock, code, code_sha256 + "SELECT id, app, hash, lock, code, code_sha256, modules FROM app_script WHERE app = ANY(SELECT id FROM app WHERE workspace_id = $1)", source_workspace_id @@ -8394,34 +8631,104 @@ async fn clone_apps( .fetch_all(&mut **tx) .await?; + let mut app_script_id_mapping: HashMap = HashMap::new(); for app_script in app_scripts { if let Some(&new_app_id) = app_id_mapping.get(&app_script.app) { - // Recompute hash using app_id, code_sha256, and lock + // Recompute hash using app_id, code_sha256, lock and modules let mut hasher = Sha256::new(); hasher.update(new_app_id.to_be_bytes()); hasher.update(hex::decode(&app_script.code_sha256)?); if let Some(lock) = &app_script.lock { hasher.update(lock.as_bytes()); } + if let Some(modules) = &app_script.modules { + hasher.update(modules.to_string()); + } let new_hash = hex::encode(hasher.finalize()); - sqlx::query!( - "INSERT INTO app_script (app, hash, lock, code, code_sha256) - VALUES ($1, $2, $3, $4, $5) ON CONFLICT DO NOTHING", + let new_id = sqlx::query_scalar!( + "INSERT INTO app_script (app, hash, lock, code, code_sha256, modules) + VALUES ($1, $2, $3, $4, $5, $6) + ON CONFLICT (hash) DO UPDATE SET app = EXCLUDED.app -- trivial update to return the id + RETURNING id", new_app_id, new_hash, app_script.lock, app_script.code, app_script.code_sha256, + app_script.modules, ) - .execute(&mut **tx) + .fetch_one(&mut **tx) .await?; + app_script_id_mapping.insert(app_script.id, new_id); } } + // A version's lite value is what points each inline script at its `app_script` row (lock and + // modules). Without it the fork serves the full value, whose inline scripts carry no id and + // so run as bare code: no lock, and no modules for a raw app's sibling imports. Every + // version, not just `versions.last()`: the fork's `versions` is rebuilt from all rows above, + // so its current one can be a row the parent's array never listed. + let source_versions: Vec = version_id_mapping.keys().copied().collect(); + let lite_versions = sqlx::query!( + "SELECT id, value AS \"value!: serde_json::Value\" FROM app_version_lite WHERE id = ANY($1)", + &source_versions, + ) + .fetch_all(&mut **tx) + .await?; + let (mut lite_ids, mut lite_values) = (vec![], vec![]); + for lite in lite_versions { + let Some(&new_version_id) = version_id_mapping.get(&lite.id) else { + continue; + }; + let mut value = lite.value; + // Lite inline scripts have no code of their own, so one left without a row cannot run. + if !remap_app_script_ids(&mut value, &app_script_id_mapping) { + continue; + } + if let Some(object) = value.as_object_mut() { + object.insert("version".to_string(), serde_json::json!(new_version_id)); + } + lite_ids.push(new_version_id); + lite_values.push(value); + } + sqlx::query!( + "INSERT INTO app_version_lite (id, value) + SELECT * FROM UNNEST($1::bigint[], $2::jsonb[]) + ON CONFLICT (id) DO NOTHING", + &lite_ids, + &lite_values, + ) + .execute(&mut **tx) + .await?; + Ok(app_id_mapping) } +/// Points every `inlineScript.id` of a cloned lite app value at the fork's copy of that row. +/// False when some id has no copy. +fn remap_app_script_ids(value: &mut serde_json::Value, mapping: &HashMap) -> bool { + match value { + serde_json::Value::Object(object) => { + if let Some(serde_json::Value::Object(script)) = object.get_mut("inlineScript") { + if let Some(old_id) = script.get("id").and_then(serde_json::Value::as_i64) { + let Some(new_id) = mapping.get(&old_id) else { + return false; + }; + script.insert("id".to_string(), serde_json::json!(new_id)); + } + } + object + .values_mut() + .all(|child| remap_app_script_ids(child, mapping)) + } + serde_json::Value::Array(array) => array + .iter_mut() + .all(|child| remap_app_script_ids(child, mapping)), + _ => true, + } +} + async fn clone_raw_apps( tx: &mut Transaction<'_, Postgres>, source_workspace_id: &str, @@ -8595,6 +8902,7 @@ async fn create_workspace_fork_branch( { return Err(Error::PermissionDenied(msg)); } + enforce_isolated_forks(&db, &authed, &w_id, &nw).await?; // Two-phase create for git-synced workspaces: this endpoint only creates the git branch(es) and // validates up front; it does NOT create the workspace row. The caller follows up with @@ -8804,11 +9112,12 @@ async fn apply_forked_datatable( fdt: &ForkedDatatableInfo, copy: &crate::datatable_clone::MadeCopy, ) -> Result<()> { - windmill_common::validate_dbname(&fdt.new_dbname)?; - if !fdt.new_dbname.starts_with("wm_fork_") { + // Not `fdt.new_dbname`: a data table sharing its database with an earlier one shares its copy. + let dbname = copy.dbname.as_str(); + windmill_common::validate_dbname(dbname)?; + if !dbname.starts_with("wm_fork_") { return Err(Error::BadRequest(format!( - "Forked datatable database name '{}' must start with 'wm_fork_'", - fdt.new_dbname + "Forked datatable database name '{dbname}' must start with 'wm_fork_'" ))); } // Held until the fork commits, as the permissions save holds them: the source moved onto @@ -8897,27 +9206,27 @@ async fn apply_forked_datatable( if database.resource_type == DataTableCatalogResourceType::ExternalInstance { windmill_common::external_instance_pg::ensure_external_instance_database_registered( - tx, - &fdt.new_dbname, + tx, dbname, ) .await?; } if database.resource_type.is_windmill_managed() { // Held until the fork commits, as every save newly naming a database takes it: none may // claim the copy between the check below and this fork's entry landing on it. - windmill_common::datatable_roles::lock_instance_databases_governance( - &mut **tx, - [fdt.new_dbname.as_str()], - ) - .await?; + windmill_common::datatable_roles::lock_instance_databases_governance(&mut **tx, [dbname]) + .await?; } + // The data tables after the first on a shared copy find it named by the first, and the + // resource it is reached through already pointed at it. + let first_on_copy = copy.names.first() == Some(&fdt.name); if database.resource_type.is_windmill_managed() + && first_on_copy && !windmill_api_auth::is_super_admin_authed(db, authed).await? { windmill_common::ensure_fork_database_available_to( &mut **tx, database.resource_type, - &fdt.new_dbname, + dbname, parent_w_id, ) .await?; @@ -8928,7 +9237,7 @@ async fn apply_forked_datatable( // on the same cluster as its source, so it keeps the source's kind. let new_database = serde_json::json!({ "resource_type": database.resource_type, - "resource_path": &fdt.new_dbname, + "resource_path": dbname, }); sqlx::query( r#"UPDATE workspace_settings @@ -8942,7 +9251,7 @@ async fn apply_forked_datatable( .bind(new_database) .execute(&mut **tx) .await?; - } else { + } else if first_on_copy { // Resource: point it at the copy and mark it ws_specific. What the settings clone carried is // the source's resource and variables as they are now, which an edit made while the copy // was being made can have changed, and changed back: the clone has to be what the copy's @@ -8965,7 +9274,7 @@ async fn apply_forked_datatable( ) .bind(forked_w_id) .bind(resource_path) - .bind(&fdt.new_dbname) + .bind(dbname) .execute(&mut **tx) .await?; @@ -9306,6 +9615,25 @@ async fn create_workspace_fork( i.msg ); } + // Unlike a dropped lake's files, a deleted fork's objects are live to a same-id fork: it + // reads its own prefix first. + let leftover_storages = crate::workspaces_extra::prepare_fork_storage_purges( + &db, + &nw.id, + Some(&parent_workspace_id), + ) + .await?; + let storage_issues = + crate::workspaces_extra::purge_fork_storages_unless_live(&db, &nw.id, leftover_storages) + .await?; + if !storage_issues.is_empty() { + return Err(Error::BadRequest(format!( + "a previously deleted workspace with id '{}' left objects in its fork prefix that \ + could not be deleted: {}; retry once the storage is reachable again", + nw.id, + storage_issues.join("; ") + ))); + } #[cfg(not(feature = "enterprise"))] _check_nb_of_workspaces(&db).await?; @@ -9325,6 +9653,7 @@ async fn create_workspace_fork( { return Err(Error::PermissionDenied(msg)); } + enforce_isolated_forks(&db, &authed, &parent_workspace_id, &nw).await?; if nw.is_dev_workspace { ensure_dev_parent_can_host_dev(&db, &parent_workspace_id).await?; @@ -9699,6 +10028,185 @@ fn copy_requests( .collect() } +/// Under `RequireIsolatedForks` on `parent`, refuse a fork that would leave any of its data +/// shared: a shared storage or lake, or a data table not cloned (`Keep original` points the fork +/// at the parent's database). +async fn enforce_isolated_forks( + db: &DB, + authed: &ApiAuthed, + parent: &str, + nw: &CreateWorkspaceFork, +) -> Result<()> { + let Some(msg) = isolation_required(db, authed, parent).await? else { + return Ok(()); + }; + let mut shared: Vec = nw + .shared_storages + .iter() + .map(|s| format!("storage `{s}`")) + .chain( + nw.shared_ducklakes + .iter() + .map(|l| format!("ducklake `{l}`")), + ) + .collect(); + shared.extend( + kept_parent_datatables(db, parent, &nw.forked_datatables) + .await? + .into_iter() + .map(|name| format!("data table `{name}`")), + ); + refuse_shared(msg, shared) +} + +/// The rule's message when `RequireIsolatedForks` on `parent` binds `authed`. +async fn isolation_required(db: &DB, authed: &ApiAuthed, parent: &str) -> Result> { + match check_user_against_rule( + parent, + &ProtectionRuleKind::RequireIsolatedForks, + AuditAuthorable::username(authed), + &authed.groups, + authed.is_admin, + db, + ) + .await? + { + RuleCheckResult::Blocked(msg) => Ok(Some(msg)), + RuleCheckResult::Allowed => Ok(None), + } +} + +/// `parent`'s own data tables that `forked` leaves as pointers at its database. An entry whose +/// database another workspace owns is not `parent`'s data, so the rule does not cover it. +async fn kept_parent_datatables( + db: &DB, + parent: &str, + forked: &[ForkedDatatableInfo], +) -> Result> { + Ok( + windmill_common::workspaces::resolve_workspace_governing_datatables(db, parent) + .await? + .into_iter() + .filter(|(_, governing)| governing.workspace_id == parent) + .filter(|(name, _)| { + !forked.iter().any(|d| { + &d.name == name + && matches!( + d.fork_behavior, + Some( + DataTableForkBehavior::SchemaOnly + | DataTableForkBehavior::SchemaAndData + ) + ) + }) + }) + .map(|(name, _)| name) + .collect(), + ) +} + +fn refuse_shared(msg: String, shared: Vec) -> Result<()> { + if shared.is_empty() { + return Ok(()); + } + Err(Error::PermissionDenied(format!( + "{msg}. Shared in this request: {}. Only a bypasser of the rule can fork while one of \ + them cannot be isolated", + shared.join(", ") + ))) +} + +/// Record every storage of the fork's cloned settings as isolated, except `shared` ones. +/// Isolation is a per-fork-creation choice, never inherited: a fork of a shared fork is +/// isolated unless it asks otherwise. +async fn isolate_fork_storages( + tx: &mut Transaction<'_, Postgres>, + fork_id: &str, + shared: &[String], + shared_ducklakes: &[String], +) -> Result<()> { + use windmill_common::fork_storage::{lfs_entry, registry_storage_name}; + + let settings = sqlx::query!( + "SELECT large_file_storage, ducklake FROM workspace_settings WHERE workspace_id = $1", + fork_id + ) + .fetch_optional(&mut **tx) + .await?; + let (lfs, ducklake) = settings + .map(|s| (s.large_file_storage, s.ducklake)) + .unwrap_or_default(); + let lfs = lfs.filter(|v| v.get("type").is_some()); + + // A shared lake keeps the parent's data path: its files must land at the parent's keys, or + // the parent's catalog would point at objects in the fork's prefix, purged with the fork. + if lfs.is_some() { + for lake in shared_ducklakes { + let lake_storage = ducklake + .as_ref() + .and_then(|d| { + d.get("ducklakes")? + .get(lake)? + .get("storage")? + .get("storage") + }) + .and_then(|s| s.as_str()); + let storage = registry_storage_name(lake_storage); + if !shared + .iter() + .any(|s| registry_storage_name(Some(s)) == storage) + { + return Err(Error::BadRequest(format!( + "ducklake `{lake}` is shared with the parent, so the storage holding its \ + data (`{}`) must be shared too", + lake_storage.unwrap_or(windmill_types::s3::DEFAULT_STORAGE) + ))); + } + } + } + let mut storages: Vec<&str> = vec![]; + if let Some(lfs) = &lfs { + storages.push(""); + if let Some(secondary) = lfs.get("secondary_storage").and_then(|s| s.as_object()) { + storages.extend(secondary.keys().map(String::as_str)); + } + } + for name in shared { + if !storages.contains(®istry_storage_name(Some(name))) { + return Err(Error::BadRequest(format!( + "cannot share storage `{name}` with the parent: no such storage in the workspace \ + settings" + ))); + } + } + let Some(lfs) = &lfs else { + return Ok(()); + }; + for storage in storages { + if shared + .iter() + .any(|s| registry_storage_name(Some(s)) == storage) + { + continue; + } + let Some(storage_ref) = + lfs_entry(lfs, storage).and_then(windmill_common::workspaces::lfs_entry_storage_ref) + else { + continue; + }; + sqlx::query!( + "INSERT INTO fork_storage_namespace (workspace_id, storage, storage_ref) + VALUES ($1, $2, $3)", + fork_id, + storage, + storage_ref + ) + .execute(&mut **tx) + .await?; + } + Ok(()) +} + /// Write the fork, with its data tables pointed at `copies`. async fn write_workspace_fork( db: DB, @@ -9721,6 +10229,17 @@ async fn write_workspace_fork( // Also before the external cluster's lifecycle lock, which finalizing an external copy takes: // fork cleanup takes the two in this order. windmill_common::workspaces::lock_fork_datatables(&mut tx, &parent_workspace_id).await?; + // Data table edits take the lock above: one committed since the creation check would reach + // this fork as a pointer at the parent's database. + if let Some(msg) = isolation_required(&db, &authed, &parent_workspace_id).await? { + let kept = kept_parent_datatables(&db, &parent_workspace_id, &nw.forked_datatables).await?; + refuse_shared( + msg, + kept.into_iter() + .map(|name| format!("data table `{name}`")) + .collect(), + )?; + } if nw.is_dev_workspace { // The checks above ran outside a transaction, so the parent's eligibility and the chain's @@ -9902,9 +10421,12 @@ async fn write_workspace_fork( // Update forked datatable settings to point to new databases for fdt in &nw.forked_datatables { - let copy = copies.iter().find(|c| c.name == fdt.name).ok_or_else(|| { - Error::internal_err(format!("No copy was made of data table '{}'", fdt.name)) - })?; + let copy = copies + .iter() + .find(|c| c.names.contains(&fdt.name)) + .ok_or_else(|| { + Error::internal_err(format!("No copy was made of data table '{}'", fdt.name)) + })?; apply_forked_datatable( &db, &mut tx, @@ -9961,6 +10483,14 @@ async fn write_workspace_fork( } } + isolate_fork_storages( + &mut tx, + &forked_id, + &nw.shared_storages, + &nw.shared_ducklakes, + ) + .await?; + // Lock the parent ("prod") so edits are funneled through this dev workspace. let locked_prod = nw.is_dev_workspace && (nw.lock_prod_deploy || nw.lock_prod_forking); if locked_prod { @@ -9978,7 +10508,7 @@ async fn write_workspace_fork( .map(|c| { format!( "{} ({})", - c.name, + c.names.join(" + "), match c.behavior { DataTableForkBehavior::SchemaOnly => "schema_only", _ => "schema_and_data", @@ -10008,6 +10538,9 @@ async fn write_workspace_fork( .await?; } tx.commit().await?; + // Same for a mapping cached before the isolation rows were visible: identity, writing the + // root's keys. + windmill_common::fork_storage::invalidate_fork_storage_keys_cache(&forked_id); // A pre-creation lookup could have cached an EMPTY ancestor chain for this id, which // would bypass ducklake fork isolation for the TTL. The same lookup could have cached the id @@ -10724,20 +11257,10 @@ async fn archive_workspace( if let Some(prod) = dev_lock_parent { windmill_common::workspaces::invalidate_protection_rules_cache(&prod); - // The teardown above cleared `is_dev_workspace`, which is what let this workspace keep its - // own id for tag routing; it and every fork resolving through it now land on an ancestor. - // Only a dev workspace reaches here, so archiving anything else needs no sweep. - windmill_queue::tags::invalidate_fork_parent_cache(&w_id); - for id in windmill_common::workspaces::list_fork_descendants(&db, &w_id) - .await - .unwrap_or_default() - { - windmill_queue::tags::invalidate_fork_parent_cache(&id); - } - if let Err(e) = windmill_queue::tags::notify_fork_lineage_reset(&db).await { - tracing::warn!("failed to broadcast fork lineage change: {e:#}"); - } } + // The tag lineage reads `deleted` (an archived ancestor counts as dev lineage), and a dev + // workspace's teardown above also cleared `is_dev_workspace`. + reset_tag_lineage(&db, &w_id).await; Ok(format!( "Archived workspace {}, disabled {} schedules, canceled {} jobs and deleted {} tokens", @@ -10838,10 +11361,26 @@ async fn unarchive_workspace( ) .await?; tx.commit().await?; + reset_tag_lineage(&db, &w_id).await; Ok(format!("Unarchived workspace {}", &w_id)) } +/// Drops the tag lineage cached for `w_id` and every fork resolving through it, here and on every +/// replica, after a change to a field the lineage reads. +async fn reset_tag_lineage(db: &DB, w_id: &str) { + windmill_queue::tags::invalidate_fork_parent_cache(w_id); + for id in windmill_common::workspaces::list_fork_descendants(db, w_id) + .await + .unwrap_or_default() + { + windmill_queue::tags::invalidate_fork_parent_cache(&id); + } + if let Err(e) = windmill_queue::tags::notify_fork_lineage_reset(db).await { + tracing::warn!("failed to broadcast fork lineage change: {e:#}"); + } +} + /// Whether the instance is configured to suppress the email notifications sent /// when a user is invited or added to a workspace. Defaults to false (emails on). async fn workspace_invite_emails_disabled(db: &DB) -> Result { @@ -11608,10 +12147,13 @@ struct ChangeOperatorSettings { /// withdraw or grant the right on every push. /// /// `builder_flows` lets every operator of this workspace compose flows out of already-deployed - /// runnables, and makes each of them consume a full author seat instead of half of one. + /// runnables, `builder_apps` full-code apps. Either makes each operator consume a full author + /// seat instead of half of one. #[serde(default, skip_serializing_if = "Option::is_none")] builder_flows: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + builder_apps: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] manage_schedules: Option, #[serde(default, skip_serializing_if = "Option::is_none")] manage_triggers: Option, @@ -11626,9 +12168,10 @@ async fn update_operator_settings( require_admin(authed.is_admin, &authed.username)?; // Every operator of the workspace turns into a full seat, which an offline license may not - // cover. It is a no-op delta when the right is already on. + // cover. Either right costs the same seat, so this prices "any", and it is a no-op delta when + // one of them is already on. #[cfg(feature = "enterprise")] - if settings.builder_flows == Some(true) { + if settings.builder_flows == Some(true) || settings.builder_apps == Some(true) { if let Some(msg) = windmill_common::ee_oss::check_seat_cap_for_operator_builder(&db, &w_id).await? { @@ -13702,17 +14245,18 @@ async fn compare_two_flows( }); } -/// The policy minus the identity pair. Deploying cannot converge a difference there — the -/// target recomputes the identity from the deployer's own choice, which offers its current -/// value, the deployer, or a typed-in one, never the source's — so listing an app for it -/// alone leaves an entry no deploy can clear. `script` and `flow` compare no identity either. -fn policy_without_identity(policy: &serde_json::Value) -> serde_json::Value { - let mut policy = policy.clone(); - if let Some(obj) = policy.as_object_mut() { +/// An app's policy or an agent's value minus the identity it carries. Deploying cannot converge +/// a difference there — the target recomputes the identity from the deployer's own choice, which +/// offers its current value, the deployer, or a typed-in one, never the source's — so listing an +/// item for it alone leaves an entry no deploy can clear. `script` and `flow` compare no identity +/// either. +fn without_identity(value: &serde_json::Value) -> serde_json::Value { + let mut value = value.clone(); + if let Some(obj) = value.as_object_mut() { obj.remove("on_behalf_of"); obj.remove("on_behalf_of_email"); } - policy + value } async fn compare_two_apps( @@ -13755,7 +14299,7 @@ async fn compare_two_apps( // Check metadata and content differences if let (Some(source), Some(target)) = (&source_app, &target_app) { if source.summary != target.summary - || policy_without_identity(&source.policy) != policy_without_identity(&target.policy) + || without_identity(&source.policy) != without_identity(&target.policy) || source.value != target.value || source.raw_app != target.raw_app { @@ -13833,7 +14377,14 @@ async fn compare_two_resources( // Check metadata differences if let (Some(source), Some(target)) = (&source_resource, &target_resource) { - if source.value != target.value + let agent = source.resource_type == "ai_agent" && target.resource_type == "ai_agent"; + let values_differ = if agent { + source.value.as_ref().map(without_identity) + != target.value.as_ref().map(without_identity) + } else { + source.value != target.value + }; + if values_differ || source.description != target.description || source.resource_type != target.resource_type { @@ -14720,3 +15271,154 @@ async fn set_ws_specific( body.value, body.item_kind, body.path )) } + +/// A setting the workspace settings document writes, each through the endpoint that owns it, +/// so applying a document validates, audits and has the side effects of the matching UI save. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SettingsEdit { + Webhook, + AutoInvite, + InstanceGroups, + ErrorHandler, + SuccessHandler, + LargeFileStorage, + GitSync, + DefaultScripts, + DefaultApp, + Color, + OperatorSettings, + Datatable, + SlackCommand, + SetSlackOAuth, + DeleteSlackOAuth, + Ducklake, + DbtWarehouses, + DeployUi, + GuestAccess, + GuestJwtKey, + PublicAppRateLimit, + AddAdminsAndDevelopersToForks, + /// Body: `{ datatable, permissioned, default_role, roles: [{ id, tenants }] }`, role ids. + DatatablePermissions, + CreateProtectionRule, + /// Body: the update request plus `rule_name`, the rule it updates. + UpdateProtectionRule, + /// Body: `{ name }`. + DeleteProtectionRule, +} + +fn settings_edit_body( + edit: SettingsEdit, + body: serde_json::Value, +) -> Result> { + serde_json::from_value(body) + .map(Json) + .map_err(|e| Error::BadRequest(format!("Invalid value for {edit:?}: {e}"))) +} + +/// Returns the endpoint's JSON response, or `null` for one that answers with prose. +pub async fn apply_settings_edit( + authed: ApiAuthed, + db: DB, + w_id: String, + edit: SettingsEdit, + body: serde_json::Value, +) -> Result { + use SettingsEdit::*; + let a = authed.clone(); + let (d, p) = (Extension(db), Path(w_id)); + match edit { + Webhook => edit_webhook(a, d, p, authed, settings_edit_body(edit, body)?).await?, + AutoInvite => edit_auto_invite(a, d, p, settings_edit_body(edit, body)?).await?, + InstanceGroups => edit_instance_groups(a, d, p, settings_edit_body(edit, body)?).await?, + ErrorHandler => { + edit_error_handler(a, d, p, authed, settings_edit_body(edit, body)?).await? + } + SuccessHandler => edit_success_handler(a, d, p, settings_edit_body(edit, body)?).await?, + LargeFileStorage => { + edit_large_file_storage_config(a, d, p, authed, settings_edit_body(edit, body)?).await? + } + GitSync => edit_git_sync_config(a, d, p, authed, settings_edit_body(edit, body)?).await?, + DefaultScripts => { + edit_default_scripts(a, d, p, authed, settings_edit_body(edit, body)?).await? + } + #[cfg(feature = "enterprise")] + DefaultApp => edit_default_app(a, d, p, authed, settings_edit_body(edit, body)?).await?, + #[cfg(not(feature = "enterprise"))] + DefaultApp => edit_default_app(a, d, p, settings_edit_body(edit, body)?).await?, + Color => change_workspace_color(a, p, d, settings_edit_body(edit, body)?).await?, + OperatorSettings => { + update_operator_settings(a, p, d, settings_edit_body(edit, body)?).await? + } + Datatable => { + let Json(result) = + edit_datatable_config(a, d, p, authed, settings_edit_body(edit, body)?).await?; + return serde_json::to_value(result).map_err(|e| Error::internal_err(e.to_string())); + } + SlackCommand => { + edit_slack_command(a, d, p, authed, settings_edit_body(edit, body)?).await? + } + SetSlackOAuth => set_slack_oauth_config(a, d, p, settings_edit_body(edit, body)?).await?, + DeleteSlackOAuth => delete_slack_oauth_config(a, d, p).await?, + Ducklake => edit_ducklake_config(a, d, p, authed, settings_edit_body(edit, body)?).await?, + DbtWarehouses => { + edit_dbt_warehouses(a, d, p, authed, settings_edit_body(edit, body)?).await? + } + #[cfg(feature = "enterprise")] + DeployUi => edit_deploy_ui_config(a, d, p, authed, settings_edit_body(edit, body)?).await?, + #[cfg(not(feature = "enterprise"))] + DeployUi => edit_deploy_ui_config(a, d, p).await?, + GuestAccess => edit_guest_access(a, d, p, settings_edit_body(edit, body)?).await?, + GuestJwtKey => edit_guest_jwt_key(a, d, p, settings_edit_body(edit, body)?).await?, + PublicAppRateLimit => { + edit_public_app_rate_limit(d, p, a, settings_edit_body(edit, body)?).await? + } + AddAdminsAndDevelopersToForks => { + edit_add_admins_and_developers_to_forks(a, d, p, settings_edit_body(edit, body)?) + .await? + } + #[cfg(all(feature = "private", feature = "enterprise"))] + DatatablePermissions => { + #[derive(Deserialize)] + struct Body { + datatable: String, + #[serde(flatten)] + req: crate::datatable_permissions_ee::SetDatatablePermissions, + } + let Json(Body { datatable, req }) = settings_edit_body(edit, body)?; + crate::datatable_permissions_oss::set_datatable_permissions( + a, + d, + Path((p.0, datatable)), + Json(req), + ) + .await? + } + #[cfg(not(all(feature = "private", feature = "enterprise")))] + DatatablePermissions => { + crate::datatable_permissions_oss::set_datatable_permissions(a).await? + } + CreateProtectionRule => { + create_protection_rule(a, d, p, settings_edit_body(edit, body)?).await? + } + UpdateProtectionRule => { + #[derive(Deserialize)] + struct Body { + rule_name: String, + #[serde(flatten)] + req: UpdateProtectionRuleRequest, + } + let Json(Body { rule_name, req }) = settings_edit_body(edit, body)?; + update_protection_rule(a, d, Path((p.0, rule_name)), Json(req)).await? + } + DeleteProtectionRule => { + #[derive(Deserialize)] + struct Body { + name: String, + } + let Json(Body { name }) = settings_edit_body(edit, body)?; + delete_protection_rule(a, d, Path((p.0, name))).await? + } + }; + Ok(serde_json::Value::Null) +} diff --git a/backend/windmill-api-workspaces/src/workspaces_extra.rs b/backend/windmill-api-workspaces/src/workspaces_extra.rs index 50833bfe06..e02d7c8c3e 100644 --- a/backend/windmill-api-workspaces/src/workspaces_extra.rs +++ b/backend/windmill-api-workspaces/src/workspaces_extra.rs @@ -1,4 +1,4 @@ -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use windmill_api_auth::{require_super_admin, ApiAuthed}; use windmill_common::DB; @@ -54,6 +54,23 @@ pub(crate) async fn change_workspace_id( require_admin(authed.is_admin, &authed.username)?; } + // An isolating fork's objects live under a prefix derived from its id: under a new id it + // would see none of them, and descendants would lose them from their read-through. + let isolates_storage = sqlx::query_scalar!( + "SELECT EXISTS (SELECT 1 FROM fork_storage_namespace WHERE workspace_id = $1)", + &old_id + ) + .fetch_one(&db) + .await? + .unwrap_or(false); + if isolates_storage { + return Err(Error::BadRequest( + "This workspace isolates its object storage from its parent under a prefix derived \ + from its id, so its id cannot be changed" + .to_string(), + )); + } + let mut tx = db.begin().await?; // The settings copy below carries every data table entry to the new id, which fork cleanup of @@ -868,11 +885,21 @@ pub(crate) async fn change_workspace_id( "Re-pushing jobs for {} enabled schedules", enabled_schedule_paths.len() ); - for schedule_path in &enabled_schedule_paths { - if let Some(schedule) = get_schedule_opt(&mut *tx, &rw.new_id, schedule_path).await? { - tx = push_scheduled_job(&db, tx, &schedule, None, None).await?; + windmill_queue::tags::carry_lineage_over_rename(&old_id, &rw.new_id, &db).await?; + let new_id = &rw.new_id; + let repushed = async { + for schedule_path in &enabled_schedule_paths { + if let Some(schedule) = get_schedule_opt(&mut *tx, new_id, schedule_path).await? { + tx = push_scheduled_job(&db, tx, &schedule, None, None).await?; + } } + Ok::<_, Error>(tx) } + .await; + if repushed.is_err() { + windmill_queue::tags::invalidate_fork_parent_cache(new_id); + } + let mut tx = repushed?; // After every workspace_settings write above: fork cleanup locks a settings row before the // registry, so taking the registry first here would deadlock with it. @@ -1099,6 +1126,34 @@ pub(crate) async fn delete_workspace( tracing::warn!("deleting workspace {w_id}: preparing ducklake cleanup: {e:#}"); vec![] }); + // A child fork reads through to this fork's prefix, or to the one this fork shares, and a + // child sharing the storage writes into it: deleting this link would destroy the child's + // data, or leave its chain without the isolating fork, writing the root's own keys. Under the + // lock forking this workspace takes, so no child can commit between the check and the delete. + windmill_common::workspaces::lock_fork_datatables(&mut tx, &w_id).await?; + let chain = windmill_common::workspaces::workspace_with_fork_ancestors(&db, &w_id).await?; + let isolating_with_children = sqlx::query_scalar!( + "SELECT EXISTS (SELECT 1 FROM fork_storage_namespace WHERE workspace_id = ANY($1)) + AND EXISTS (SELECT 1 FROM workspace WHERE parent_workspace_id = $2)", + &chain, + &w_id + ) + .fetch_one(&mut *tx) + .await? + .unwrap_or(false); + if isolating_with_children { + return Err(Error::BadRequest(format!( + "the forks of {w_id} reach its fork chain's isolated object storage through it: \ + delete them first" + ))); + } + // Nothing can reach a deleted fork's prefix once it is gone, so it is always purged. + let fork_storage_purges = prepare_fork_storage_purges(&db, &w_id, None) + .await + .unwrap_or_else(|e| { + tracing::warn!("deleting workspace {w_id}: preparing storage purge: {e:#}"); + vec![] + }); sqlx::query!("DELETE FROM ai_agent_memory WHERE workspace_id = $1", &w_id) .execute(&mut *tx) @@ -1299,6 +1354,13 @@ pub(crate) async fn delete_workspace( .execute(&mut *tx) .await?; + sqlx::query!( + "DELETE FROM runnable_job_stats WHERE workspace_id = $1", + &w_id + ) + .execute(&mut *tx) + .await?; + // If this workspace is itself a dev workspace, deleting it dissolves the pairing, so also drop // the parent prod's reserved dev_workspace_lock (mirrors detach_dev_workspace) — otherwise prod // stays locked against direct deploy/forking with no dev workspace left to make changes in. @@ -1362,6 +1424,14 @@ pub(crate) async fn delete_workspace( e.msg ); } + match purge_fork_storages_unless_live(&db, &w_id, fork_storage_purges).await { + Ok(errors) => { + for e in errors { + tracing::warn!("deleted workspace {w_id}: storage purge: {e}"); + } + } + Err(e) => tracing::warn!("deleted workspace {w_id}: storage purge: {e:#}"), + } if let Some(parent) = dev_lock_parent { windmill_common::workspaces::invalidate_protection_rules_cache(&parent); @@ -1479,20 +1549,39 @@ pub async fn drop_forked_datatable_databases( serde_json::from_value(datatable_config).unwrap_or_default(); let mut errors: Vec = Vec::new(); + // Data tables cloned from one database share its copy, which is dropped once for all of them. + // Keyed by where the database lives too: copies on other clusters or servers can share a name. + let mut dropped_dbs: HashSet<(String, Option, String)> = HashSet::new(); + // Only a clone is droppable, and a clone is terminal by construction: a kept data table is a + // pointer at the parent's database, which this fork does not own. + let cloned_database = |name: &str| { + datatables + .get(name) + .filter(|dt| dt.forked_from.is_some()) + .and_then(|dt| dt.database.as_ref()) + }; for dt_name in &req.datatable_names { - // Only a clone is droppable, and a clone is terminal by construction: a kept data table is - // a pointer at the parent's database, which this fork does not own. - let database = match datatables.get(dt_name) { - Some(dt) if dt.forked_from.is_some() => match dt.database.as_ref() { - Some(database) => database, - None => continue, - }, - _ => continue, + let Some(database) = cloned_database(dt_name) else { + continue; }; if database.resource_type.is_windmill_managed() { let db_to_drop = &database.resource_path; + let cluster = database.resource_type.as_ref().to_string(); + if !dropped_dbs.insert((cluster, None, db_to_drop.clone())) { + continue; + } + let sharing: Vec = req + .datatable_names + .iter() + .filter(|name| { + cloned_database(name).is_some_and(|d| { + d.resource_type == database.resource_type && &d.resource_path == db_to_drop + }) + }) + .cloned() + .collect(); if !db_to_drop.starts_with("wm_fork_") { errors.push(format!( "Refusing to drop instance database '{}' for datatable://{}: name does not start with 'wm_fork_'", @@ -1506,12 +1595,8 @@ pub async fn drop_forked_datatable_databases( // A task of its own, so a client going away cannot stop it between dropping the // database and committing the entry's removal. let dropped = tokio::spawn({ - let (db, w_id, dt_name, db_to_drop) = ( - db.clone(), - w_id.clone(), - dt_name.clone(), - db_to_drop.clone(), - ); + let (db, w_id, sharing, db_to_drop) = + (db.clone(), w_id.clone(), sharing.clone(), db_to_drop.clone()); let resource_type = database.resource_type; async move { let mut tx = db.begin().await?; @@ -1520,26 +1605,29 @@ pub async fn drop_forked_datatable_databases( // rename this entry, or point another one here, either side of the check below. windmill_common::workspaces::lock_fork_datatables(&mut tx, &w_id).await?; // The snapshot above was read unlocked: a save committing since could have - // repointed this entry, and the entry is removed below whatever it names by then. - let current = sqlx::query_scalar::<_, Option>( - "SELECT datatable->'datatables'->$2 FROM workspace_settings - WHERE workspace_id = $1 FOR UPDATE", - ) - .bind(&w_id) - .bind(&dt_name) - .fetch_optional(&mut *tx) - .await? - .flatten() - .and_then(|v| serde_json::from_value::(v).ok()); - if !current.is_some_and(|dt| { - dt.forked_from.is_some() - && dt.database.is_some_and(|d| { - d.resource_type == resource_type && d.resource_path == db_to_drop - }) - }) { - return Err(Error::BadRequest( - "the data table changed while it was being cleaned up".to_string(), - )); + // repointed these entries, and they are removed below whatever they name by then. + for dt_name in &sharing { + let current = sqlx::query_scalar::<_, Option>( + "SELECT datatable->'datatables'->$2 FROM workspace_settings + WHERE workspace_id = $1 FOR UPDATE", + ) + .bind(&w_id) + .bind(dt_name) + .fetch_optional(&mut *tx) + .await? + .flatten() + .and_then(|v| serde_json::from_value::(v).ok()); + if !current.is_some_and(|dt| { + dt.forked_from.is_some() + && dt.database.is_some_and(|d| { + d.resource_type == resource_type + && d.resource_path == db_to_drop + }) + }) { + return Err(Error::BadRequest(format!( + "data table '{dt_name}' changed while it was being cleaned up" + ))); + } } let external = resource_type == windmill_common::workspaces::DataTableCatalogResourceType::ExternalInstance; @@ -1557,11 +1645,13 @@ pub async fn drop_forked_datatable_databases( ) .await?; // Before the entry is removed: child fork pointers are found through it. - let uses = windmill_common::workspaces::managed_database_uses( + let names: Vec<&str> = sharing.iter().map(String::as_str).collect(); + let uses = windmill_common::workspaces::managed_database_uses_except( &mut tx, resource_type, &db_to_drop, - Some((w_id.as_str(), dt_name.as_str())), + &w_id, + &names, ) .await?; if !uses.is_empty() { @@ -1572,20 +1662,22 @@ pub async fn drop_forked_datatable_databases( } // The entry goes with the database: a fork this one is cloned into afterwards // must not inherit a pointer at a data table whose database is gone. - sqlx::query( - "UPDATE workspace_settings SET datatable = datatable #- ARRAY['datatables', $2] - WHERE workspace_id = $1", - ) - .bind(&w_id) - .bind(&dt_name) - .execute(&mut *tx) - .await?; + for dt_name in &sharing { + sqlx::query( + "UPDATE workspace_settings SET datatable = datatable #- ARRAY['datatables', $2] + WHERE workspace_id = $1", + ) + .bind(&w_id) + .bind(dt_name) + .execute(&mut *tx) + .await?; + } if external { // Checks the uses of the database itself, and unregisters it. windmill_common::external_instance_pg::drop_external_instance_database_unchecked( &mut tx, &db_to_drop, - Some((w_id.as_str(), dt_name.as_str())), + sharing.first().map(|name| (w_id.as_str(), name.as_str())), ) .await?; } else { @@ -1608,10 +1700,38 @@ pub async fn drop_forked_datatable_databases( if let Err(e) = dropped { errors.push(format!( "Could not drop instance database '{}' for datatable://{}: {}", - db_to_drop, dt_name, e + db_to_drop, + sharing.join(", datatable://"), + e )); } } else { + // Clones on one resource share its copy, which stays while any of them is kept. Only + // clones: a kept entry naming the resource cannot be put in the request. + let mut kept: Vec<&String> = datatables + .iter() + .filter(|(name, dt)| { + !req.datatable_names.contains(name) + && dt.forked_from.is_some() + && dt.database.as_ref().is_some_and(|d| { + d.resource_type == database.resource_type + && d.resource_path == database.resource_path + }) + }) + .map(|(name, _)| name) + .collect(); + if !kept.is_empty() { + kept.sort(); + errors.push(format!( + "Could not drop the database of datatable://{dt_name}: it is still used by data \ + tables {}", + kept.iter() + .map(|name| format!("'{name}'")) + .collect::>() + .join(", ") + )); + continue; + } let fork_pg = match crate::workspaces::resolve_pg_source_checked( &db, &user_db, @@ -1666,6 +1786,9 @@ pub async fn drop_forked_datatable_databases( )); continue; } + if !dropped_dbs.insert((parent_pg.host.clone(), parent_pg.port, db_to_drop.clone())) { + continue; + } match parent_pg.connect(Some(&db)).await { Ok((client, connection)) => { @@ -2238,6 +2361,114 @@ async fn delete_fork_ducklake_data( )) } +/// A storage a fork isolated, resolved while its `$res:` still exists. +pub(crate) struct PreparedForkStoragePurge { + storage: String, + store: std::result::Result<(windmill_types::s3::LargeFileStorage, serde_json::Value), String>, +} + +/// Read-only: one entry per `fork_storage_namespace` row of `w_id`. `res_fallback_w_id` as in +/// [`prepare_fork_ducklake_cleanups`]. +pub(crate) async fn prepare_fork_storage_purges( + db: &DB, + w_id: &str, + res_fallback_w_id: Option<&str>, +) -> Result> { + let rows = sqlx::query!( + "SELECT storage, storage_ref FROM fork_storage_namespace WHERE workspace_id = $1", + w_id + ) + .fetch_all(db) + .await?; + let mut prepared = Vec::with_capacity(rows.len()); + for row in rows { + let storage = Some(row.storage.as_str()).filter(|s| !s.is_empty()); + let store = resolve_fork_storage(db, w_id, res_fallback_w_id, storage, &row.storage_ref) + .await + .map_err(|e| e.to_string()); + prepared.push(PreparedForkStoragePurge { storage: row.storage, store }); + } + Ok(prepared) +} + +/// [`purge_fork_storages`] under the lock same-id fork creation takes, unless a workspace with +/// that id exists again: the rows are then the new fork's, and its creation already purged the +/// ones it found. +pub(crate) async fn purge_fork_storages_unless_live( + db: &DB, + w_id: &str, + prepared: Vec, +) -> Result> { + // The lock only orders a purge against a same-id fork write; with nothing to purge, waiting + // on it would only hold fork creation's answer behind such a write. + if prepared.is_empty() { + return Ok(vec![]); + } + let mut lock = db.begin().await?; + sqlx::query("SELECT pg_advisory_xact_lock(hashtext('fork:' || $1))") + .bind(w_id) + .execute(&mut *lock) + .await?; + let live = sqlx::query_scalar!( + "SELECT EXISTS (SELECT 1 FROM workspace WHERE id = $1)", + w_id + ) + .fetch_one(&mut *lock) + .await? + .unwrap_or(false); + let errors = if live { + vec![] + } else { + purge_fork_storages(db, w_id, prepared).await + }; + lock.commit().await?; + Ok(errors) +} + +/// Delete everything under the fork's `__wm_forks//` in each prepared storage, then its +/// registry row. Returns one message per storage that could not be purged; its row survives. +async fn purge_fork_storages( + db: &DB, + w_id: &str, + prepared: Vec, +) -> Vec { + let area = format!( + "{}/{}", + windmill_common::workspaces::FORK_DUCKLAKE_DATA_DIR, + windmill_common::workspaces::fork_data_dir_segment(w_id) + ); + let mut errors = vec![]; + for p in prepared { + let name = if p.storage.is_empty() { + "default storage" + } else { + p.storage.as_str() + }; + let purged = match p.store { + Ok((lfs, value)) => delete_fork_ducklake_data(lfs, value, &area) + .await + .map_err(|e| e.to_string()), + Err(e) => Err(e), + }; + if let Err(e) = purged { + errors.push(format!("{name}: {e}")); + continue; + } + if let Err(e) = sqlx::query!( + "DELETE FROM fork_storage_namespace WHERE workspace_id = $1 AND storage = $2", + w_id, + p.storage + ) + .execute(db) + .await + { + errors.push(format!("{name}: removing registry row: {e}")); + } + } + windmill_common::fork_storage::invalidate_fork_storage_keys_cache(w_id); + errors +} + /// Destroying an ATTACHED dev workspace (or its data environments) must be a prod-admin /// action, not just the dev's own owner (dev ownership can diverge from prod's) — mirrors /// detach_dev_workspace. Shared by `delete_workspace` and `drop_forked_ducklake_namespaces` diff --git a/backend/windmill-api/Cargo.toml b/backend/windmill-api/Cargo.toml index ad7f12453c..583d139cf5 100644 --- a/backend/windmill-api/Cargo.toml +++ b/backend/windmill-api/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true [lib] name = "windmill_api" path = "src/lib.rs" +# src/ has no doctests: remove this line before adding one, or cargo test never runs it. +doctest = false [features] default = [] @@ -20,7 +22,7 @@ benchmark = [] embedding = ["windmill-api-embeddings/embedding"] parquet = ["dep:datafusion", "windmill-common/parquet", "windmill-object-store/parquet", "windmill-worker?/parquet", "windmill-indexer?/parquet", "windmill-api-users/parquet", "windmill-api-settings/parquet", "windmill-api-workspaces/parquet", "windmill-api-npm-proxy/parquet", "dep:aws-sigv4", "dep:aws-sdk-config", "dep:quick-xml"] prometheus = ["windmill-common/prometheus", "windmill-queue/prometheus", "dep:prometheus", "windmill-worker?/prometheus", "windmill-api-scripts/prometheus"] -openidconnect = ["dep:openidconnect", "windmill-common/openidconnect", "windmill-store/openidconnect"] +openidconnect = ["dep:openidconnect", "dep:rsa", "dep:p256", "dep:tokio-rustls", "windmill-common/openidconnect", "windmill-store/openidconnect"] # The service log search handler reads the columnar store, so tantivy alone is # not enough for this crate to build on its own. tantivy = ["dep:windmill-indexer", "parquet"] @@ -141,6 +143,8 @@ samael = { workspace = true, optional = true } libxml = { workspace = true, optional = true } async-recursion.workspace = true rsa = { workspace = true, optional = true} +p256 = { workspace = true, optional = true } +tokio-rustls = { workspace = true, optional = true } uuid.workspace = true datafusion = { workspace = true, optional = true} openidconnect = { workspace = true, optional = true} @@ -189,4 +193,7 @@ flate2.workspace = true strum = { workspace = true, optional = true } dashmap.workspace = true +[dev-dependencies] +rcgen.workspace = true + [build-dependencies] diff --git a/backend/windmill-api/openapi-deref.json b/backend/windmill-api/openapi-deref.json index 4016222d30..ad312c43e3 100644 --- a/backend/windmill-api/openapi-deref.json +++ b/backend/windmill-api/openapi-deref.json @@ -34948,7 +34948,7 @@ }, "early_return": { "type": "string", - "description": "JavaScript expression to return early from the flow" + "description": "Id of the step whose result a sync webhook returns as soon as that step completes, while the rest of the flow keeps running. When the step does not run, or fails while the flow has a failure module, the flow's final result is returned instead." }, "chat_input_enabled": { "type": "boolean", @@ -48161,7 +48161,7 @@ }, "early_return": { "type": "string", - "description": "JavaScript expression to return early from the flow" + "description": "Id of the step whose result a sync webhook returns as soon as that step completes, while the rest of the flow keeps running. When the step does not run, or fails while the flow has a failure module, the flow's final result is returned instead." }, "chat_input_enabled": { "type": "boolean", diff --git a/backend/windmill-api/openapi-deref.yaml b/backend/windmill-api/openapi-deref.yaml index d541144231..aa97838a30 100644 --- a/backend/windmill-api/openapi-deref.yaml +++ b/backend/windmill-api/openapi-deref.yaml @@ -11884,8 +11884,11 @@ paths: early_return: type: string description: >- - JavaScript expression to return early from the - flow + Id of the step whose result a sync webhook returns + as soon as that step completes, while the rest of + the flow keeps running. When the step does not + run, or fails while the flow has a failure module, + the flow's final result is returned instead. chat_input_enabled: type: boolean description: Whether this flow accepts chat-style input @@ -19210,7 +19213,12 @@ paths: description: Execution priority (higher numbers run first) early_return: type: string - description: JavaScript expression to return early from the flow + description: >- + Id of the step whose result a sync webhook returns as + soon as that step completes, while the rest of the flow + keeps running. When the step does not run, or fails + while the flow has a failure module, the flow's final + result is returned instead. chat_input_enabled: type: boolean description: Whether this flow accepts chat-style input diff --git a/backend/windmill-api/openapi.yaml b/backend/windmill-api/openapi.yaml index d8c217cbc8..64534d0afc 100644 --- a/backend/windmill-api/openapi.yaml +++ b/backend/windmill-api/openapi.yaml @@ -1,7 +1,7 @@ openapi: "3.0.3" info: - version: 1.827.0 + version: 1.841.0 title: Windmill API contact: @@ -1919,7 +1919,7 @@ paths: /settings/instance_ui: get: - summary: get the instance-wide announcement banner and accent color + summary: get the instance-wide announcement banner, accent color and API base url description: | Readable by any authenticated user; every page load reads it. Each value is the raw stored setting, or null when unset. @@ -1928,7 +1928,7 @@ paths: - setting responses: "200": - description: the instance_banner and accent_color settings + description: the instance_banner, accent_color and api_base_url settings content: application/json: schema: @@ -1936,6 +1936,7 @@ paths: properties: instance_banner: {} accent_color: {} + api_base_url: {} /settings_u/ruff_config: get: @@ -1970,6 +1971,24 @@ paths: application/json: schema: {} + /settings/smtp_configured: + get: + summary: whether instance SMTP is configured + description: | + Readable by any authenticated user. True when this build can send email + and SMTP is set, either in the smtp_settings instance setting or through + the SMTP_* environment variables. + operationId: getSmtpConfigured + tags: + - setting + responses: + "200": + description: whether email notifications can be sent + content: + application/json: + schema: + type: boolean + /settings/test_smtp: post: summary: test smtp @@ -5165,6 +5184,107 @@ paths: - has_instance_ai_config - uses_instance_ai_config + /w/{workspace}/workspaces/settings_document: + get: + summary: get the workspace settings document + description: >- + The workspace's settings in the layout of the settings.yaml that `wmill sync` writes. + Admin only. + operationId: getWorkspaceSettingsDocument + x-mcp-tool: true + x-mcp-tool-include-query-params: [] + tags: + - workspace + parameters: + - $ref: "#/components/parameters/WorkspaceId" + - name: secrets + description: >- + How secrets are written: `redacted` (the default) replaces each set secret with + `__SENSITIVE_AND_UNCHANGED__`; `encrypted` writes it encrypted with the workspace key, + prefixed with `$encrypted:`. + in: query + schema: + type: string + enum: [redacted, encrypted] + responses: + "200": + description: the settings document + content: + application/json: + schema: + type: object + additionalProperties: true + post: + summary: apply a workspace settings document + description: >- + Applies a settings document, each setting through the endpoint that owns it. Admin only. + operationId: applyWorkspaceSettingsDocument + x-mcp-tool: true + x-mcp-instructions: "Send only the top-level keys to change, each whole as getWorkspaceSettingsDocument returns it: a key the document omits is left as it is, and a key set to null clears it. Keep `__SENSITIVE_AND_UNCHANGED__` for a secret you were not given. Call with dry_run true first, show the user the changes and apply only once they agree." + x-mcp-tool-include-fields: + - document + - dry_run + x-mcp-tool-opaque-fields: + - document + tags: + - workspace + parameters: + - $ref: "#/components/parameters/WorkspaceId" + requestBody: + required: true + content: + application/json: + schema: + type: object + properties: + document: + description: >- + The settings to apply, in the layout of the document. A secret given as + `__SENSITIVE_AND_UNCHANGED__` keeps its stored value; one prefixed with + `$encrypted:` is decrypted with the workspace key. + type: object + additionalProperties: true + replace: + description: >- + Clear the settings `wmill sync push` clears when settings.yaml omits them. + Otherwise a setting the document omits is left as it is. + type: boolean + dry_run: + description: Only compute the changes, without applying them. + type: boolean + required: + - document + responses: + "200": + description: the changes, applied unless dry_run + content: + application/json: + schema: + type: object + properties: + changes: + type: array + items: + type: object + properties: + key: + type: string + before: {} + after: {} + required: + - key + - before + - after + applied: + type: boolean + warnings: + type: array + items: + type: string + required: + - changes + - applied + /w/{workspace}/workspaces/get_copilot_settings_state: get: summary: get copilot settings state @@ -5520,6 +5640,9 @@ paths: type: string governing_workspace_id: type: string + database_workspace_id: + type: string + description: The workspace owning the database this entry points at, when it is not this workspace. permissioned: type: boolean @@ -5567,6 +5690,9 @@ paths: type: boolean default_role: type: string + description: >- + The id of one of `roles`, `admin` (the default), or `$none` for no default + role: a connection that names no role then holds its viewer's roles only. roles: type: array items: @@ -5945,6 +6071,12 @@ paths: schema: type: integer format: int64 + - name: schema + in: query + required: false + description: apply only the pending migrations whose `-- schemas` annotation declares this schema + schema: + type: string responses: "200": description: applied migrations @@ -7435,6 +7567,72 @@ paths: items: $ref: "#/components/schemas/TruncatedToken" + /oidc/signing_status: + get: + summary: what signs OIDC tokens and the keys the JWKS serves (ee only, superadmin) + operationId: getOidcSigningStatus + tags: + - oidc + responses: + "200": + description: OIDC signing status + content: + application/json: + schema: + type: object + required: + - mode + - keys + properties: + mode: + type: string + enum: [database, file, external] + keys: + type: array + items: + type: object + required: + - alg + - state + - source + properties: + kid: + type: string + alg: + type: string + state: + type: string + enum: [pending, active, retired, published] + source: + type: string + enum: [signer, database, file, publish_dir] + signer: + type: object + description: set when an external signer is configured + required: + - breaker + - max_rps + - current_rps + properties: + last_refresh_success: + type: string + format: date-time + last_refresh_error: + type: string + breaker: + type: string + enum: [closed, open, half_open] + max_rps: + type: number + current_rps: + type: number + keys_from_store: + type: boolean + description: the keys served are those stored by the last accepted listing, the signer has not answered this server yet + tls_files_error: + type: string + description: why the mTLS files on disk are not the ones in use + /w/{workspace}/oidc/token/{audience}: post: summary: get OIDC token (ee only) @@ -9279,6 +9477,12 @@ paths: required: false schema: type: boolean + - name: starred_only + description: Only the `ai_agent` resources the caller starred + in: query + required: false + schema: + type: boolean responses: "200": description: resource list @@ -10924,6 +11128,37 @@ paths: description: "`saved` only, upsert or delete: where the write landed. Differs from the URL path when the item had moved away from it; the editor follows it there. Absent when a delete found nothing to remove and the caller cannot read the path it moved to." required: [status, current_timestamp] + /w/{workspace}/drafts/delete_for_user/{kind}/{path}: + post: + summary: delete another user's draft, or every draft at a path (admin only) + description: Delete the draft a given user holds at a path, or, without `username`, every draft at that path (the legacy ownerless one and the caller's own included). Workspace admins / superadmins only, and only for script, flow, app and raw_app drafts. Unlike a discard of one's own draft through `drafts/update`, this returns 404 when nothing was deleted. + operationId: deleteDraftForUser + tags: + - draft + parameters: + - $ref: "#/components/parameters/WorkspaceId" + - name: kind + in: path + required: true + schema: + $ref: "#/components/schemas/UserDraftItemKind" + - $ref: "#/components/parameters/ScriptPath" + - name: username + in: query + required: false + description: Workspace username of the draft owner. Omit to delete every user's draft at the path. + schema: + type: string + responses: + "200": + description: draft(s) deleted + content: + text/plain: + schema: + type: string + "404": + description: no matching draft at that path + /w/{workspace}/drafts/move/{kind}/{path}: post: summary: move the current user's draft-only item to another path @@ -11181,6 +11416,34 @@ paths: schema: type: boolean + /workers/dev_workspace_isolation: + get: + summary: get whether the jobs of dev workspaces and forks run on their own worker groups + operationId: getDevWorkspaceIsolation + tags: + - worker + responses: + "200": + description: dev workspace isolation + content: + application/json: + schema: + type: object + properties: + enabled: + type: boolean + description: whether new jobs of dev workspaces and forks are queued on suffixed tags + suffix: + type: string + description: the suffix of those tags, which worker groups serving dev workspaces listen with + skip_non_dev_forks: + type: boolean + description: whether forks of a workspace that is not a dev workspace, nor under one, run on their parent's workers instead + required: + - enabled + - suffix + - skip_non_dev_forks + /w/{workspace}/workspace_dependencies/create: post: summary: create workspace dependencies @@ -12664,7 +12927,7 @@ paths: /w/{workspace}/runnables/list: get: - summary: list runnables (scripts, flows, apps) merged, ordered and keyset-paginated + summary: list runnables (scripts, flows, apps, agents) merged, ordered and keyset-paginated operationId: listRunnables tags: - script @@ -12681,7 +12944,7 @@ paths: - $ref: "#/components/parameters/OrderDesc" - name: kinds in: query - description: comma-separated subset of script,flow,app (default all) + description: comma-separated subset of script,flow,app,agent (default all) schema: type: string - name: show_archived @@ -12755,7 +13018,7 @@ paths: - $ref: "#/components/parameters/WorkspaceId" - name: kinds in: query - description: comma-separated subset of script,flow,app (default all) + description: comma-separated subset of script,flow,app,agent (default all) schema: type: string - name: include_without_main @@ -14445,6 +14708,168 @@ paths: schema: type: string + /w/{workspace}/ai/shared_sessions/share: + post: + summary: share an AI session transcript by link + description: > + Stores a read-only snapshot of the session that members of the workspace can open by + id, or anyone with the link once it is public. Sharing the same session again updates + that snapshot and keeps its id. + operationId: shareAiSession + tags: + - ai + parameters: + - $ref: "#/components/parameters/WorkspaceId" + requestBody: + required: true + content: + application/json: + schema: + type: object + required: + - session_id + - name + - message_count + - snapshot + properties: + session_id: + type: string + description: the session's id in the author's browser + name: + type: string + is_public: + type: boolean + description: left as it is on an existing share when absent; a new share starts private + message_count: + type: integer + minimum: 0 + snapshot: + type: object + additionalProperties: true + responses: + "200": + description: the shared snapshot + content: + application/json: + schema: + $ref: "#/components/schemas/SharedAiSessionInfo" + + /w/{workspace}/ai/shared_sessions/status: + get: + summary: get the calling user's share of one of their AI sessions + operationId: getAiSessionShareStatus + tags: + - ai + parameters: + - $ref: "#/components/parameters/WorkspaceId" + - name: session_id + in: query + required: true + schema: + type: string + responses: + "200": + description: the share, if any + content: + application/json: + schema: + type: object + properties: + share: + $ref: "#/components/schemas/SharedAiSessionInfo" + + /w/{workspace}/ai/shared_sessions/set_public/{id}: + post: + summary: make a shared AI session public, or reserve it to workspace members + operationId: setAiSessionSharePublic + tags: + - ai + parameters: + - $ref: "#/components/parameters/WorkspaceId" + - name: id + in: path + required: true + schema: + type: string + format: uuid + requestBody: + required: true + content: + application/json: + schema: + type: object + required: + - is_public + properties: + is_public: + type: boolean + responses: + "200": + description: the updated share + content: + application/json: + schema: + $ref: "#/components/schemas/SharedAiSessionInfo" + + /w/{workspace}/ai_u/shared_sessions/get/{id}: + get: + summary: get a shared AI session + description: > + A public share is served without authentication; any other one only to a member of + the workspace. + operationId: getSharedAiSession + tags: + - ai + parameters: + - $ref: "#/components/parameters/WorkspaceId" + - name: id + in: path + required: true + schema: + type: string + format: uuid + responses: + "200": + description: the shared session + content: + application/json: + schema: + allOf: + - $ref: "#/components/schemas/SharedAiSessionInfo" + - type: object + required: + - snapshot + - can_unshare + properties: + snapshot: + type: object + additionalProperties: true + can_unshare: + type: boolean + description: whether the caller authored the share or is a workspace admin + + /w/{workspace}/ai/shared_sessions/delete/{id}: + delete: + summary: stop sharing an AI session + operationId: unshareAiSession + tags: + - ai + parameters: + - $ref: "#/components/parameters/WorkspaceId" + - name: id + in: path + required: true + schema: + type: string + format: uuid + responses: + "200": + description: share deleted + content: + text/plain: + schema: + type: string + /w/{workspace}/apps/get_data/v/{secretWithExtension}: get: summary: get raw app data by @@ -15368,6 +15793,12 @@ paths: type: integer tag: type: string + modules: + type: object + nullable: true + description: "Additional modules keyed by relative file path. Honored in preview only: a deployed app runs the modules stored with its runnable." + additionalProperties: + $ref: "#/components/schemas/ScriptModule" required: - content - language @@ -15396,6 +15827,14 @@ paths: description: "Map of relative-import script path -> temp storage hash. Only honored for inline-script (raw_code) execution so app dev resolves those imports from not-yet-deployed local content." additionalProperties: type: string + on_behalf_of: + type: string + nullable: true + description: "Preview mode (force_viewer_static_fields set) only: run as this identity (an email, `u/` or `g/`) instead of the caller. Naming anyone other than yourself requires being an admin or a member of wm_deployers." + viewer_data_access: + type: boolean + nullable: true + description: "Preview mode only: the inline runnable's viewer_data_access policy setting (run mode reads it from the deployed policy)." required: - args - component @@ -15871,6 +16310,9 @@ paths: /w/{workspace}/jobs/run/batch_rerun_jobs: post: summary: re-run multiple jobs + description: >- + Re-runs each job and marks every failed or canceled original that was re-run as + resolved, with the new job's id in its note. Operators re-run without resolving. operationId: batchReRunJobs tags: - job @@ -16372,8 +16814,9 @@ paths: summary: run a saved AI agent description: | Runs the `ai_agent` resource at `path` as stored, for any caller who can read it - (operators included), as the caller, who needs access to the agent's AI resource and to - whatever its tools use. With `memory_id`, the run is a turn + (operators included). The run is the caller's, or the agent's `on_behalf_of` when its + `run_on_behalf_of` is set; the caller's inputs may then not reference variables or + resources. With `memory_id`, the run is a turn of the caller's conversation with the agent; without, a single run. operationId: runAgent tags: @@ -16632,6 +17075,7 @@ paths: - job parameters: - $ref: "#/components/parameters/WorkspaceId" + - $ref: "#/components/parameters/OrderDesc" - $ref: "#/components/parameters/CreatedBy" - $ref: "#/components/parameters/Label" - $ref: "#/components/parameters/Worker" @@ -16664,8 +17108,8 @@ paths: type: boolean - name: resolved description: >- - filter on whether a failure has been marked as handled. true keeps only - resolved failures, false hides them + filter on whether a failed or canceled run has been marked as handled. true + keeps only resolved runs, false hides them in: query schema: type: boolean @@ -16976,8 +17420,8 @@ paths: type: boolean - name: resolved description: >- - filter on whether a failure has been marked as handled. true keeps only - resolved failures, false hides them + filter on whether a failed or canceled run has been marked as handled. true + keeps only resolved runs, false hides them in: query schema: type: boolean @@ -17163,8 +17607,8 @@ paths: type: boolean - name: resolved description: >- - filter on whether a failure has been marked as handled. true keeps only - resolved failures, false hides them + filter on whether a failed or canceled run has been marked as handled. true + keeps only resolved runs, false hides them in: query schema: type: boolean @@ -17322,6 +17766,27 @@ paths: schema: type: string + /w/{workspace}/jobs/worker_is_draining/{id}: + get: + summary: whether the worker running this job is draining + description: | + True once the worker running the job has received its shutdown signal. The worker + still waits for the job to finish, so a long-running job can poll this to exit early. + False when the job is not currently running on a worker. + operationId: workerIsDraining + tags: + - job + parameters: + - $ref: "#/components/parameters/WorkspaceId" + - $ref: "#/components/parameters/JobId" + responses: + "200": + description: whether the worker running this job is draining + content: + application/json: + schema: + type: boolean + /w/{workspace}/jobs_u/get_logs/{id}: get: summary: get job logs @@ -18001,11 +18466,12 @@ paths: /w/{workspace}/jobs/completed/resolve: post: - summary: mark failed jobs as resolved + summary: mark failed or canceled jobs as resolved description: >- - Marks failed jobs as handled so triage surfaces stop showing them as failures. - The job status itself is unchanged. Returns the ids actually resolved: ids that - are not visible to the caller or did not fail are silently skipped. + Marks failed or canceled jobs as handled so triage surfaces stop showing them as + unhandled. The job status itself is unchanged. Returns the ids actually resolved: ids + that are not visible to the caller or neither failed nor were canceled are silently + skipped. operationId: resolveCompletedJobs tags: - job @@ -23502,6 +23968,54 @@ paths: - id - values + /workers/runnable_stats: + get: + summary: get resource usage per runnable and worker group over a time window (require devops role) + operationId: getRunnableStats + tags: + - worker + parameters: + - name: window_secs + in: query + required: false + description: how far back to read, in seconds (defaults to one day, capped at the 30-day retention) + schema: + type: integer + - name: worker_group + in: query + required: false + description: only the jobs run by this worker group + schema: + type: string + - name: workspace + in: query + required: false + description: only the jobs of this workspace + schema: + type: string + - name: order_by + in: query + required: false + description: "what the rows are ranked by, descending (default: total_duration)" + schema: + type: string + enum: [total_duration, max_memory, cpu] + - name: limit + in: query + required: false + description: number of rows to return (default 100, at most 1000) + schema: + type: integer + responses: + "200": + description: resource usage per runnable and worker group, heaviest first + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/RunnableStats" + /workers/queue_metrics_series: get: summary: get the queue metrics of a time window, as a bounded line per tag @@ -24353,7 +24867,7 @@ paths: type: string favorite_kind: type: string - enum: [flow, app, script, raw_app, asset] + enum: [flow, app, script, raw_app, asset, agent] responses: "200": description: star item @@ -24376,7 +24890,7 @@ paths: type: string favorite_kind: type: string - enum: [flow, app, script, raw_app, asset] + enum: [flow, app, script, raw_app, asset, agent] responses: "200": description: unstar item @@ -24737,6 +25251,31 @@ paths: schema: $ref: "#/components/schemas/S3Resource" + /w/{workspace}/job_helpers/v2/s3_proxy_bucket: + get: + summary: Returns the bucket S3 clients name to reach a workspace storage + through the S3 proxy, or null when that storage is not S3 + operationId: s3ProxyBucket + tags: + - helpers + parameters: + - $ref: "#/components/parameters/WorkspaceId" + - name: storage + in: query + schema: + type: string + responses: + "200": + description: The storage's bucket + content: + application/json: + schema: + type: object + properties: + bucket: + type: string + nullable: true + /w/{workspace}/job_helpers/test_connection: get: summary: Test connection to the workspace object storage @@ -25209,9 +25748,12 @@ paths: in: query schema: type: string + - $ref: "#/components/parameters/TablePreviewS3ResourcePath" + - $ref: "#/components/parameters/TablePreviewFilters" responses: "200": - description: Parquet Preview + description: > + Parquet Preview: `columns`, `column_types` (Arrow type names) and `rows`. content: application/json: {} @@ -25236,6 +25778,13 @@ paths: in: query schema: type: string + - $ref: "#/components/parameters/TablePreviewS3ResourcePath" + - name: csv_separator + in: query + schema: + type: string + - $ref: "#/components/parameters/TablePreviewCsvHasHeader" + - $ref: "#/components/parameters/TablePreviewFilters" responses: "200": description: Table count @@ -25284,13 +25833,20 @@ paths: in: query schema: type: string + - $ref: "#/components/parameters/TablePreviewS3ResourcePath" - name: csv_separator in: query schema: type: string + - $ref: "#/components/parameters/TablePreviewCsvHasHeader" + - $ref: "#/components/parameters/TablePreviewFilters" responses: "200": - description: Csv Preview + description: > + Csv Preview: `columns`, `column_types` (Arrow type names), `rows`, and the + `csv_separator` the file was read with, guessed from its first bytes when + none is given. + A `.jsonl` or `.ndjson` file is read as newline-delimited JSON. content: application/json: {} @@ -25798,8 +26354,8 @@ paths: type: boolean - name: resolved description: >- - filter on whether a failure has been marked as handled. true keeps only - resolved failures, false hides them + filter on whether a failed or canceled run has been marked as handled. true + keeps only resolved runs, false hides them in: query schema: type: boolean @@ -27650,6 +28206,28 @@ components: required: true schema: type: string + TablePreviewS3ResourcePath: + name: s3_resource_path + description: Read the file from this object storage resource instead of the workspace storage. + in: query + schema: + type: string + TablePreviewCsvHasHeader: + name: csv_has_header + description: Whether the first CSV line names the columns. Defaults to true. + in: query + schema: + type: boolean + TablePreviewFilters: + name: filters + description: > + JSON object, column name to filter. A number column takes an optional comparison + operator and a number (`>=10`), a boolean column a boolean, and any other column a + case-insensitive substring, or `=value` for an exact match. A `search_term` without + a `search_col` matches any column, case-insensitively. + in: query + schema: + type: string HubPublishFolder: name: folder in: query @@ -29897,6 +30475,31 @@ components: - shared_at - expires_at + SharedAiSessionInfo: + type: object + properties: + id: + type: string + format: uuid + name: + type: string + is_public: + type: boolean + message_count: + type: integer + created_by: + type: string + shared_at: + type: string + format: date-time + required: + - id + - name + - is_public + - message_count + - created_by + - shared_at + InstanceAIProviderSummary: type: object properties: @@ -30009,9 +30612,10 @@ components: description: | A row in the merged runnables listing. `type` is the discriminator; kind-specific fields (hash/language/kind for scripts, execution_mode/ - version for apps) are present only for that kind. `edited_at` is the - unified last-updated time (a script's created_at, a flow/app's edit - time). + version for apps, agent_memory/ws_specific for agents) are present only + for that kind. An agent is an `ai_agent` resource whose description is + reported as `summary`. `edited_at` is the unified last-updated time (a + script's created_at, a flow/app/agent's edit time). properties: type: type: string @@ -30019,6 +30623,7 @@ components: - script - flow - app + - agent path: type: string summary: @@ -30086,6 +30691,11 @@ components: version: type: integer format: int64 + agent_memory: + description: agent-only. The agent's `memory` setting. + ws_specific: + type: boolean + description: agent-only. Whether the agent is workspace-specific, which keeps it out of deploys to other workspaces. required: - type - path @@ -30691,7 +31301,7 @@ components: type: boolean resolved: type: boolean - description: whether this failure has been marked as handled + description: whether this failed or canceled run has been marked as handled resolved_by: type: string description: >- @@ -31710,6 +32320,7 @@ components: - "resource_types.create" - "resource_types.update" - "resource_types.delete" + - "resource_types.sync" - "schedule.create" - "schedule.setenabled" - "schedule.edit" @@ -32057,6 +32668,14 @@ components: description: "Map of relative-import script path -> temp storage hash so the preview job resolves those imports from not-yet-deployed local content instead of the deployed script" additionalProperties: type: string + on_behalf_of: + type: string + nullable: true + description: "Run the preview as this identity (an email, `u/` or `g/`) instead of the caller. Naming anyone other than yourself requires being an admin or a member of wm_deployers." + viewer_data_access: + type: boolean + nullable: true + description: "Data table and object storage access as the caller rather than as the job's identity, as a full-code app's inline runnable flagged viewer_data_access does for its viewer." required: - args @@ -32124,6 +32743,9 @@ components: type: string ws_specific: type: boolean + preserve_on_behalf_of: + type: boolean + description: ai_agent only. Keep the identity `value.on_behalf_of` names (`u/`, `g/`) rather than the caller's own. Honoured for admins and members of wm_deployers; otherwise every write of an agent sets it to the caller. required: - path - value @@ -32148,6 +32770,9 @@ components: type: string ws_specific: type: boolean + preserve_on_behalf_of: + type: boolean + description: ai_agent only. Keep the identity `value.on_behalf_of` names (`u/`, `g/`) rather than the caller's own. Honoured for admins and members of wm_deployers; otherwise every write of an agent sets it to the caller. Resource: type: object @@ -34575,6 +35200,7 @@ components: type: boolean default_role: type: string + description: A role id, `admin`, or `$none` when the data table has no default role. roles: type: array items: @@ -35853,6 +36479,45 @@ components: `u/`, `g/`, or an email that exists in this workspace. + RunnableStats: + type: object + description: > + Resource usage of the jobs of one runnable on one worker group. Memory and CPU are + only known for jobs run as a subprocess; memory is the peak of the job's main process. + properties: + workspace_id: + type: string + runnable_path: + type: string + description: path of the script or flow step; `` gathers previews and other runs without a stable path + worker_group: + type: string + job_count: + type: integer + total_duration_ms: + type: integer + max_memory_peak: + type: integer + description: highest peak memory of a job, in kB + sum_memory_peak: + type: integer + description: sum of the peak memory of the jobs that have one, in kB + memory_sample_count: + type: integer + description: number of jobs that have a peak memory reading + total_cpu_ms: + type: integer + required: + - workspace_id + - runnable_path + - worker_group + - job_count + - total_duration_ms + - max_memory_peak + - sum_memory_peak + - memory_sample_count + - total_cpu_ms + WorkerPing: type: object properties: @@ -35901,6 +36566,9 @@ components: type: string native_mode: type: boolean + draining: + type: boolean + description: the worker received its shutdown signal and exits once its current job is done required: - worker - worker_instance @@ -36013,6 +36681,11 @@ components: items: type: string description: "Lake names the fork SHARES with the parent (reads and writes the parent's lake directly). Every lake not listed gets the default isolated fork namespace with read-defer to the parent." + shared_storages: + type: array + items: + type: string + description: "Workspace storages the fork SHARES with the parent (`_default_` for the primary one): it reads and writes the parent's objects directly. Every storage not listed is isolated: the fork writes under its own prefix and reads through to the parent's objects." is_dev_workspace: type: boolean description: "Create the fork as a persistent dev workspace (id not required to carry the wm-fork- prefix; at most one per parent)" @@ -36358,6 +37031,10 @@ components: description: "Map of relative-import script path -> temp storage hash, propagated to each flow step so inline-script relative imports resolve from not-yet-deployed local content instead of the deployed script" additionalProperties: type: string + on_behalf_of: + type: string + nullable: true + description: "Run the preview as this identity (an email, `u/` or `g/`) instead of the caller. Naming anyone other than yourself requires being an admin or a member of wm_deployers." required: - value @@ -36454,7 +37131,8 @@ components: the app bundle so `windmill-client` calls run as the viewer. Must be a subset of the server's curated allowlist (jobs:run, jobs:read, users:read, resources:read, variables:read, flow_conversations:read, - flow_conversations:write). + flow_conversations:write). Every such token can call whoami without + consent, whether `users:read` is declared or not. ListableApp: type: object @@ -37050,6 +37728,15 @@ components: - ran - not_run - unknown + schemas: + type: array + description: the schemas its `-- schemas` annotation declares; absent when it applies to the whole database + items: + type: string + blocked_by: + type: integer + format: int64 + description: when not run, the earliest pending migration that must be applied first; when run, the latest applied migration that must be rolled back first DataTableSchema: type: object required: [datatable_name, schemas] @@ -37083,6 +37770,7 @@ components: default_role, can_create_schema, creatable_schemas, + migrations_enabled, ] properties: datatable_name: @@ -37116,6 +37804,9 @@ components: description: the schemas the role the listing connected as may create in items: type: string + migrations_enabled: + type: boolean + description: whether its schema is kept as versioned migrations, which a change made with plain SQL would bypass DataTableTableSchema: type: object @@ -37863,6 +38554,9 @@ components: builder_flows: type: boolean description: Whether operators can compose flows out of existing runnables (consumes a full seat). Omitting the field leaves the stored value unchanged. + builder_apps: + type: boolean + description: Whether operators can compose full-code apps out of existing runnables (consumes a full seat). Omitting the field leaves the stored value unchanged. manage_schedules: type: boolean description: Whether operators can create, edit and delete schedules. Granted unless withdrawn; omitting the field leaves the stored value unchanged. @@ -38493,6 +39187,7 @@ components: - RestrictAnonymousAppDeployment - RestrictPublicRunSharing - RestrictGuestAppDeployment + - RequireIsolatedForks RuleBypasserGroups: type: array description: Groups that can bypass this ruleset diff --git a/backend/windmill-api/src/agent_runs.rs b/backend/windmill-api/src/agent_runs.rs index 76f729e7e0..ebd83a52a5 100644 --- a/backend/windmill-api/src/agent_runs.rs +++ b/backend/windmill-api/src/agent_runs.rs @@ -2,8 +2,9 @@ //! //! The run is built here from the stored agent rather than sent by the client, which is what lets //! anyone who can read the agent run it, operators included, the way a deployed flow runs by path: -//! a preview takes arbitrary code, this takes only the run's inputs. It runs as the caller, who -//! needs access to the agent's AI resource and to whatever its tools use. +//! a preview takes arbitrary code, this takes only the run's inputs. It runs as the caller, or as +//! the agent's `on_behalf_of` when its `run_on_behalf_of` is set; the server resolves +//! `on_behalf_of` on every write of the agent. use std::collections::HashMap; @@ -20,13 +21,16 @@ use windmill_common::{ jobs::JobPayload, users::username_to_permissioned_as, utils::{not_found_if_none, StripPath}, + variables::arg_needs_interpolation, }; use windmill_queue::{push, PushArgs, PushIsolationLevel}; use crate::ai_evals::run::config_to_draft; use crate::ai_evals::subject::AgentDraft; use crate::db::{ApiAuthed, DB}; -use crate::jobs::{handle_chat_conversation_messages, set_flow_memory_id, RunJobQuery}; +use crate::jobs::{ + handle_chat_conversation_messages, run_end_user_email, set_flow_memory_id, RunJobQuery, +}; /// The id the agent's step carries in the run, as the editor's chat names it. A token scoped to /// `jobs:run:agents:` reads its runs back by it (`require_job_within_read_scope`). @@ -59,11 +63,20 @@ pub(crate) async fn run_agent( .fetch_optional(&mut *tx) .await?; tx.commit().await?; - let Some(sqlx::types::Json(value)) = not_found_if_none(value, "Agent", path)? else { + let Some(sqlx::types::Json(mut value)) = not_found_if_none(value, "Agent", path)? else { return Err(Error::BadRequest(format!( "Agent {path} has no configuration" ))); }; + // Who the agent runs as, not one of its inputs: its identity when it opts in, as a deployed + // flow does. + let obj = value.as_object_mut(); + let (agent_obo, run_obo) = obj + .map(|o| (o.remove("on_behalf_of"), o.remove("run_on_behalf_of"))) + .unwrap_or_default(); + let agent_obo = agent_obo + .filter(|_| run_obo.and_then(|v| v.as_bool()).unwrap_or(false)) + .and_then(|v| v.as_str().map(str::to_string)); let config = config_to_draft(value)?; // A chat turn is filed where the agent's chat lists its conversations, which a flow cannot @@ -83,11 +96,47 @@ pub(crate) async fn run_agent( &["memory_id", "previous_messages"], )?; - let push_authed = authed.clone().into(); + let on_behalf_of = + windmill_common::on_behalf_of_from_permissioned_as(agent_obo.as_deref(), &w_id, &db) + .await?; + // As `run_flow` picks the identity of a deployed flow: the agent's own when it has one, the + // caller's otherwise, which lends nobody's permissions. + let (email, permissioned_as, push_authed, isolation) = if let Some(obo) = on_behalf_of.as_ref() + { + ( + &obo.email, + obo.permissioned_as.clone(), + None, + PushIsolationLevel::IsolatedRoot(db.clone()), + ) + } else { + ( + &authed.email, + username_to_permissioned_as(&authed.username), + Some(authed.clone().into()), + PushIsolationLevel::Isolated(user_db.clone(), authed.clone().into()), + ) + }; + if let Some(obo) = on_behalf_of.as_ref() { + // The worker would interpolate such an input with the job's token, which is the + // identity's. Checked on the decoded value: the raw JSON can spell `$` as `\u0024`. + if args.values().any(|v| { + serde_json::from_str::(v.get()) + .is_ok_and(|v| arg_needs_interpolation(&v.to_string())) + }) { + return Err(Error::BadRequest(format!( + "Agent {path} runs on behalf of {}, so its inputs cannot reference variables or resources", + obo.permissioned_as + ))); + } + #[cfg(all(feature = "parquet", feature = "private"))] + check_attachments_readable(&db, &authed, &w_id, &args).await?; + } let scope_ceiling = windmill_api_auth::caller_scope_ceiling(&db, &authed).await?; + let end_user_email = run_end_user_email(&db, &w_id, &authed, None).await?; let (uuid, mut tx) = push( &db, - PushIsolationLevel::Isolated(user_db.clone(), authed.clone().into()), + isolation, &w_id, JobPayload::RawFlow { value: flow_value, @@ -96,8 +145,8 @@ pub(crate) async fn run_agent( }, PushArgs::from(&args), authed.display_username(), - &authed.email, - username_to_permissioned_as(&authed.username), + email, + permissioned_as, authed.token_prefix.as_deref(), authed.username_override.as_deref(), None, @@ -114,9 +163,9 @@ pub(crate) async fn run_agent( None, None, None, - Some(&push_authed), + push_authed.as_ref(), false, - None, + end_user_email, authed.trigger_or_fallback(None), None, scope_ceiling.as_deref(), @@ -127,7 +176,8 @@ pub(crate) async fn run_agent( set_flow_memory_id(&mut tx, uuid, memory_id).await?; } if chat { - // A real conversation, not a test one: this is the agent as deployed, not a draft. + // The caller's conversation, whoever the agent runs as, and a real one: this is the + // agent as deployed, not a draft under test. handle_chat_conversation_messages( &mut tx, &authed, @@ -146,6 +196,50 @@ pub(crate) async fn run_agent( Ok((StatusCode::CREATED, uuid.to_string())) } +/// The step fetches the message's files with its job's token, so a run as the agent's identity +/// would read any file that identity can: a caller attaches only what they could download +/// themselves, checked as `sign_s3_objects` checks a key before signing it. +#[cfg(all(feature = "parquet", feature = "private"))] +async fn check_attachments_readable( + db: &DB, + authed: &ApiAuthed, + w_id: &str, + args: &HashMap>, +) -> Result<()> { + use crate::job_helpers_oss::{ + get_large_file_storage, get_workspace_s3_resource_and_check_paths, + }; + use windmill_common::db::DbWithOptAuthed; + use windmill_types::s3::{S3Object, S3Permission}; + + let Some(raw) = args.get("user_attachments") else { + return Ok(()); + }; + let attachments: Option> = serde_json::from_str(raw.get()) + .map_err(|e| Error::BadRequest(format!("invalid user_attachments: {e}")))?; + for attachment in attachments.iter().flatten().filter(|a| !a.s3.is_empty()) { + // The path check is skipped, not failed, when the storage does not resolve. + if get_large_file_storage(db, w_id, attachment.storage.clone()) + .await? + .is_none() + { + return Err(windmill_object_store::workspace_storage_not_found( + attachment.storage.as_deref(), + )); + } + get_workspace_s3_resource_and_check_paths( + &DbWithOptAuthed::from_authed(authed, db.clone(), None), + Some(authed), + w_id, + attachment.storage.clone(), + &[(&attachment.s3, S3Permission::READ)], + None, + ) + .await?; + } + Ok(()) +} + /// The agent as a one-step flow, validated by deserializing through `FlowValue` rather than /// trusted as raw JSON. Its own transforms are the step's, minus `without`, and the run's inputs /// supply the message and the attachments over the top. Always inlined, never a link to the diff --git a/backend/windmill-api/src/ai.rs b/backend/windmill-api/src/ai.rs index c401568868..8de5e16c11 100644 --- a/backend/windmill-api/src/ai.rs +++ b/backend/windmill-api/src/ai.rs @@ -37,9 +37,10 @@ use windmill_ai::providers::{ }, }; use windmill_ai::proxy::{ - fim::maybe_transform_fim_request, proxy_execution_mode, ProxyBuildArgs, ProxyExecutionMode, - ProxyRequest, + fim::maybe_transform_fim_request, proxy_execution_mode, validate_proxy_path, ProxyBuildArgs, + ProxyExecutionMode, ProxyRequest, }; +use windmill_ai::retry::send_with_retries; use windmill_audit::{audit_oss::audit_log, ActionKind}; use windmill_common::db::UserDB; use windmill_common::error::{to_anyhow, Error, Result}; @@ -165,27 +166,14 @@ fn ai_http_client_builder() -> reqwest::ClientBuilder { /// after the check (DNS-rebinding TOCTOU). /// /// Returns the shared pooled [`HTTP_CLIENT`] unchanged when there is nothing to -/// pin — an IP-literal host, or a deployment that opted into private AI -/// endpoints via `ALLOW_PRIVATE_AI_BASE_URLS`. The same opt-out and error hint -/// as `get_base_url` apply, so the guard here is consistent with save-time +/// pin — an IP-literal host, or a host `ALLOW_PRIVATE_AI_BASE_URLS` allows +/// by name or wholesale. The same allowlist and error hint as `get_base_url` +/// apply, so the guard here is consistent with save-time /// validation while additionally closing the connect-time window. async fn pinned_ai_client_for(url: &str) -> Result> { use std::borrow::Cow; - use windmill_common::ssrf::SsrfValidationError; - if *windmill_ai::ai_providers::ALLOW_PRIVATE_AI_BASE_URLS { - return Ok(Cow::Borrowed(&HTTP_CLIENT)); - } - - let target = windmill_common::ssrf::validate_url_for_ssrf(url) - .await - .map_err(|e| match e { - e @ SsrfValidationError::Private { .. } => Error::BadRequest(format!( - "{e}. If you need to use private/internal AI endpoints, \ - set the ALLOW_PRIVATE_AI_BASE_URLS=true environment variable" - )), - e => Error::from(e), - })?; + let target = windmill_ai::ai_providers::validate_ai_url(url).await?; if target.pinned_addrs().is_empty() { return Ok(Cow::Borrowed(&HTTP_CLIENT)); @@ -712,6 +700,10 @@ pub fn workspaced_service() -> Router { .nest( "/shared_artifacts", crate::ai_shared_artifacts::workspaced_service(), + ) + .nest( + "/shared_sessions", + crate::ai_shared_sessions::workspaced_service(), ); #[cfg(feature = "bedrock")] @@ -1098,6 +1090,7 @@ async fn global_proxy( headers: HeaderMap, body: Bytes, ) -> impl IntoResponse { + validate_proxy_path(&ai_path)?; let provider = headers .get("X-Provider") .map(|v| v.to_str().unwrap_or("").to_string()); @@ -1188,15 +1181,11 @@ async fn global_proxy( } }; - let response = request.send().await.map_err(to_anyhow)?; + let response = send_with_retries(request).await; audit_global_ai_request(&db, &authed).await?; - if response.error_for_status_ref().is_err() { - let err_msg = response.text().await.unwrap_or("".to_string()); - return Err(Error::AIError(err_msg)); - } - + let response = response?; let status_code = response.status(); let headers = response.headers().clone(); let stream = response.bytes_stream(); @@ -1220,6 +1209,7 @@ async fn proxy( headers: HeaderMap, mut body: Bytes, ) -> impl IntoResponse { + validate_proxy_path(&ai_path)?; let provider = headers .get("X-Provider") .map(|v| v.to_str().unwrap_or("").to_string()); @@ -1576,7 +1566,7 @@ async fn proxy( } }; - let response = request.send().await.map_err(to_anyhow)?; + let response = send_with_retries(request).await; let mut tx = db.begin().await?; @@ -1592,11 +1582,7 @@ async fn proxy( .await?; tx.commit().await?; - if response.error_for_status_ref().is_err() { - let err_msg = response.text().await.unwrap_or("".to_string()); - return Err(Error::AIError(err_msg)); - } - + let response = response?; let status_code = response.status(); let headers = response.headers().clone(); let is_sse = is_sse_response(&headers); diff --git a/backend/windmill-api/src/ai_sessions.rs b/backend/windmill-api/src/ai_sessions.rs index 65a8137c4e..097e5c4862 100644 --- a/backend/windmill-api/src/ai_sessions.rs +++ b/backend/windmill-api/src/ai_sessions.rs @@ -24,7 +24,6 @@ use axum::{ Extension, Json, Router, }; use futures::{StreamExt, TryStreamExt}; -use magic_crypt::{MagicCrypt256, MagicCryptTrait}; use serde::{Deserialize, Serialize}; use serde_json::value::RawValue; use std::sync::Arc; @@ -33,9 +32,11 @@ use windmill_api_workspaces::ai_session_backups::{ fallback_store, generation_prefix, primary_store, storage_id, MAX_OBJECT_BYTES, }; use windmill_api_workspaces::workspaces::sessions_retention_days; +use windmill_common::db::{process_uptime, PREVIOUS_RELEASE_ROLLOUT_UPTIME}; use windmill_common::error::{Error, JsonResult, Result}; use windmill_common::utils::calculate_hash; -use windmill_common::variables::{crypt_from_key_with_suffix, get_workspace_key}; +use windmill_common::variables::{crypt_from_key_with_suffix, get_workspace_key, WorkspaceCrypt}; +use windmill_common::workspace_crypt::{CipherFormat, MAX_BYTES_OVERHEAD}; use windmill_object_store::object_store_reexports::{ ObjectStore, ObjectStoreError, Path as ObjectPath, PutPayload, }; @@ -47,9 +48,9 @@ const PULL_BODY_LIMIT: usize = 64 * 1024; /// A pull answer larger than this hands the remaining ids back as `deferred`. const PULL_RESPONSE_BUDGET: usize = 32 * 1024 * 1024; const MAX_HEAD_BYTES: usize = 1024 * 1024; -/// What the cipher adds to a plaintext at most (a block of padding): an object stored at a -/// cap is that much larger than the cap when read back. -const CIPHER_PADDING: usize = 16; +/// What the cipher adds to a plaintext at most: an object stored at a cap is that much larger +/// than the cap when read back. +const CIPHER_PADDING: usize = MAX_BYTES_OVERHEAD; /// The browser bounds an image to a 1568 px edge and re-encodes past 700 KB; this is /// well above what that produces. const MAX_IMAGE_BYTES: usize = 4 * 1024 * 1024; @@ -120,6 +121,15 @@ pub fn workspaced_service() -> Router { ) } +fn backup_format(current: CipherFormat, uptime: std::time::Duration) -> CipherFormat { + // A previous-release server reads only CBC here: GCM waits for it to be rolled out. + if current == CipherFormat::V2 && uptime >= PREVIOUS_RELEASE_ROLLOUT_UPTIME { + CipherFormat::V2 + } else { + CipherFormat::LegacyCbc + } +} + /// What reading an object yields. `Gone`: not there (deleted since the listing, or never /// pushed). `Grown`: larger than expected, so replaced since the listing (or planted), and /// left unread; a pull answers with a page ending before it rather than without it. @@ -135,7 +145,7 @@ enum Read { /// The user's prefix in the workspace storage, plus what reads and writes it. struct Backend { store: Arc, - mc: MagicCrypt256, + mc: WorkspaceCrypt, prefix: String, /// Name the storage and the generation the objects are under, for the browser's sync /// state: a row recorded against another storage or generation is stale, a removal is @@ -214,7 +224,8 @@ impl Backend { } fn seal(&self, plaintext: &[u8]) -> Vec { - self.mc.encrypt_bytes_to_bytes(plaintext) + let format = backup_format(CipherFormat::current(), process_uptime()); + self.mc.encrypt_bytes_in(plaintext, format) } /// Bytes written. @@ -255,7 +266,7 @@ impl Backend { // apart beyond the cipher's padding check, which a wrong key passes now and then. match self .mc - .decrypt_bytes_to_bytes(&bytes) + .decrypt_bytes(&bytes) .ok() .and_then(|plaintext| String::from_utf8(plaintext).ok()) { @@ -1632,3 +1643,32 @@ async fn push( results, })) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn backups_are_written_in_gcm_only_once_the_previous_release_is_rolled_out() { + let just_short = PREVIOUS_RELEASE_ROLLOUT_UPTIME - std::time::Duration::from_secs(1); + for (current, uptime, expected) in [ + ( + CipherFormat::V2, + PREVIOUS_RELEASE_ROLLOUT_UPTIME, + CipherFormat::V2, + ), + (CipherFormat::V2, just_short, CipherFormat::LegacyCbc), + ( + CipherFormat::LegacyCbc, + PREVIOUS_RELEASE_ROLLOUT_UPTIME * 4, + CipherFormat::LegacyCbc, + ), + ] { + assert_eq!( + backup_format(current, uptime), + expected, + "{current:?} {uptime:?}" + ); + } + } +} diff --git a/backend/windmill-api/src/ai_shared_sessions.rs b/backend/windmill-api/src/ai_shared_sessions.rs new file mode 100644 index 0000000000..c6554305db --- /dev/null +++ b/backend/windmill-api/src/ai_shared_sessions.rs @@ -0,0 +1,368 @@ +/* + * Author: Ruben Fiszel + * Copyright: Windmill Labs, Inc 2026 + * This file and its contents are licensed under the AGPLv3 License. + * Please see the included NOTICE for copyright information and + * LICENSE-AGPL for a copy of the license. + */ + +//! Read-only snapshots of AI session transcripts, shared by their author. +//! +//! Sessions live in the author's browser; a row here exists only because the author asked for +//! a link. A share is readable by the members of its workspace, or by anyone holding the link +//! once its author makes it public. The snapshot is whatever the author's browser sent, so the +//! viewer treats it as untrusted data. + +use crate::db::{ApiAuthed, DB}; +use axum::{ + extract::{DefaultBodyLimit, Extension, Json, Path, Query}, + routing::{delete, get, post}, + Router, +}; +use chrono::{DateTime, Utc}; +use serde::{Deserialize, Serialize}; +use serde_json::value::RawValue; +use uuid::Uuid; +use windmill_api_auth::{is_effectively_unscoped, OptAuthed}; +use windmill_audit::{audit_oss::audit_log, ActionKind}; +use windmill_common::error::{Error, JsonResult, Result}; + +const MAX_SNAPSHOT_BYTES: usize = 10 * 1024 * 1024; +const MAX_NAME_CHARS: usize = 255; +const MAX_SESSION_ID_CHARS: usize = 255; +const SHARE_BODY_LIMIT: usize = MAX_SNAPSHOT_BYTES + 64 * 1024; + +pub fn workspaced_service() -> Router { + Router::new() + .route( + "/share", + post(share_session).layer(DefaultBodyLimit::max(SHARE_BODY_LIMIT)), + ) + .route("/status", get(get_share_status)) + .route("/set_public/{id}", post(set_public)) + .route("/delete/{id}", delete(unshare_session)) +} + +/// Mounted outside the authenticated router: a public share is served to anyone. +pub fn workspaced_unauthed_service() -> Router { + Router::new().route("/get/{id}", get(get_shared_session)) +} + +#[derive(Deserialize)] +struct ShareSession { + session_id: String, + name: String, + /// Left as it is on an existing share when absent; a new share starts private. + is_public: Option, + message_count: i32, + snapshot: Box, +} + +#[derive(Serialize)] +struct SharedSessionInfo { + id: Uuid, + name: String, + is_public: bool, + message_count: i32, + created_by: String, + shared_at: DateTime, +} + +#[derive(Serialize)] +struct SharedSession { + #[serde(flatten)] + info: SharedSessionInfo, + snapshot: Box, + /// Whether the caller may stop sharing it: its author, or a workspace admin. + can_unshare: bool, +} + +#[derive(Serialize)] +struct ShareStatus { + #[serde(skip_serializing_if = "Option::is_none")] + share: Option, +} + +#[derive(Deserialize)] +struct ShareStatusQuery { + session_id: String, +} + +#[derive(Deserialize)] +struct SetPublic { + is_public: bool, +} + +/// Sharing exposes the author's own browser state, so only the author's own unscoped token may +/// do it: a job token can carry an `on_behalf_of` identity, and every scoped token (guest, +/// embed, app policy, MCP) was minted for something narrower. +fn require_plain_user_token(authed: &ApiAuthed) -> Result<()> { + if authed.job_id.is_some() || !is_effectively_unscoped(authed.scopes.as_deref()) { + return Err(Error::PermissionDenied( + "Shared AI sessions are only reachable with an unscoped user token".to_string(), + )); + } + Ok(()) +} + +/// It is compared against a `VARCHAR(255)` column, and Postgres answers a NUL in a text +/// parameter with an opaque 500. +fn check_session_id(session_id: &str) -> Result<()> { + if session_id.is_empty() || session_id.chars().count() > MAX_SESSION_ID_CHARS { + return Err(Error::BadRequest(format!( + "Session id must be between 1 and {MAX_SESSION_ID_CHARS} characters" + ))); + } + if session_id.contains('\0') { + return Err(Error::BadRequest( + "Session id cannot contain NUL characters".to_string(), + )); + } + Ok(()) +} + +/// Share a session, or move the caller's existing link for it to this snapshot. +async fn share_session( + authed: ApiAuthed, + Extension(db): Extension, + Path(w_id): Path, + Json(payload): Json, +) -> JsonResult { + require_plain_user_token(&authed)?; + check_session_id(&payload.session_id)?; + let name = payload.name.trim(); + if name.is_empty() || name.chars().count() > MAX_NAME_CHARS || name.contains('\0') { + return Err(Error::BadRequest(format!( + "Session name must be between 1 and {MAX_NAME_CHARS} characters, without NUL" + ))); + } + let snapshot = payload.snapshot.get(); + if snapshot.len() > MAX_SNAPSHOT_BYTES { + return Err(Error::BadRequest(format!( + "Session snapshot is {} bytes, above the {MAX_SNAPSHOT_BYTES} byte limit", + snapshot.len() + ))); + } + if !snapshot.trim_start().starts_with('{') { + return Err(Error::BadRequest( + "Session snapshot must be a JSON object".to_string(), + )); + } + if payload.message_count < 0 { + return Err(Error::BadRequest( + "Message count cannot be negative".to_string(), + )); + } + + let mut tx = db.begin().await?; + let row = sqlx::query!( + r#"INSERT INTO ai_shared_session + (workspace_id, session_id, email, created_by, name, is_public, message_count, snapshot) + VALUES ($1, $2, $3, $4, $5, COALESCE($6, false), $7, $8) + ON CONFLICT (workspace_id, email, session_id) DO UPDATE + SET created_by = EXCLUDED.created_by, + name = EXCLUDED.name, + is_public = COALESCE($6, ai_shared_session.is_public), + message_count = EXCLUDED.message_count, + snapshot = EXCLUDED.snapshot, + shared_at = now() + RETURNING id, is_public, shared_at, (xmax = 0) AS "inserted!""#, + &w_id, + &payload.session_id, + &authed.email, + &authed.username, + name, + payload.is_public, + payload.message_count, + snapshot, + ) + .fetch_one(&mut *tx) + .await?; + + let id = row.id.to_string(); + let public = row.is_public.to_string(); + audit_log( + &mut *tx, + &authed, + "ai.shared_sessions.share", + if row.inserted { + ActionKind::Create + } else { + ActionKind::Update + }, + &w_id, + Some(&id), + Some([("name", name), ("public", public.as_str())].into()), + ) + .await?; + tx.commit().await?; + + Ok(Json(SharedSessionInfo { + id: row.id, + name: name.to_string(), + is_public: row.is_public, + message_count: payload.message_count, + created_by: authed.username.clone(), + shared_at: row.shared_at, + })) +} + +/// The caller's own share of one of their sessions, if any. +async fn get_share_status( + authed: ApiAuthed, + Extension(db): Extension, + Path(w_id): Path, + Query(query): Query, +) -> JsonResult { + require_plain_user_token(&authed)?; + check_session_id(&query.session_id)?; + let share = sqlx::query_as!( + SharedSessionInfo, + "SELECT id, name, is_public, message_count, created_by, shared_at FROM ai_shared_session + WHERE workspace_id = $1 AND email = $2 AND session_id = $3", + &w_id, + &authed.email, + &query.session_id, + ) + .fetch_optional(&db) + .await?; + + Ok(Json(ShareStatus { share })) +} + +/// Only the author changes who can open their link; an admin may only take it down. +async fn set_public( + authed: ApiAuthed, + Extension(db): Extension, + Path((w_id, id)): Path<(String, Uuid)>, + Json(payload): Json, +) -> JsonResult { + require_plain_user_token(&authed)?; + let mut tx = db.begin().await?; + let info = sqlx::query_as!( + SharedSessionInfo, + "UPDATE ai_shared_session SET is_public = $4 + WHERE workspace_id = $1 AND id = $2 AND email = $3 + RETURNING id, name, is_public, message_count, created_by, shared_at", + &w_id, + id, + &authed.email, + payload.is_public, + ) + .fetch_optional(&mut *tx) + .await? + .ok_or_else(|| { + Error::NotFound(format!( + "Shared session {id} not found, or not shared by you" + )) + })?; + + let id_str = id.to_string(); + let public = info.is_public.to_string(); + audit_log( + &mut *tx, + &authed, + "ai.shared_sessions.set_public", + ActionKind::Update, + &w_id, + Some(&id_str), + Some([("name", info.name.as_str()), ("public", public.as_str())].into()), + ) + .await?; + tx.commit().await?; + + Ok(Json(info)) +} + +/// A public share is served to anyone with the link; any other one only to a member of its +/// workspace, which is what an `ApiAuthed` resolved on a `/w/{workspace_id}` path is. +async fn get_shared_session( + OptAuthed(opt_authed): OptAuthed, + Extension(db): Extension, + Path((w_id, id)): Path<(String, Uuid)>, +) -> JsonResult { + let row = sqlx::query!( + "SELECT id, email, name, is_public, message_count, created_by, snapshot, shared_at + FROM ai_shared_session + WHERE workspace_id = $1 AND id = $2", + &w_id, + id, + ) + .fetch_optional(&db) + .await?; + + let not_found = || { + Error::NotFound(format!( + "Shared session {id} not found: it may have been unshared, or be visible only to members of {w_id}" + )) + }; + let member = opt_authed + .as_ref() + .filter(|a| a.job_id.is_none() && is_effectively_unscoped(a.scopes.as_deref())); + let row = match row { + Some(row) if row.is_public || member.is_some() => row, + // A missing share and a private one answer a stranger alike, so the link does not + // confirm that a private share exists. + _ if member.is_none() => { + return Err(Error::NotAuthorized(format!( + "Shared session {id} is not public: sign in as a member of {w_id} to open it" + ))) + } + _ => return Err(not_found()), + }; + + Ok(Json(SharedSession { + can_unshare: member.is_some_and(|a| row.email == a.email || a.is_admin), + snapshot: RawValue::from_string(row.snapshot).map_err(|e| { + Error::internal_err(format!("Stored session snapshot is not valid JSON: {e}")) + })?, + info: SharedSessionInfo { + id: row.id, + name: row.name, + is_public: row.is_public, + message_count: row.message_count, + created_by: row.created_by, + shared_at: row.shared_at, + }, + })) +} + +async fn unshare_session( + authed: ApiAuthed, + Extension(db): Extension, + Path((w_id, id)): Path<(String, Uuid)>, +) -> Result { + require_plain_user_token(&authed)?; + let mut tx = db.begin().await?; + let name = sqlx::query_scalar!( + "DELETE FROM ai_shared_session + WHERE workspace_id = $1 AND id = $2 AND (email = $3 OR $4::bool) + RETURNING name", + &w_id, + id, + &authed.email, + authed.is_admin, + ) + .fetch_optional(&mut *tx) + .await? + .ok_or_else(|| { + Error::NotFound(format!( + "Shared session {id} not found, or not shared by you" + )) + })?; + + let id_str = id.to_string(); + audit_log( + &mut *tx, + &authed, + "ai.shared_sessions.unshare", + ActionKind::Delete, + &w_id, + Some(&id_str), + Some([("name", name.as_str())].into()), + ) + .await?; + tx.commit().await?; + + Ok(format!("Stopped sharing {name}")) +} diff --git a/backend/windmill-api/src/apps.rs b/backend/windmill-api/src/apps.rs index 26b369ce74..944535dd84 100644 --- a/backend/windmill-api/src/apps.rs +++ b/backend/windmill-api/src/apps.rs @@ -56,15 +56,19 @@ use std::str; use windmill_audit::audit_oss::{audit_log, AuditAuthorable}; use windmill_audit::ActionKind; use windmill_common::{ - apps::{AppScriptId, ListAppQuery, APP_WORKSPACED_ROUTE}, + apps::{ + app_value_has_inline_script, app_value_runnable_paths, AppScriptId, ListAppQuery, + APP_WORKSPACED_ROUTE, + }, auth::{APP_EMBED_TOKEN_LABEL_PREFIX, RAW_APP_SDK_TOKEN_LABEL_PREFIX, TOKEN_PREFIX_LEN}, - cache::{self, future::FutureCachedExt}, + cache, db::{DbWithOptAuthed, UserDB}, error::{to_anyhow, Error, JsonResult, Result}, jobs::{ get_payload_tag_from_prefixed_path, resolve_delete_after_secs, schedule_job_deletion, JobPayload, JobTriggerKind, RawCode, }, + scripts::ScriptLang, triggers::TriggerMetadata, user_drafts::{overlay_or_draft_only, DraftUserRef, UserDraftItemKind, WithDraftOverlay}, users::username_to_permissioned_as, @@ -75,7 +79,8 @@ use windmill_common::{ variables::{build_crypt, build_crypt_with_key_suffix, encrypt}, worker::{to_raw_value, CLOUD_HOSTED}, workspaces::{ - check_deploy_rules, check_user_against_rule, ProtectionRuleKind, RuleCheckResult, + check_deploy_rules, check_operator_can_build, check_user_against_rule, + operator_builder_rights, BuilderKind, ProtectionRuleKind, RuleCheckResult, }, HUB_BASE_URL, }; @@ -477,6 +482,12 @@ pub struct PolicyTriggerableInputs { sensitive_inputs: Vec, #[serde(default, skip_serializing_if = "Option::is_none")] tag: Option, + /// The runnable reads data as the app's viewer rather than as the app's identity: data table + /// connections that name no role, and object storage advanced permission rules. Honored for + /// inline runnables only: their code is deployed with the app, so it is the publisher who + /// chose to read with the viewer's rights. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + viewer_data_access: bool, } #[derive(Serialize, Deserialize, Debug, Clone)] @@ -749,7 +760,7 @@ async fn list_apps( // Append the authed user's `app`/`raw_app` drafts at paths with no deployed app; // see scripts.rs. if lq.include_draft_only.unwrap_or(false) - && !authed.is_operator + && (!authed.is_operator || operator_builder_rights(&db, &w_id).await?.apps) && offset == 0 && lq.path_start.is_none() && lq.path_exact.is_none() @@ -1005,7 +1016,6 @@ fn raw_app_wrapper_html(secret: &str) -> String { -App @@ -331,8 +331,8 @@ custom integrations. ## For AI coding agents When asked to add a chat over a Windmill flow: the flow must be deployed with chat mode -on. Pick the entry point from the table at the top (`useChat` → `windmill-chat/ai-sdk`, -assistant-ui → `windmill-chat/assistant-ui`, otherwise `windmill-chat/react`). Inside a +on. Pick the entry point from the table at the top (`useChat` → `@windmill-labs/chat-sdk/ai-sdk`, +assistant-ui → `@windmill-labs/chat-sdk/assistant-ui`, otherwise `@windmill-labs/chat-sdk/react`). Inside a Windmill raw app pass only `flowPath`. Elsewhere pass `baseUrl`, `workspace` and a `token`; for a public page use a token scoped to `jobs:run:flows:` and leave `history` at its default. Render `role`, `content`, `pending`, `success` and diff --git a/chat-sdk/package-lock.json b/chat-sdk/package-lock.json index 692e5d33f5..93d3e00348 100644 --- a/chat-sdk/package-lock.json +++ b/chat-sdk/package-lock.json @@ -1,12 +1,12 @@ { - "name": "windmill-chat", - "version": "1.827.0", + "name": "@windmill-labs/chat-sdk", + "version": "1.841.0", "lockfileVersion": 3, "requires": true, "packages": { "": { - "name": "windmill-chat", - "version": "1.827.0", + "name": "@windmill-labs/chat-sdk", + "version": "1.841.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 287636a9f8..ca4b73df45 100644 --- a/chat-sdk/package.json +++ b/chat-sdk/package.json @@ -1,7 +1,7 @@ { - "name": "windmill-chat", + "name": "@windmill-labs/chat-sdk", "description": "Build chat interfaces on Windmill flows deployed in chat mode, from any frontend or raw app", - "version": "1.827.0", + "version": "1.841.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 0e0885f563..db6fd253bf 100644 --- a/cli/bun.lock +++ b/cli/bun.lock @@ -19,14 +19,14 @@ "pg-gateway": "0.3.0-beta.4", "svelte": "^5.56.8", "tar-stream": "^3.1.7", - "windmill-parser-wasm-asset": "1.753.0", + "windmill-parser-wasm-asset": "1.830.0", "windmill-parser-wasm-csharp": "1.510.1", "windmill-parser-wasm-go": "1.761.0", "windmill-parser-wasm-java": "1.510.1", "windmill-parser-wasm-nu": "1.510.1", "windmill-parser-wasm-php": "1.647.1", - "windmill-parser-wasm-py": "1.782.0", - "windmill-parser-wasm-py-imports": "1.693.1", + "windmill-parser-wasm-py": "1.830.0", + "windmill-parser-wasm-py-imports": "1.830.0", "windmill-parser-wasm-r": "1.668.1", "windmill-parser-wasm-regex": "1.764.0", "windmill-parser-wasm-ruby": "1.526.1", @@ -291,7 +291,7 @@ "utility-types": ["utility-types@3.11.0", "", {}, "sha512-6Z7Ma2aVEWisaL6TvBCy7P8rm2LQoPv6dJ7ecIaIixHcwfbJ0x7mWdbcwlIM5IGQxPZSFYeqRCqlOOeKoJYMkw=="], - "windmill-parser-wasm-asset": ["windmill-parser-wasm-asset@1.753.0", "", {}, "sha512-zpJhjvcU8EWRoOJzas/nRGKjGdQnvzeB9GOxP+Mdmnk8BFk3uehsmHS2Krxyjo36fUrCHqobbnffEqf0g3LIGg=="], + "windmill-parser-wasm-asset": ["windmill-parser-wasm-asset@1.830.0", "", {}, "sha512-q4HSaMOd5cF8pmfPcEGiGeQbO8vhtv89us7zbO12IlgpxpWT8ojvw66J75y4yUt1PaEuaoztSaX8Gkxxn/6MXw=="], "windmill-parser-wasm-csharp": ["windmill-parser-wasm-csharp@1.510.1", "", {}, "sha512-qm09YmnbeYHLwYn1jUnObVzPhYO9NZKMlIO7nlo7zPJBXqksgG5fK/KCtwGw9rChrnz+DsvM9wP5FhrwRLMtwQ=="], @@ -303,9 +303,9 @@ "windmill-parser-wasm-php": ["windmill-parser-wasm-php@1.647.1", "", {}, "sha512-u2qaMkupSdhJibxvkLh3r/y36IARvnYNTLXWvOKxcQ0G/BPUB4+yF5o/yf47vv9zUV5WZv4mrdsKDt/pZDYeDg=="], - "windmill-parser-wasm-py": ["windmill-parser-wasm-py@1.782.0", "", {}, "sha512-ZnpEvhbffaJI+Uq7HH1mVO6kUgR4uiAIIxaLa30Pqb1/oz0h4abT6W7bFOApIE5X9SDOuycoaDBEr9Ogm6ZLzQ=="], + "windmill-parser-wasm-py": ["windmill-parser-wasm-py@1.830.0", "", {}, "sha512-+P4mIyp3lXkgjsr3/20Oc31ank8orQDd4K/v8TnjTQnCyxyy+VB9rynLESnkH6OlcEVSk2qf9pDM9c367E8DoQ=="], - "windmill-parser-wasm-py-imports": ["windmill-parser-wasm-py-imports@1.693.1", "", {}, "sha512-FC0KbREe2G/sa/9kYIR930wmWw+VL6PvEIqg12J3dsJes3A+0x5JIUPT/jeD+c24DrG0ko/Ub7yDnYs56Bem7g=="], + "windmill-parser-wasm-py-imports": ["windmill-parser-wasm-py-imports@1.830.0", "", {}, "sha512-Pi9gHStNFTEqfcDrjSxK5SnI/1dTG4xKcVUD3BHlR1aQ7E/VxkTD/D0INJm7mNC2usKb2bO21NMdKmGh+RAXEw=="], "windmill-parser-wasm-r": ["windmill-parser-wasm-r@1.668.1", "", {}, "sha512-5YNeUibxpNBvYrxCgQcz1PxGhTFx2CyEpg2udtIhq7bx0d4gF/KDZVupMeQmAObmrEtTSFGUWNRJ4zXSWNrSpQ=="], diff --git a/cli/package.json b/cli/package.json index 5e7623a7ab..5efe8a2499 100644 --- a/cli/package.json +++ b/cli/package.json @@ -31,14 +31,14 @@ "pg-gateway": "0.3.0-beta.4", "svelte": "^5.56.8", "tar-stream": "^3.1.7", - "windmill-parser-wasm-asset": "1.753.0", + "windmill-parser-wasm-asset": "1.830.0", "windmill-parser-wasm-csharp": "1.510.1", "windmill-parser-wasm-go": "1.761.0", "windmill-parser-wasm-java": "1.510.1", "windmill-parser-wasm-nu": "1.510.1", "windmill-parser-wasm-php": "1.647.1", - "windmill-parser-wasm-py": "1.782.0", - "windmill-parser-wasm-py-imports": "1.693.1", + "windmill-parser-wasm-py": "1.830.0", + "windmill-parser-wasm-py-imports": "1.830.0", "windmill-parser-wasm-r": "1.668.1", "windmill-parser-wasm-regex": "1.764.0", "windmill-parser-wasm-ruby": "1.526.1", diff --git a/cli/src/commands/app/app.ts b/cli/src/commands/app/app.ts index 0d4ad634c8..b4d8230bdb 100644 --- a/cli/src/commands/app/app.ts +++ b/cli/src/commands/app/app.ts @@ -32,6 +32,9 @@ export interface AppFile { guests?: boolean; value: any; public?: boolean; + sandbox?: boolean; + frontend_api?: string[]; + custom_path?: string; summary: string; policy: Policy; // Mirrors granular ACLs on the app path. Omitted from app.yaml when no @@ -113,6 +116,44 @@ export function replaceInlineScripts( } return []; } +/** `parent_version` is the editor's stale-draft base: a version id that changes on + * every deploy and means nothing in another workspace, so it is kept out of the + * tracked file and out of what a push deploys. */ +export function stripEditorState(app: any) { + if (app?.value && typeof app.value == "object") { + delete app.value.parent_version; + } +} +/** The backend requires admin for any update that carries `custom_path`, even + * an unchanged one, so a value read from a checkout must only be sent when it + * differs from the deployed one or a non-admin can no longer deploy the app. */ +export function changedCustomPath( + local: string | undefined, + deployed: { custom_path?: string } | undefined, +): string | undefined { + return (local ?? "") === (deployed?.custom_path ?? "") ? undefined : local; +} + +/** Applies a workspace's `..custom_path.yaml`. An empty value + * clears the custom path; the app (low-code or raw) must already exist. */ +export async function pushAppCustomPath( + workspace: string, + remotePath: string, + localFile: { custom_path?: string } | undefined, +): Promise { + remotePath = remotePath.replaceAll(SEP, "/"); + const deployed = await wmill.getAppByPath({ workspace, path: remotePath }); + const customPath = changedCustomPath(localFile?.custom_path ?? "", deployed); + if (customPath === undefined) { + return; + } + log.info(colors.bold.yellow(`Setting custom path of app ${remotePath}...`)); + await wmill.updateApp({ + workspace, + path: remotePath, + requestBody: { custom_path: customPath, skip_draft_deletion: true }, + }); +} export function isExecutionModeAnonymous(app: any) { return app?.["policy"]?.["execution_mode"] == "anonymous"; } @@ -160,12 +201,107 @@ export function executionModeForPush( } return deployedPolicy?.execution_mode === "viewer" ? "viewer" : "publisher"; } +/** Mirrors `FRONTEND_SDK_ALLOWED_SCOPES` in the backend's `apps.rs`, which stays + * the authority: this copy only fails a push before it bundles. */ +export const FRONTEND_API_SCOPES = [ + "jobs:run", + "jobs:read", + "users:read", + "resources:read", + "variables:read", + "flow_conversations:read", + "flow_conversations:write", +]; + +export type AppIsolation = { sandbox: boolean; frontendApi: string[] }; + +/** Write `sandbox` and `frontend_api` on a pulled app, only when they are on, so + * an app using neither keeps the file it had. Scopes of an unsandboxed app are + * inert and stay out: a file stating them without `sandbox` does not push. */ +export function markIsolationFromPolicy(app: any, rawApp: boolean) { + if (app?.["policy"]?.["sandbox"] !== true) { + return; + } + app.sandbox = true; + const scopes = app.policy.frontend_sdk_scopes; + if (rawApp && Array.isArray(scopes) && scopes.length > 0) { + app.frontend_api = scopes; + } +} + +/** The isolation the tracked file states, or `undefined` when it has no `sandbox` + * key and the deployed policy carries over. A file that has the key states both + * fields: `sandbox: false` turns isolation off, and a missing `frontend_api` + * means no scopes. */ +export function statedIsolation( + localApp: any, + rawApp: boolean, +): AppIsolation | undefined { + const sandbox = localApp?.["sandbox"]; + const scopes = localApp?.["frontend_api"] ?? []; + if (sandbox !== undefined && typeof sandbox !== "boolean") { + throw new Error("'sandbox' must be true or false"); + } + if ( + !Array.isArray(scopes) || + scopes.some((s: unknown) => typeof s !== "string") + ) { + throw new Error("'frontend_api' must be a list of scopes"); + } + if (scopes.length > 0 && !rawApp) { + throw new Error("'frontend_api' is only available to full-code apps"); + } + const seen = new Set(); + for (const scope of scopes) { + if (!FRONTEND_API_SCOPES.includes(scope)) { + throw new Error( + `Invalid frontend_api scope '${scope}'. Allowed scopes: ${FRONTEND_API_SCOPES.join(", ")}`, + ); + } + if (seen.has(scope)) { + throw new Error(`Duplicate frontend_api scope '${scope}'`); + } + seen.add(scope); + } + if (scopes.length > 0 && sandbox !== true) { + throw new Error( + "'frontend_api' requires 'sandbox: true': an unsandboxed app gets no frontend API token", + ); + } + return sandbox === undefined ? undefined : { sandbox, frontendApi: scopes }; +} + +/** Whether the deployed policy already has the stated isolation. The file's two + * keys are kept out of the superset comparison against the deployed app, which + * could not see a key the file dropped. */ +export function isolationUpToDate( + isolation: AppIsolation | undefined, + deployedPolicy: Policy | undefined, + rawApp: boolean, +): boolean { + if (!isolation) { + return true; + } + if ((deployedPolicy?.sandbox === true) !== isolation.sandbox) { + return false; + } + if (!rawApp) { + return true; + } + const deployed = deployedPolicy?.frontend_sdk_scopes ?? []; + return ( + deployed.length === isolation.frontendApi.length && + deployed.every((s, i) => s === isolation.frontendApi[i]) + ); +} + export async function pushApp( workspace: string, remotePath: string, localPath: string, message?: string, - permissionedAsContext?: PermissionedAsContext + permissionedAsContext?: PermissionedAsContext, + customPathFromFile = true ): Promise { if (alreadySynced.includes(localPath)) { return; @@ -198,6 +334,8 @@ export async function pushApp( } const path = localPath + "app.yaml"; const localApp = (await yamlParseFile(path)) as AppFile; + stripEditorState(localApp); + const isolation = statedIsolation(localApp, false); replaceInlineScripts(localApp.value, localPath, true); // On create the backend applies folder defaults, so there is nothing to preserve. @@ -210,17 +348,29 @@ export async function pushApp( localApp, remotePath, executionModeForPush(localApp, deployedPolicy), - basePolicy(localApp, deployedPolicy, !!preserveFields.preserve_on_behalf_of) + basePolicy(localApp, deployedPolicy, !!preserveFields.preserve_on_behalf_of), + isolation ); // extra_perms goes through /acls/* — strip from the body so a perms-only // edit never bumps the app version (see applyExtraPermsDiff for details). - const { extra_perms: localPerms, ...localAppBody } = localApp as AppFile & { + const { + extra_perms: localPerms, + sandbox: _sandbox, + frontend_api: _frontendApi, + custom_path: localCustomPath, + ...localAppBody + } = localApp as AppFile & { extra_perms?: Record; }; + const customPath = customPathFromFile ? localCustomPath : undefined; if (app) { - if (isSuperset(localAppBody, app)) { + if ( + isSuperset(localAppBody, app) && + changedCustomPath(customPath, app) === undefined && + isolationUpToDate(isolation, deployedPolicy, false) + ) { log.info(colors.green(`App ${remotePath} is up to date`)); } else { log.info(colors.bold.yellow(`Updating app ${remotePath}...`)); @@ -230,6 +380,7 @@ export async function pushApp( requestBody: { deployment_message: message, ...localAppBody, + custom_path: changedCustomPath(customPath, app), ...preserveFields, // Preserve any user draft at this path (see backend skip_draft_deletion). skip_draft_deletion: true, @@ -245,6 +396,7 @@ export async function pushApp( path: remotePath, deployment_message: message, ...localAppBody, + ...(customPath ? { custom_path: customPath } : {}), ...preserveFields, // Preserve any user draft at this path (see backend skip_draft_deletion). skip_draft_deletion: true, @@ -269,12 +421,13 @@ export async function generatingPolicy( app: any, path: string, executionMode: AppExecutionMode, - base: Policy | undefined + base: Policy | undefined, + isolation?: AppIsolation ) { log.info(colors.gray(`Generating fresh policy for app ${path}...`)); try { app.policy = await windmillUtils.updatePolicy(app.value, base); - finalizeDerivedPolicy(app.policy, executionMode); + finalizeDerivedPolicy(app.policy, executionMode, isolation); } catch (e) { log.error(colors.red(`Error generating policy for app ${path}: ${e}`)); throw e; @@ -332,10 +485,21 @@ export function preserveOnBehalfOfFields( * deployed app would keep being able to run runnables this push removed. */ export function finalizeDerivedPolicy( policy: Policy, - executionMode: AppExecutionMode + executionMode: AppExecutionMode, + isolation?: AppIsolation, + rawApp: boolean = false ) { policy.triggerables = undefined; policy.execution_mode = executionMode; + if (isolation) { + // `false` is sent rather than left out: the server reads an omitted value as + // "no opinion" and may sandbox the app anyway, hiding that the file was refused. + policy.sandbox = isolation.sandbox; + if (rawApp) { + policy.frontend_sdk_scopes = + isolation.frontendApi.length > 0 ? isolation.frontendApi : undefined; + } + } } async function list(opts: GlobalOptions & { includeDraftOnly?: boolean; json?: boolean }) { diff --git a/cli/src/commands/app/bundle.ts b/cli/src/commands/app/bundle.ts index 286e878cfb..287d01ebed 100644 --- a/cli/src/commands/app/bundle.ts +++ b/cli/src/commands/app/bundle.ts @@ -58,10 +58,10 @@ function conditionsFor(svelte: boolean): string[] { /** * Detects which frontend frameworks are present in package.json */ -export function detectFrameworks(appDir: string): { svelte: boolean; vue: boolean } { +export function detectFrameworks(appDir: string): { svelte: boolean } { const packageJsonPath = path.join(appDir, "package.json"); if (!fs.existsSync(packageJsonPath)) { - return { svelte: false, vue: false }; + return { svelte: false }; } try { @@ -73,10 +73,9 @@ export function detectFrameworks(appDir: string): { svelte: boolean; vue: boolea return { svelte: "svelte" in allDeps, - vue: "vue" in allDeps, }; } catch { - return { svelte: false, vue: false }; + return { svelte: false }; } } @@ -256,17 +255,6 @@ export async function createFrameworkPlugins(appDir: string): Promise { plugins.push(createSveltePlugin(appDir)); } - if (frameworks.vue) { - log.info(colors.blue("🔧 Vue detected, adding vue plugin...")); - throw new Error("Vue plugin not supported yet"); - // try { - // const esbuildPluginVue = await import("esbuild-plugin-vue3"); - // plugins.push(esbuildPluginVue.default()); - // } catch (error: any) { - // log.warn(colors.yellow(`Failed to load vue plugin: ${error.message}`)); - // } - } - return plugins; } @@ -313,7 +301,7 @@ export async function createBundle( // Use the entryPoint's directory if provided, otherwise fall back to cwd. const appDir = options.entryPoint ? path.dirname(options.entryPoint) : process.cwd(); const frameworks = detectFrameworks(appDir); - const defaultEntry = (frameworks.svelte || frameworks.vue) ? "index.ts" : "index.tsx"; + const defaultEntry = frameworks.svelte ? "index.ts" : "index.tsx"; const entryPoint = options.entryPoint ?? defaultEntry; const outDir = options.outDir ?? "dist"; @@ -331,7 +319,7 @@ export async function createBundle( // Ensure node_modules exists in the app directory await ensureNodeModules(appDir); - // Load framework-specific plugins (svelte, vue) based on package.json + // Load framework-specific plugins (svelte) based on package.json const frameworkPlugins = await createFrameworkPlugins(appDir); // Ensure output directory exists diff --git a/cli/src/commands/app/bundle_command.ts b/cli/src/commands/app/bundle_command.ts index bef13f4268..c4119aafb0 100644 --- a/cli/src/commands/app/bundle_command.ts +++ b/cli/src/commands/app/bundle_command.ts @@ -12,10 +12,10 @@ interface BundleOptions { } /** Every entry point a raw app may have, most specific first, with the - * framework's preferred one promoted — Svelte and Vue mount from a `.ts`. */ + * framework's preferred one promoted — Svelte mounts from a `.ts`. */ function entryPointFor(appDir: string): string { const frameworks = detectFrameworks(appDir); - const candidates = frameworks.svelte || frameworks.vue + const candidates = frameworks.svelte ? ["index.ts", "index.tsx", "index.js"] : ["index.tsx", "index.ts", "index.js"]; const entry = candidates.find((c) => fs.existsSync(path.join(appDir, c))); diff --git a/cli/src/commands/app/dev.ts b/cli/src/commands/app/dev.ts index 2dac8639e2..fbeba2914f 100644 --- a/cli/src/commands/app/dev.ts +++ b/cli/src/commands/app/dev.ts @@ -67,7 +67,7 @@ const DEFAULT_PORT = 4000; const DEFAULT_HOST = "localhost"; // HTML template with live reload and SQL migration modal -const createHTML = (jsPath: string, cssPath: string) => ` +const createHTML = (jsPath: string, cssPath: string, appCtx: unknown) => ` @@ -228,6 +228,7 @@ const createHTML = (jsPath: string, cssPath: string) => ` + `; - -const indexVue = `import { createApp } from 'vue' -import App from './App.vue' -import "./index.css"; - -createApp(App).mount('#root')`; - const indexCss = `body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; @@ -171,21 +156,6 @@ const templates: Record = { "svelte": "^5.55.5", "windmill-client": "^1" } -}`, - }, - }, - vue: { - name: "Vue 3", - files: { - "/index.ts": indexVue, - "/App.vue": appVue, - "/index.css": indexCss, - "/package.json": `{ - "dependencies": { - "core-js": "3.26.1", - "vue": "3.5.13", - "windmill-client": "^1" - } }`, }, }, @@ -251,7 +221,7 @@ interface DataConfig { schema?: string; } -type FrameworkKey = "react19" | "react18" | "svelte5" | "vue"; +type FrameworkKey = "react19" | "react18" | "svelte5"; interface NewAppOptions extends GlobalOptions { /** App summary (short description). Skips the prompt when provided. */ @@ -384,7 +354,7 @@ async function newApp(opts: NewAppOptions) { } // Ask for framework (skipped if --framework is provided) - const VALID_FRAMEWORKS: FrameworkKey[] = ["react19", "react18", "svelte5", "vue"]; + const VALID_FRAMEWORKS: FrameworkKey[] = ["react19", "react18", "svelte5"]; let framework: string; if (opts.framework !== undefined) { if (!VALID_FRAMEWORKS.includes(opts.framework)) { @@ -403,7 +373,6 @@ async function newApp(opts: NewAppOptions) { { name: "React 19 (Recommended)", value: "react19" }, { name: "React 18", value: "react18" }, { name: "Svelte 5", value: "svelte5" }, - { name: "Vue 3", value: "vue" }, ], }); } @@ -624,6 +593,7 @@ CREATE SCHEMA IF NOT EXISTS ${schemaName}; // Create raw_app.yaml with data configuration const rawAppConfig: Record = { summary, + sandbox: true, }; // Add data configuration if present @@ -900,7 +870,7 @@ const command = new Command() ) .option( "--framework ", - "Framework template: react19 | react18 | svelte5 | vue. Skips the prompt when provided. Triggers non-interactive mode." + "Framework template: react19 | react18 | svelte5. Skips the prompt when provided. Triggers non-interactive mode." ) .option( "--datatable ", diff --git a/cli/src/commands/app/raw_apps.ts b/cli/src/commands/app/raw_apps.ts index 36c8260e25..ec526f2af2 100644 --- a/cli/src/commands/app/raw_apps.ts +++ b/cli/src/commands/app/raw_apps.ts @@ -20,13 +20,17 @@ import { deepEqual, readTextFile } from "../../utils/utils.ts"; import { type AppExecutionMode, + type AppIsolation, basePolicy, + changedCustomPath, executionModeForPush, finalizeDerivedPolicy, + isolationUpToDate, markAccessFromPolicy, preserveOnBehalfOfFields, replaceInlineScripts, repopulateFields, + statedIsolation, } from "./app.ts"; import type { PermissionedAsContext } from "../../core/permissioned_as.ts"; import { buildPermissionedAsContext } from "../../core/permissioned_as.ts"; @@ -49,6 +53,8 @@ export interface AppFile { runnables?: any; custom_path?: string; public?: boolean; + sandbox?: boolean; + frontend_api?: string[]; summary: string; policy: Policy; data?: { @@ -371,6 +377,7 @@ export async function pushRawApp( message?: string, defaultTs: "bun" | "deno" = "bun", permissionedAsContext?: PermissionedAsContext, + customPathFromFile = true, ): Promise { if (alreadySynced.includes(localPath)) { return; @@ -402,6 +409,7 @@ export async function pushRawApp( } const appFilePath = localPath + "raw_app.yaml"; const localApp = (await yamlParseFile(appFilePath)) as AppFile; + const isolation = statedIsolation(localApp, true); // Load runnables from separate YAML files in the backend folder // Falls back to reading from raw_app.yaml if no separate files exist (backward compat) @@ -454,6 +462,7 @@ export async function pushRawApp( deployedPolicy, !!preserveFields.preserve_on_behalf_of, ), + isolation, ); const files = await collectAppFiles(localPath); @@ -461,7 +470,7 @@ export async function pushRawApp( log.info(colors.yellow.bold(`Creating raw app ${remotePath} bundle...`)); // Detect frameworks to determine entry point const frameworks = detectFrameworks(localPath); - const entryFile = frameworks.svelte || frameworks.vue + const entryFile = frameworks.svelte ? "index.ts" : "index.tsx"; const entryPoint = localPath + entryFile; @@ -485,14 +494,24 @@ export async function pushRawApp( // to `.raw_app.json`, not `.app.json`. The backend granular_acls // handler routes "raw_app" to the `app` table (where v2 raw apps actually // live) while still dispatching DeployedObject::RawApp for git-sync. - const { extra_perms: localPerms, ...localAppNoPerms } = localApp as AppFile & { + const { + extra_perms: localPerms, + sandbox: _sandbox, + frontend_api: _frontendApi, + custom_path: localCustomPath, + ...localAppNoPerms + } = localApp as AppFile & { extra_perms?: Record; }; + const customPath = customPathFromFile ? localCustomPath : undefined; if (app) { // Check both metadata/runnables AND files for changes // Files need separate comparison because isSuperset only checks if local keys exist in remote - const metadataUpToDate = isSuperset({ ...localAppNoPerms, runnables }, app); + const metadataUpToDate = + isSuperset({ ...localAppNoPerms, runnables }, app) && + changedCustomPath(customPath, app) === undefined && + isolationUpToDate(isolation, deployedPolicy, true); const filesUpToDate = deepEqual(files, app.value?.files); if (metadataUpToDate && filesUpToDate) { log.info(colors.green(`App ${remotePath} is up to date`)); @@ -512,9 +531,7 @@ export async function pushRawApp( deployment_message: message, // Preserve any user draft at this path (see backend skip_draft_deletion). skip_draft_deletion: true, - ...(localApp.custom_path - ? { custom_path: localApp.custom_path } - : {}), + custom_path: changedCustomPath(customPath, app), }, js, css, @@ -534,9 +551,7 @@ export async function pushRawApp( deployment_message: message, // Preserve any user draft at this path (see backend skip_draft_deletion). skip_draft_deletion: true, - ...(localApp.custom_path - ? { custom_path: localApp.custom_path } - : {}), + ...(customPath ? { custom_path: customPath } : {}), }, js, css, @@ -555,16 +570,38 @@ export async function pushRawApp( ); } +/** + * `@windmill-labs/shared-utils` up to 1.0.13 derives the policy without `viewer_data_access`, + * which would silently deploy an inline runnable that asks to connect as its viewer as one + * connecting as the app. The server honors the flag on inline runnables only. + */ +export function carryViewerDataAccess( + runnables: Record | undefined, + policy: Policy | undefined, +) { + const triggerables = policy?.triggerables_v2 as Record | undefined; + if (!runnables || !triggerables) return; + for (const [id, runnable] of Object.entries(runnables)) { + if (runnable?.viewer_data_access !== true) continue; + if (runnable.type !== "inline" && runnable.type !== "runnableByName") continue; + for (const [key, triggerable] of Object.entries(triggerables)) { + if (key.startsWith(`${id}:rawscript/`)) triggerable.viewer_data_access = true; + } + } +} + export async function generatingPolicy( app: any, path: string, executionMode: AppExecutionMode, base: Policy | undefined, + isolation?: AppIsolation, ) { log.info(colors.gray(`Generating fresh policy for app ${path}...`)); try { app.policy = await windmillUtils.updateRawAppPolicy(app.runnables, base); - finalizeDerivedPolicy(app.policy, executionMode); + carryViewerDataAccess(app.runnables, app.policy); + finalizeDerivedPolicy(app.policy, executionMode, isolation, true); } catch (e) { log.error(colors.red(`Error generating policy for app ${path}: ${e}`)); throw e; diff --git a/cli/src/commands/datatable/datatable.ts b/cli/src/commands/datatable/datatable.ts index 3c0c5d6c65..2b6505de75 100644 --- a/cli/src/commands/datatable/datatable.ts +++ b/cli/src/commands/datatable/datatable.ts @@ -50,13 +50,19 @@ async function run( } function migrateNew( - opts: GlobalOptions & { datatable?: string }, + opts: GlobalOptions & { datatable?: string; schemas?: string }, name: string, ) { - createMigration(opts.datatable ?? DEFAULT_DATATABLE_NAME, name); + const schemas = (opts.schemas ?? "") + .split(",") + .map((s) => s.trim()) + .filter((s) => s !== ""); + createMigration(opts.datatable ?? DEFAULT_DATATABLE_NAME, name, schemas); } -async function migrateUp(opts: GlobalOptions & { datatable?: string }) { +async function migrateUp( + opts: GlobalOptions & { datatable?: string; schema?: string }, +) { const workspace = await resolveWorkspace(opts); await requireLogin(opts); const dt = opts.datatable ?? DEFAULT_DATATABLE_NAME; @@ -74,7 +80,7 @@ async function migrateUp(opts: GlobalOptions & { datatable?: string }) { // Push any locally-created/edited migration files first (without running // them), so `migrate up` works even before a `wmill sync push`. await pushLocalMigrations(workspace.workspaceId, dt); - await runMigrations(workspace.workspaceId, dt); + await runMigrations(workspace.workspaceId, dt, opts.schema); } async function migrateDown(opts: GlobalOptions & { datatable?: string }) { @@ -97,7 +103,12 @@ async function migrateStatus( }); // `migrate up` pushes local files before running, so they count as pending too. const remote = new Set(status.migrations.map((m) => m.timestamp)); - const migrations: { timestamp: number; name: string; status: string }[] = [ + const migrations: { + timestamp: number; + name: string; + status: string; + schemas?: string[]; + }[] = [ ...status.migrations, ...listLocalMigrations(dt) .filter((m) => !remote.has(m.timestamp)) @@ -124,7 +135,7 @@ async function migrateStatus( local: "pending (not pushed)", }; new Table() - .header(["Timestamp", "Name", "Status"]) + .header(["Timestamp", "Name", "Status", "Schemas"]) .padding(2) .border(true) .body( @@ -132,6 +143,9 @@ async function migrateStatus( String(m.timestamp), m.name, label[m.status] ?? m.status, + m.status === "local" + ? "" + : (m.schemas?.join(", ") ?? "whole database"), ]), ) .render(); @@ -145,6 +159,10 @@ const migrateCommand = new Command() "-d --datatable ", "Target datatable (default: main)", ) + .option( + "-s --schemas ", + "Comma-separated schemas the migration changes, written as its `-- schemas` line. Without it the migration applies to the whole database and every later migration waits for it", + ) .action(migrateNew as any) .command( "up", @@ -154,6 +172,10 @@ const migrateCommand = new Command() "-d --datatable ", "Target datatable (default: main)", ) + .option( + "--schema ", + "Apply only the pending migrations that declare this schema; refused while an earlier overlapping migration is pending", + ) .action(migrateUp as any) .command( "down", diff --git a/cli/src/commands/datatable_migrations.ts b/cli/src/commands/datatable_migrations.ts index a637f99968..49237257b0 100644 --- a/cli/src/commands/datatable_migrations.ts +++ b/cli/src/commands/datatable_migrations.ts @@ -44,16 +44,32 @@ function nextMigrationTimestamp(dir: string): string { return String(max >= now ? max + 1 : now); } +// Matches `is_annotatable_schema_name` on the server. +const SCHEMA_NAME_RE = /^[A-Za-z0-9_$-]{1,63}$/; + /** * Scaffold a new migration under migrations/datatable// as empty * `_.up.sql` and `.down.sql` files. Purely local — no network. + * `schemas` becomes the up file's leading `-- schemas` annotation, which the + * server reads as the migration's scope. */ -export function createMigration(datatable: string, name: string): void { +export function createMigration( + datatable: string, + name: string, + schemas: string[] = [], +): void { if (!MIGRATION_NAME_RE.test(name)) { throw new Error( `Invalid migration name '${name}': use only letters, digits, '_' and '-'`, ); } + for (const s of schemas) { + if (!SCHEMA_NAME_RE.test(s)) { + throw new Error( + `Invalid schema name '${s}': use only letters, digits, '_', '$' and '-'`, + ); + } + } const dir = path.join(process.cwd(), MIGRATIONS_DIR, datatable); fs.mkdirSync(dir, { recursive: true }); @@ -65,7 +81,9 @@ export function createMigration(datatable: string, name: string): void { // the template the UI's "New migration" modal seeds. const template = (direction: string) => `-- ${direction} migration: ${name}\nBEGIN;\n\n-- Add your migration here\n\nEND;\n`; - fs.writeFileSync(up, template("up"), "utf-8"); + const scope = + schemas.length > 0 ? `-- schemas ${schemas.join(", ")}\n` : ""; + fs.writeFileSync(up, scope + template("up"), "utf-8"); fs.writeFileSync(down, template("down"), "utf-8"); log.info( @@ -74,6 +92,13 @@ export function createMigration(datatable: string, name: string): void { for (const f of [up, down]) { log.info(colors.gray(` ${path.relative(process.cwd(), f)}`)); } + if (schemas.length === 0) { + log.warn( + "It declares no schemas, so it applies to the whole database and every later migration " + + "waits for it. Pass --schemas, or add a `-- schemas , ` line at the top of " + + "the up file.", + ); + } } /** @@ -83,14 +108,20 @@ export function createMigration(datatable: string, name: string): void { export async function runMigrations( workspace: string, datatableName: string, + schema?: string, ): Promise { const result = await wmill.runDatatableMigrations({ workspace, datatableName, + schema, }); const applied = result.applied ?? []; if (applied.length === 0) { - log.info(colors.gray(`No pending migrations to run on '${datatableName}'`)); + log.info( + colors.gray( + `No pending migrations to run on '${datatableName}'${schema ? ` for schema '${schema}'` : ""}`, + ), + ); return; } log.info( diff --git a/cli/src/commands/dev/dev.ts b/cli/src/commands/dev/dev.ts index 00a6f72f0e..562c38233e 100644 --- a/cli/src/commands/dev/dev.ts +++ b/cli/src/commands/dev/dev.ts @@ -30,8 +30,8 @@ import type { ScriptModule } from "../../../gen/types.gen.ts"; import { DBT_DESCRIPTOR_NAME, DBT_MODULE_SUFFIX, + getModuleFolderSuffix, getScriptBasePathFromModulePath, - isDbtModulePath, } from "../../utils/resource_folders.ts"; import { inferContentTypeFromFilePath } from "../../utils/script_common.ts"; import { OpenFlow } from "../../../gen/types.gen.ts"; @@ -148,6 +148,19 @@ export async function listWorkspacePaths(): Promise { items.push({ path: stripFolderSuffix(childRel, APP_SUFFIXES), kind: "raw_app" }); continue; } + // A script's own bundle, whose files are its modules rather than + // scripts. In folder layout the script itself is its `script.*`. + if (entry.name.endsWith(getModuleFolderSuffix())) { + const files = await readdir(childAbs).catch(() => [] as string[]); + if (files.some((f) => f.startsWith("script.") && hasScriptExt(f))) { + items.push({ + path: childRel.slice(0, -getModuleFolderSuffix().length), + kind: "script", + _metaPath: path.join(childAbs, "script.yaml"), + }); + } + continue; + } // A dbt script IS the project directory: its descriptor is optional, so // there may be no file here to recognize it by. Not descended into // either — the project's own `.sql` models would otherwise each be @@ -307,30 +320,25 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) { const flowMetadataFile = getMetadataFileName("flow", "yaml"); async function loadPaths(pathsToLoad: string[]) { - // A change ANYWHERE inside a dbt project is a change to that script: the - // bundle is the project, so the whole thing is re-read and rebroadcast. - // Treating the file as a script of its own would drop the edit — a bare - // `.sql` has no language to infer, and a `.yml` or `.csv` is filtered out - // below — leaving the browser previewing the snapshot taken at startup. + // Module edits belong to the parent script's bundle, even when the file + // has no standalone script extension, as with dbt's `.yml` and `.csv`. const rest: string[] = []; - const dbtProjects = new Set(); + const scriptsWithModules = new Set(); for (const raw of pathsToLoad) { const rel = (await realpath(raw).catch(() => raw)) .replace(base + SEP, "") .replaceAll("\\", "/"); - const wmPath = isDbtModulePath(rel) - ? getScriptBasePathFromModulePath(rel) - : undefined; + const wmPath = getScriptBasePathFromModulePath(rel); // Every project in the batch, and each only once: a save-all or a // `git checkout` touches many files at once, and returning on the first // would drop both the other projects and whatever else changed with them. - if (wmPath) dbtProjects.add(wmPath); + if (wmPath) scriptsWithModules.add(wmPath); else rest.push(raw); } - for (const wmPath of dbtProjects) { + for (const wmPath of scriptsWithModules) { const edit = await loadWmPath(wmPath); if (edit) { - log.info("Updated " + wmPath + " (dbt project)"); + log.info("Updated " + wmPath + " (script modules)"); broadcastChanges(edit); } } @@ -399,8 +407,7 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) { log.info("Updated " + wmFlowPath); broadcastChanges(currentLastEdit); } else if (typ == "script") { - const splitted = cpath.split("."); - const wmPath = splitted[0]; + const wmPath = removeExtensionToPath(cpath); const content = await readTextFile(cpath); const lang = inferContentTypeFromFilePath(cpath, opts.defaultTs); const typed = @@ -419,6 +426,9 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) { tag: typed?.tag, lock: typed?.lock, temp_script_refs: tempScriptRefs, + modules: await readModulesFromDisk( + wmPath + getModuleFolderSuffix(lang), opts.defaultTs, lang === "dbt", lang === "dbt" + ), }; log.info("Updated " + wmPath); broadcastChanges(currentLastEdit); @@ -433,9 +443,7 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) { tag?: string; lock?: string; temp_script_refs?: Record; - /** The bundle the dev page forwards to a preview run. A dbt project cannot - * run without it: the worker looks for `dbt_project.yml` in the bundle and - * refuses the job when it is not there. */ + /** Module bundle forwarded by the dev page to preview runs. */ modules?: Record; }; @@ -494,9 +502,14 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) { // Not a flow, try as script } - // Try as script - for (const ext of exts) { - const filePath = wmPath + ext; + // Try as script: flat `.`, then folder layout `__mod/script.` + const candidates = [ + ...exts.map((ext) => ({ ext, filePath: wmPath + ext, folderLayout: false })), + ...exts + .filter((ext) => !ext.includes("/")) + .map((ext) => ({ ext, filePath: wmPath + getModuleFolderSuffix() + "/script" + ext, folderLayout: true })), + ]; + for (const { ext, filePath, folderLayout } of candidates) { try { // A dbt project's descriptor is optional, so what says "this is a dbt // script" is the project beside it. Requiring the descriptor to exist @@ -516,7 +529,7 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) { } const content = isAbsentDbtDescriptor ? "" : await readTextFile(filePath); const lang = inferContentTypeFromFilePath(filePath, opts.defaultTs); - const typed = (await parseMetadataFile(removeExtensionToPath(filePath), undefined))?.payload; + const typed = (await parseMetadataFile(wmPath, undefined))?.payload; const edit: LastEditScript = { type: "script", content, @@ -528,15 +541,12 @@ export async function dev(opts: GlobalOptions & SyncOptions & DevOpts) { // Read VERBATIM for dbt, the way push does: the project's `.sql` and // `.yml` files are dbt's, and inferring a language for each would // drop the ones that are not Windmill scripts. - modules: + modules: await readModulesFromDisk( + wmPath + getModuleFolderSuffix(lang), + opts.defaultTs, + folderLayout || lang === "dbt", lang === "dbt" - ? await readModulesFromDisk( - wmPath + DBT_MODULE_SUFFIX, - opts.defaultTs, - true, - true - ) - : undefined, + ), }; currentLastEdit = edit; return edit; diff --git a/cli/src/commands/flow/flow.ts b/cli/src/commands/flow/flow.ts index a266834f41..98339865be 100644 --- a/cli/src/commands/flow/flow.ts +++ b/cli/src/commands/flow/flow.ts @@ -19,7 +19,7 @@ import { toSyncRootRelativePath, validatePath, } from "../../core/context.ts"; -import { resolve, track_job, pollForJobResult } from "../script/script.ts"; +import { resolve, track_job, pollForJobResult, ensurePreviewOnBehalfOfSupported } from "../script/script.ts"; import { defaultFlowDefinition } from "../../../bootstrap/flow_bootstrap.ts"; import { SyncOptions, @@ -639,6 +639,7 @@ async function preview( remote?: boolean; step?: string; tag?: string; + onBehalfOf?: string; } & SyncOptions, flowPath: string ) { @@ -653,6 +654,7 @@ async function preview( } const workspace = await resolveWorkspace(opts); await requireLogin(opts); + await ensurePreviewOnBehalfOfSupported(workspace.workspaceId, opts.onBehalfOf); const codebases = useLocalPathScripts ? listSyncCodebases(opts) : []; const argPath = flowPath; @@ -758,7 +760,7 @@ async function preview( // when `useLocalPathScripts` is set, and tempScriptRefs covers relative // imports in inline scripts. if (opts.step) { - await previewStep(opts.step, localFlow, flowWmPath, workspace, input, tempScriptRefs, opts.silent, opts.tag); + await previewStep(opts.step, localFlow, flowWmPath, workspace, input, tempScriptRefs, opts.silent, opts.tag, opts.onBehalfOf); return; } @@ -775,6 +777,7 @@ async function preview( args: input, tag: opts.tag, temp_script_refs: tempScriptRefs, + on_behalf_of: opts.onBehalfOf, }, }); @@ -808,6 +811,7 @@ async function previewStep( tempScriptRefs: Record | undefined, silent: boolean, tag: string | undefined, + onBehalfOf: string | undefined, ) { const module = findStepInFlowValue(localFlow.value, stepId); if (!module) { @@ -841,6 +845,7 @@ async function previewStep( args, tag, temp_script_refs: tempScriptRefs, + on_behalf_of: onBehalfOf, }, }); } else if (moduleValue?.type === "script") { @@ -868,9 +873,15 @@ async function previewStep( args, tag, temp_script_refs: tempScriptRefs, + on_behalf_of: onBehalfOf, }, }); } else if (moduleValue?.type === "flow") { + if (onBehalfOf) { + throw new Error( + `--on-behalf-of does not apply to step '${stepId}': a flow step runs the deployed flow ${moduleValue.path} by path, and this flag cannot override its identity.` + ); + } log.info(colors.yellow(`Previewing step '${stepId}' (flow ${moduleValue.path})...`)); jobId = await wmill.runFlowByPath({ workspace: workspace.workspaceId, @@ -1216,6 +1227,10 @@ const command = new Command() "--tag ", "Override the worker tag the preview is dispatched to (e.g. to route it to dev workers instead of the flow's default tag)." ) + .option( + "--on-behalf-of ", + "Run the preview as this user or group (an email, u/ or g/) instead of yourself, e.g. to reproduce a run_on_behalf_of identity. Requires being an admin or a member of wm_deployers." + ) .action(preview as any) .command( "generate-locks", diff --git a/cli/src/commands/init/template.ts b/cli/src/commands/init/template.ts index 8a433d69d4..1f78c13148 100644 --- a/cli/src/commands/init/template.ts +++ b/cli/src/commands/init/template.ts @@ -77,8 +77,8 @@ const WORKSPACE_CONFIG_SCHEMA = { */ export const CONFIG_REFERENCE: ConfigOption[] = [ // ── Core ────────────────────────────────────────────────────────────── - { name: "defaultTs", type: "string", enum: ["bun", "deno"], default: "bun", description: "Default TypeScript runtime for new scripts", - inlineComment: "bun or deno" }, + { name: "defaultTs", type: "string", enum: ["bun", "deno"], default: "bun", description: "TypeScript runtime of a plain .ts script (bun when absent)", + skipInTemplate: true }, { name: "includes", type: "array", items: { type: "string" }, default: '["f/**"]', description: "Glob patterns for files to include in sync", templateValue: '\n - "f/**"', inlineComment: 'use ** for all, f/** for folder-scoped' }, { name: "extraIncludes", type: "array", items: { type: "string" }, default: "[]", description: "Additional glob patterns merged with includes (useful in workspace overrides)", @@ -109,6 +109,9 @@ export const CONFIG_REFERENCE: ConfigOption[] = [ commented: true, templateValue: "true" }, { name: "includeSettings", type: "boolean", default: "false", description: "Include workspace settings in sync", commented: true, templateValue: "true" }, + { name: "includeDatatablePermissions", type: "boolean", default: "false", + description: "With includeSettings, also sync each data table's roles and who may connect as them", + commented: true, templateValue: "true" }, { name: "includeKey", type: "boolean", default: "false", description: "Include encryption key in sync", commented: true, templateValue: "true" }, diff --git a/cli/src/commands/resource-type/resource-type.ts b/cli/src/commands/resource-type/resource-type.ts index 505200f07a..e8e03757e5 100644 --- a/cli/src/commands/resource-type/resource-type.ts +++ b/cli/src/commands/resource-type/resource-type.ts @@ -91,6 +91,19 @@ async function push(opts: PushOptions, filePath: string, name: string) { log.info(colors.bold.underline.green("Resource pushed")); } +// The hub publishes hundreds of resource types and an instance seeds only a few of its own, +// so fewer than this means the instance never synced with the hub. +const UNSYNCED_RESOURCE_TYPE_COUNT = 20; + +function warnIfNotSyncedWithHub(resourceTypes: ResourceType[]) { + const count = new Set(resourceTypes.map((rt) => rt.name)).size; + if (count < UNSYNCED_RESOURCE_TYPE_COUNT) { + log.warnAlways( + `Only ${count} resource types exist on this instance, so it has most likely never synced with the Windmill Hub, which has types for most services. A superadmin can sync resource types from the hub with "Sync resource types with Hub" in the Add resource dialog of the Resources page.` + ); + } +} + async function list(opts: GlobalOptions & { schema?: boolean; json?: boolean }) { if (opts.json) log.setSilent(true); const workspace = await resolveWorkspace(opts); @@ -99,12 +112,9 @@ async function list(opts: GlobalOptions & { schema?: boolean; json?: boolean }) workspace: workspace.workspaceId, }); + warnIfNotSyncedWithHub(res); if (opts.json) { console.log(JSON.stringify(res)); - } else if (res.length === 0) { - log.info("No custom resource types found in this workspace."); - log.info("Built-in types like 'postgresql', 'slack', 'mysql', etc. are available from the Windmill Hub."); - return; } else if (opts.schema) { new Table() .header(["Workspace", "Name", "Schema"]) @@ -172,6 +182,7 @@ export async function generateRTNamespace(opts: GlobalOptions) { const rts = await wmill.listResourceType({ workspace: workspace.workspaceId, }); + warnIfNotSyncedWithHub(rts); let namespaceContent = "declare namespace RT {\n"; namespaceContent += rts diff --git a/cli/src/commands/resource/resource.ts b/cli/src/commands/resource/resource.ts index 7cef4caf1f..87c31b331a 100644 --- a/cli/src/commands/resource/resource.ts +++ b/cli/src/commands/resource/resource.ts @@ -20,6 +20,11 @@ import { Resource } from "../../../gen/types.gen.ts"; import { readInlinePathSync, readTextFile } from "../../utils/utils.ts"; import { isWorkspaceSpecificFile } from "../../core/specific_items.ts"; import { getCurrentGitBranch } from "../../utils/git.ts"; +import { + buildPermissionedAsContext, + type PermissionedAsContext, +} from "../../core/permissioned_as.ts"; +import { readEffectiveSyncBehavior } from "../../core/conf.ts"; export interface ResourceFile { value: any; @@ -83,6 +88,7 @@ export async function pushResource( // only round-trip the canonical layout); the standalone `resource push` // command pushes a single explicit file, where any pointer is fine. enforceCanonicalFileset?: boolean, + permissionedAsContext?: PermissionedAsContext, ): Promise { remotePath = removeType(remotePath, "resource"); try { @@ -93,6 +99,11 @@ export async function pushResource( } catch { // flow doesn't exist } + const claimed = agentOnBehalfOf( + resource, + localResource, + permissionedAsContext + ); // Helper function to resolve inline content const resolveInlineContent = async () => { @@ -133,11 +144,23 @@ export async function pushResource( // Only resolve inline content if we're actually updating await resolveInlineContent(); + if (claimed) { + log.info(`Preserving ${claimed} as permissioned_as for agent ${remotePath}`); + } await wmill.updateResource({ workspace: workspace, path: remotePath.replaceAll(SEP, "/"), - requestBody: { ...localResource, ...(wsSpecific !== undefined ? { ws_specific: wsSpecific } : {}) }, + requestBody: { + ...localResource, + ...(wsSpecific !== undefined ? { ws_specific: wsSpecific } : {}), + ...(claimed + ? { + value: { ...localResource.value, on_behalf_of: claimed }, + preserve_on_behalf_of: true, + } + : {}), + }, }); } else { // New resource - resolve inline content @@ -163,6 +186,42 @@ export async function pushResource( } } +/** + * An agent with `run_on_behalf_of` runs as the identity in its value's + * `on_behalf_of`, which the backend sets to whoever writes the agent and clears + * while the toggle is off. Like an app's, it is never taken from the + * tracked file, which the pull leaves it out of: the deployed one is claimed + * back only by a pusher the backend lets keep it, an admin or a `wm_deployers` + * member. Strips the key from `localResource` (and from the deployed value, so + * an unchanged agent still compares equal) and returns the identity to claim. + */ +export function agentOnBehalfOf( + deployed: ResourceFile | Resource | undefined, + localResource: ResourceFile, + permissionedAsContext: PermissionedAsContext | undefined +): string | undefined { + // What the push writes is the tracked file's type: an agent retyped into + // another resource keeps its value exactly as the file states it. + if (localResource.resource_type !== "ai_agent") { + return undefined; + } + const local = localResource.value; + if (local && typeof local === "object") { + delete local.on_behalf_of; + } + const value = deployed?.resource_type === "ai_agent" ? deployed.value : undefined; + const onBehalfOf = + value && typeof value === "object" ? value.on_behalf_of : undefined; + if (deployed && onBehalfOf !== undefined) { + const { on_behalf_of: _, ...rest } = value; + deployed.value = rest; + } + if (!onBehalfOf || !permissionedAsContext?.userIsAdminOrDeployer) { + return undefined; + } + return onBehalfOf; +} + type PushOptions = GlobalOptions; async function push(opts: PushOptions, filePath: string, remotePath: string) { const workspace = await resolveWorkspace(opts); @@ -184,7 +243,13 @@ async function push(opts: PushOptions, filePath: string, remotePath: string) { remotePath, undefined, parseFromFile(filePath), - filePath // Pass the local file path for branch-specific inline content resolution + filePath, // Pass the local file path for branch-specific inline content resolution + undefined, + undefined, + await buildPermissionedAsContext( + workspace.workspaceId, + await readEffectiveSyncBehavior(opts, workspace) + ) ); log.info(colors.bold.underline.green(`Resource ${remotePath} pushed`)); } diff --git a/cli/src/commands/script/script.ts b/cli/src/commands/script/script.ts index 4938b6aeb3..f38a73d697 100644 --- a/cli/src/commands/script/script.ts +++ b/cli/src/commands/script/script.ts @@ -19,7 +19,7 @@ import * as log from "../../core/log.ts"; import { sep as SEP } from "node:path"; import * as path from "node:path"; import { stringify as yamlStringify } from "yaml"; -import { deepEqual, getHeaders, isFileResource, isFilesetResource, readTextFile, readTextFileSync } from "../../utils/utils.ts"; +import { deepEqual, getHeaders, isFileResource, isFilesetResource, readTextFile, readTextFileSync, sleep } from "../../utils/utils.ts"; import { detectAuthGatewayChallenge } from "../../utils/http_guards.ts"; import * as wmill from "../../../gen/services.gen.ts"; import * as specificItems from "../../core/specific_items.ts"; @@ -1492,45 +1492,49 @@ async function run( await track_job(workspace.workspaceId, id); } - const MAX_RETRIES = 600; // ~60 seconds at 100ms intervals - let retries = 0; - while (retries < MAX_RETRIES) { - try { - const completedJob = await wmill.getCompletedJob({ - workspace: workspace.workspaceId, - id, - }); - - if (completedJob.success === false) { - process.exitCode = 1; - } - - const result = completedJob.result ?? {}; - if (opts.silent) { - console.log(JSON.stringify(result)); - } else { - log.info(JSON.stringify(result, null, 2)); - } - - break; - } catch { - retries++; - await new Promise((resolve) => setTimeout(resolve, 100)); - } + let { result, success } = await pollForJobResult(workspace.workspaceId, id); + // Prefer getCompletedJob: unlike the poller, it counts a skipped + // (debounced) job as a success. + try { + const completedJob = await wmill.getCompletedJob({ + workspace: workspace.workspaceId, + id, + }); + result = completedJob.result; + success = completedJob.success !== false; + } catch { + /* keep the poller's result */ } - if (retries >= MAX_RETRIES) { - throw new Error(`Timed out waiting for job ${id} to complete`); + if (!success) { + process.exitCode = 1; + } + result = result ?? {}; + if (opts.silent) { + console.log(JSON.stringify(result)); + } else { + log.info(JSON.stringify(result, null, 2)); } } +function logJobCompleted(success: boolean | undefined) { + log.info("\n"); + log.info( + success === false + ? colors.bold.underline.red("Job Completed") + : colors.bold.underline.green("Job Completed") + ); + log.info("\n"); +} + +const JOB_UPDATES_POLL_INTERVAL_MS = 500; +const MAX_CONSECUTIVE_JOB_UPDATE_ERRORS = 5; + export async function track_job(workspace: string, id: string) { try { const result = await wmill.getCompletedJob({ workspace, id }); log.info(result.logs); - log.info("\n"); - log.info(colors.bold.underline.green("Job Completed")); - log.info("\n"); + logJobCompleted(result.success); return; } catch { /* ignore */ @@ -1538,15 +1542,13 @@ export async function track_job(workspace: string, id: string) { log.info(colors.yellow("Waiting for Job " + id + " to start...")); + // Server-side character position (1-based, as returned in `log_offset`), not + // a JS string length: UTF-16 lengths drift from it on non-BMP characters. let logOffset = 0; let running = false; - let retry = 0; + let errors = 0; while (true) { - let updates: { - running?: boolean | undefined; - completed?: boolean | undefined; - new_logs?: string | undefined; - }; + let updates: Awaited>; try { updates = await wmill.getJobUpdates({ workspace, @@ -1554,13 +1556,16 @@ export async function track_job(workspace: string, id: string) { logOffset, running, }); - } catch { - retry++; - if (retry > 3) { - log.info("failed to get job updated. skipping log streaming."); + errors = 0; + } catch (e: any) { + errors++; + if (errors >= MAX_CONSECUTIVE_JOB_UPDATE_ERRORS) { + log.warn( + `Failed to get job updates (${e?.message ?? e}), log streaming stopped. Waiting for the job to complete...` + ); break; } - await new Promise((resolve) => setTimeout(resolve, 500)); + await sleep(JOB_UPDATES_POLL_INTERVAL_MS); continue; } @@ -1571,11 +1576,10 @@ export async function track_job(workspace: string, id: string) { if (updates.new_logs) { process.stdout.write(updates.new_logs); - logOffset += updates.new_logs.length; } + logOffset = updates.log_offset ?? logOffset; if (updates.completed === true) { - running = false; break; } @@ -1583,24 +1587,25 @@ export async function track_job(workspace: string, id: string) { running = false; log.info(colors.yellow("Job suspended. Waiting for it to continue...")); } + await sleep(JOB_UPDATES_POLL_INTERVAL_MS); } - await new Promise((resolve, _) => setTimeout(() => resolve(undefined), 1000)); + await pollForJobResult(workspace, id); + + let success: boolean | undefined; try { const final_job = await wmill.getCompletedJob({ workspace, id }); - if ((final_job.logs?.length ?? -1) > logOffset) { - log.info(final_job.logs!.substring(logOffset)); + success = final_job.success; + const remaining = Array.from(final_job.logs ?? "") + .slice(Math.max(logOffset - 1, 0)) + .join(""); + if (remaining) { + log.info(remaining); } - log.info("\n"); - if (final_job.success) { - log.info(colors.bold.underline.green("Job Completed")); - } else { - log.info(colors.bold.underline.red("Job Completed")); - } - log.info("\n"); - } catch { - log.info("Job appears to have completed, but no data can be retrieved"); + } catch (e: any) { + log.warn(`Could not retrieve the job's remaining logs: ${e?.message ?? e}`); } + logJobCompleted(success); } export async function pollForJobResult( @@ -1610,6 +1615,32 @@ export async function pollForJobResult( return await pollJobWithQueueLogging(workspace, jobId); } +/** + * A server that predates preview `on_behalf_of` drops the field and runs the preview as the + * caller, which would pass for a reproduction of the other identity's run. Probe it with an + * `identity` preview, which runs no code, before submitting any. + */ +export async function ensurePreviewOnBehalfOfSupported( + workspace: string, + onBehalfOf: string | undefined, +) { + if (!onBehalfOf) return; + const probeId = await wmill.runScriptPreview({ + workspace, + requestBody: { kind: "identity", args: {}, on_behalf_of: onBehalfOf }, + }); + const job = await wmill.getJob({ workspace, id: probeId }); + if ( + job.permissioned_as === onBehalfOf || + job.email?.toLowerCase() === onBehalfOf.toLowerCase() + ) { + return; + } + throw new Error( + `The server does not support --on-behalf-of: it would run the preview as ${job.permissioned_as}, not ${onBehalfOf}. Upgrade the Windmill instance.` + ); +} + async function show(opts: GlobalOptions, path: string) { const workspace = await resolveWorkspace(opts); await requireLogin(opts); @@ -1873,6 +1904,7 @@ async function preview( data?: string; silent: boolean; tag?: string; + onBehalfOf?: string; } & SyncOptions, filePath: string ) { @@ -1884,6 +1916,7 @@ async function preview( opts = await mergeConfigWithConfigFile(opts); const workspace = await resolveWorkspace(opts); await requireLogin(opts); + await ensurePreviewOnBehalfOfSupported(workspace.workspaceId, opts.onBehalfOf); const argPath = filePath; filePath = toSyncRootRelativePath(filePath, cwdBeforeConfig); @@ -2053,6 +2086,7 @@ async function preview( kind: isTar ? "tarbundle" : "bundle", format: codebase?.format ?? "cjs", temp_script_refs: tempScriptRefs, + on_behalf_of: opts.onBehalfOf, }; form.append("preview", JSON.stringify(previewPayload)); form.append( @@ -2122,6 +2156,7 @@ async function preview( tag: opts.tag, modules: modules ?? undefined, temp_script_refs: tempScriptRefs, + on_behalf_of: opts.onBehalfOf, }, }); @@ -2272,6 +2307,10 @@ const command = new Command() "--tag ", "Override the worker tag the preview is dispatched to (e.g. to route it to dev workers instead of the script's default tag)." ) + .option( + "--on-behalf-of ", + "Run the preview as this user or group (an email, u/ or g/) instead of yourself, e.g. to reproduce a run_on_behalf_of identity. Requires being an admin or a member of wm_deployers." + ) .action(preview as any) .command("new", "create a new script") .arguments(" ") diff --git a/cli/src/commands/sync/pull.ts b/cli/src/commands/sync/pull.ts index d75dc81912..51709b7d73 100644 --- a/cli/src/commands/sync/pull.ts +++ b/cli/src/commands/sync/pull.ts @@ -86,7 +86,8 @@ export async function downloadZip( skipWorkspaceDependencies?: boolean, skipDatatableMigrations?: boolean, defaultTs?: "bun" | "deno", - syncBehavior?: string + syncBehavior?: string, + includeDatatablePermissions?: boolean, ): Promise { const requestHeaders = new Headers(); requestHeaders.set("Authorization", "Bearer " + workspace.token); @@ -112,6 +113,7 @@ export async function downloadZip( }&skip_secrets=${skipSecrets ?? false}&include_schedules=${includeSchedules ?? false }&include_triggers=${includeTriggers ?? false}&include_users=${includeUsers ?? false }&include_groups=${includeGroups ?? false}&include_settings=${includeSettings ?? false + }&include_datatable_permissions=${includeDatatablePermissions ?? false }&include_key=${includeKey ?? false}&include_workspace_dependencies=${includeWorkspaceDependenciesValue}&skip_datatable_migrations=${skipDatatableMigrations ?? false}&default_ts=${defaultTs ?? "bun"}&skip_resource_types=${skipResourceTypes ?? false}&settings_version=v2&preserve_extra_perms=true&sync_behavior_version=${syncBehavior ?? "v0"}`; const baseUrl = workspace.remote + "api/w/" + workspace.workspaceId + "/workspaces/tarball?"; diff --git a/cli/src/commands/sync/sync.ts b/cli/src/commands/sync/sync.ts index 54887028f0..43bba850ed 100644 --- a/cli/src/commands/sync/sync.ts +++ b/cli/src/commands/sync/sync.ts @@ -14,6 +14,7 @@ import { colors } from "@cliffy/ansi/colors"; import { Command } from "@cliffy/command"; import { Confirm } from "@cliffy/prompt/confirm"; import * as log from "../../core/log.ts"; +import { SETTINGS_MANAGED_ONLY_WHEN_PRESENT } from "../../core/settings.ts"; import * as path from "node:path"; import { sep as SEP } from "node:path"; import { @@ -100,6 +101,7 @@ import { isCurrentWorkspaceFile, isItemTypeConfigured, isSpecificItem, + isCustomPathFile, SpecificItemsConfig, } from "../../core/specific_items.ts"; import { @@ -149,7 +151,11 @@ import { extractCurrentMapping, } from "../../../windmill-utils-internal/src/inline-scripts/extractor.ts"; import { generateFlowLockInternal } from "../flow/flow_metadata.ts"; -import { markAccessFromPolicy } from "../app/app.ts"; +import { + markAccessFromPolicy, + markIsolationFromPolicy, + stripEditorState, +} from "../app/app.ts"; import { APP_BACKEND_FOLDER, generateAppLocksInternal, @@ -1062,7 +1068,7 @@ async function pushFilesetParentResource( if (cachedWsName && isWorkspaceSpecificFile(resourceFilePath)) { serverPath = fromWorkspaceSpecificPath(resourceFilePath, cachedWsName); wsSpecific = true; - } else if (specificItems && isSpecificItem(childPath, specificItems)) { + } else if (isSpecificItem(childPath, specificItems)) { wsSpecific = true; } @@ -1329,6 +1335,7 @@ export function ZipFSElement( log.error(`Failed to parse app.yaml at path: ${p}`); throw error; } + stripEditorState(app); let inlineScripts; try { inlineScripts = extractInlineScriptsForApps( @@ -1359,7 +1366,10 @@ export function ZipFSElement( } markAccessFromPolicy(app); + markIsolationFromPolicy(app, false); app.policy = undefined; + // Rendered as its own workspace-specific file (see below). + delete app.custom_path; yield { isDirectory: false, path: path.join(finalPath, "app.yaml"), @@ -1377,10 +1387,10 @@ export function ZipFSElement( throw error; } markAccessFromPolicy(rawApp); + markIsolationFromPolicy(rawApp, true); // console.log("rawApp", rawApp); rawApp.policy = undefined; - // custom_path is derived from the file path, don't store it - delete rawApp?.["custom_path"]; + delete rawApp.custom_path; let inlineScripts; const value = rawApp?.["value"]; const runnables = value?.["runnables"] ?? {}; @@ -1837,6 +1847,24 @@ export function ZipFSElement( } } } + if (kind == "app" || kind == "raw_app") { + // Always workspace-specific: see isCustomPathFile. + const customPath = JSON.parse(await f.async("text"))?.custom_path; + if (customPath) { + const appPath = removeSuffix(p, kind == "app" ? ".app.json" : ".raw_app.json"); + const obj = { custom_path: customPath }; + r.push({ + isDirectory: false, + path: appPath + (useYaml ? ".custom_path.yaml" : ".custom_path.json"), + async *getChildren() {}, + async getContentText() { + return useYaml + ? yamlStringify(obj, yamlOptions) + : JSON.stringify(obj, null, 2); + }, + }); + } + } return r; } function _internal_folder(p: string, zip: JSZip): DynFSElement { @@ -2099,7 +2127,11 @@ export async function elementsToMap( continue; } if (skips.skipFlows && fileType === "flow") continue; - if (skips.skipApps && fileType === "app") continue; + if ( + skips.skipApps && + (fileType === "app" || fileType === "custom_path") + ) + continue; if (skips.skipFolders && fileType === "folder") continue; if ( skips.skipWorkspaceDependencies && @@ -2569,6 +2601,14 @@ const isWorkspaceSettingsFile = (p: string) => function stripUnappliedSettingsFields(local: any, remote: any) { delete local?.name; delete remote?.name; + for (const key of ["operator_settings", ...SETTINGS_MANAGED_ONLY_WHEN_PRESENT]) { + if (local?.[key] === undefined) delete remote?.[key]; + } + // push clears an omitted mute_critical_alerts to false + if (local?.mute_critical_alerts == null && remote?.mute_critical_alerts === false) { + delete local?.mute_critical_alerts; + delete remote.mute_critical_alerts; + } if (local?.color == null) { delete local?.color; delete remote?.color; @@ -2589,6 +2629,53 @@ function stripUnappliedSettingsFields(local: any, remote: any) { } } +/** + * A checkout made before custom paths had their own file still carries one in + * its app file, and a push deploys it. It compares as the workspace's + * custom-path file it stands for, unless that file exists, so such a checkout + * neither lists its app file as edited nor drops the custom path. + */ +function liftInFileCustomPaths( + localMap: Record, + json: boolean, +): void { + for (const key of Object.keys(localMap)) { + const normalized = key.replaceAll(SEP, "/"); + const type = isRawAppFolderMetadataFile(normalized) + ? "raw_app" + : isAppFolderMetadataFile(normalized) + ? "app" + : undefined; + if (!type || normalized.endsWith(json ? ".yaml" : ".json")) continue; + const appPath = extractResourceName(normalized, type); + let obj: any; + try { + obj = json + ? JSON.parse(localMap[key]) + : yamlParseContent(key, localMap[key]); + } catch { + continue; + } + if (!appPath || !obj || typeof obj != "object" || !("custom_path" in obj)) { + continue; + } + const customPath = obj.custom_path; + delete obj.custom_path; + localMap[key] = json + ? JSON.stringify(obj, null, 2) + : yamlStringify(obj, yamlOptions); + const fileKey = + appPath.replaceAll("/", SEP) + + (json ? ".custom_path.json" : ".custom_path.yaml"); + if (customPath && !(fileKey in localMap)) { + const file = { custom_path: customPath }; + localMap[fileKey] = json + ? JSON.stringify(file, null, 2) + : yamlStringify(file, yamlOptions); + } + } +} + export async function compareDynFSElement( els1: DynFSElement, els2: DynFSElement | undefined, @@ -2716,6 +2803,22 @@ export async function compareDynFSElement( ); } + if (isEls1Remote === false) { + liftInFileCustomPaths(m1, json); + // `custom_path: ''` clears the deployed one, after which the export has + // no file to match it: an empty value with nothing deployed is in sync. + for (const [k, v] of Object.entries(m1)) { + if (!isCustomPathFile(k) || k in m2) continue; + let value: unknown; + try { + value = (json ? JSON.parse(v) : yamlParseContent(k, v))?.custom_path; + } catch { + continue; + } + if (!value) delete m1[k]; + } + } + const changes: Change[] = []; function parseYaml(k: string, v: string) { @@ -2747,12 +2850,18 @@ export async function compareDynFSElement( } return o; } else { + let o: any; try { - return yamlParseContent(k, v); + o = yamlParseContent(k, v); } catch (error) { log.error(`Failed to parse YAML content at path: ${k}`); throw error; } + // A file tracked before the field was dropped still carries it. + if (path.basename(k) == "app.yaml") { + stripEditorState(o); + } + return o; } } @@ -2859,6 +2968,11 @@ export async function compareDynFSElement( const remoteCodebase: Record = {}; for (const [k] of Object.entries(m2)) { if (m1[k] === undefined) { + // A workspace without its own custom-path file leaves the deployed one + // alone: a promotion never carries the target's custom path. + if (isEls1Remote === false && isCustomPathFile(k)) { + continue; + } if ( !ignoreMetadataDeletion || (!k?.endsWith(".script.yaml") && !k?.endsWith(".script.json")) @@ -2962,8 +3076,10 @@ function getOrderFromPath(p: string) { return 11; } else if (typ == "app") { return 12; - } else if (typ == "schedule") { + } else if (typ == "custom_path") { return 13; + } else if (typ == "schedule") { + return 14; } else if ( typ == "http_trigger" || typ == "websocket_trigger" || @@ -2978,9 +3094,9 @@ function getOrderFromPath(p: string) { typ == "email_trigger" || typ == "native_trigger" ) { - return 14; - } else { return 15; + } else { + return 16; } } @@ -3830,6 +3946,7 @@ export async function pull( opts.skipDatatableMigrations, opts.defaultTs, opts.syncBehavior, + opts.includeDatatablePermissions, ); const remote = ZipFSElement( @@ -3900,7 +4017,7 @@ export async function pull( ...(change.name === "edited" && change.codebase ? { codebase_changed: true } : {}), - ...(specificItems && isSpecificItem(change.path, specificItems) + ...(isSpecificItem(change.path, specificItems) ? { workspace_specific: true, workspace_specific_path: getWorkspaceSpecificPath( @@ -3949,7 +4066,7 @@ export async function pull( const change: Change = rawChange; // Determine if this file should be written to a workspace-specific path let targetPath = change.path; - if (specificItems && isSpecificItem(change.path, specificItems)) { + if (isSpecificItem(change.path, specificItems)) { const workspaceSpecificPath = getWorkspaceSpecificPath( change.path, specificItems, @@ -4210,7 +4327,7 @@ export async function pull( ...(change.name === "edited" && change.codebase ? { codebase_changed: true } : {}), - ...(specificItems && isSpecificItem(change.path, specificItems) + ...(isSpecificItem(change.path, specificItems) ? { workspace_specific: true, workspace_specific_path: getWorkspaceSpecificPath( @@ -4490,7 +4607,7 @@ function prettyChanges( let wsNote = ""; // Check if this will be written as a workspace-specific file - if (specificItems && isSpecificItem(change.path, specificItems)) { + if (isSpecificItem(change.path, specificItems)) { const workspaceSpecificPath = getWorkspaceSpecificPath( change.path, specificItems, @@ -4933,6 +5050,7 @@ export async function push( opts.skipDatatableMigrations, opts.defaultTs, opts.syncBehavior, + opts.includeDatatablePermissions, ))!, !opts.json, opts.defaultTs ?? "bun", @@ -5561,7 +5679,7 @@ export async function push( ...(change.name === "edited" && change.codebase ? { codebase_changed: true } : {}), - ...(specificItems && isSpecificItem(change.path, specificItems) + ...(isSpecificItem(change.path, specificItems) ? { workspace_specific: true, workspace_specific_path: getWorkspaceSpecificPath( @@ -5731,8 +5849,12 @@ export async function push( // `alreadySynced`, and a push touching several files of one bundle then // deploys the script once per file: several versions in a row, of which // only the last is the one the asset graph ends up describing. + // An app's files and its custom-path file group under the app path in + // both folder layouts, so the custom path is applied after the app. const basePath = getScriptBasePathFromModulePath(change.path) ?? + extractResourceName(change.path, "raw_app")?.replaceAll("/", SEP) ?? + extractResourceName(change.path, "app")?.replaceAll("/", SEP) ?? change.path.split(".")[0]; if (!groupedChanges.has(basePath)) { groupedChanges.set(basePath, []); @@ -5822,10 +5944,14 @@ export async function push( changes = [deleteRawApp]; } else { // The app is one bundle, so a single change re-pushes all of it. - // That leaves the loop exactly one change: any skip it takes for - // a raw-app path drops the whole app from the push, and nothing - // downstream records that as a failure. - changes.splice(1, changes.length - 1); + // That leaves the loop exactly one raw-app change: any skip it + // takes for a raw-app path drops the whole app from the push, and + // nothing downstream records that as a failure. The custom path + // is not part of the bundle and is applied after it. + changes = [ + changes[0], + ...changes.slice(1).filter((c) => isCustomPathFile(c.path)), + ]; } } @@ -5939,6 +6065,7 @@ export async function push( resourceFilePath, isFileResWsSpecific ? true : undefined, true, + permissionedAsContext, ); } // Already-synced parents got the full content this run. @@ -6007,7 +6134,7 @@ export async function push( // Check if this is a branch-specific item and get the original workspace-specific path let originalWorkspaceSpecificPath: string | undefined; const isWsSpecific = - specificItems && isSpecificItem(change.path, specificItems); + isSpecificItem(change.path, specificItems); if (isWsSpecific) { originalWorkspaceSpecificPath = getWorkspaceSpecificPath( change.path, @@ -6036,6 +6163,7 @@ export async function push( (opts.yes ?? false) || !process.stdin.isTTY, skipReencrypt: opts.skipReencryptOnKeyChange, }, + includeDatatablePermissions: opts.includeDatatablePermissions, defaultTs: opts.defaultTs, }, ); @@ -6142,7 +6270,7 @@ export async function push( // For branch-specific items, we read from workspace-specific files but push to base server paths let localFilePath = change.path; const isAddedWsSpecific = - specificItems && isSpecificItem(change.path, specificItems); + isSpecificItem(change.path, specificItems); if (isAddedWsSpecific) { const workspaceSpecificPath = getWorkspaceSpecificPath( change.path, @@ -6174,6 +6302,7 @@ export async function push( (opts.yes ?? false) || !process.stdin.isTTY, skipReencrypt: opts.skipReencryptOnKeyChange, }, + includeDatatablePermissions: opts.includeDatatablePermissions, defaultTs: opts.defaultTs, }, ); @@ -6671,7 +6800,7 @@ export async function push( ...(change.name === "edited" && change.codebase ? { codebase_changed: true } : {}), - ...(specificItems && isSpecificItem(change.path, specificItems) + ...(isSpecificItem(change.path, specificItems) ? { workspace_specific: true, workspace_specific_path: getWorkspaceSpecificPath( @@ -6802,6 +6931,10 @@ const command = new Command() .option("--include-users", "Include syncing users") .option("--include-groups", "Include syncing groups") .option("--include-settings", "Include syncing workspace settings") + .option( + "--include-datatable-permissions", + "With --include-settings, also sync who may connect to each data table as which role", + ) .option("--include-key", "Include workspace encryption key") .option( "--keep-deleted", @@ -6865,6 +6998,10 @@ const command = new Command() .option("--include-users", "Include syncing users") .option("--include-groups", "Include syncing groups") .option("--include-settings", "Include syncing workspace settings") + .option( + "--include-datatable-permissions", + "With --include-settings, also sync who may connect to each data table as which role", + ) .option("--include-key", "Include workspace encryption key") .option( "--skip-reencrypt-on-key-change", diff --git a/cli/src/commands/variable/variable.ts b/cli/src/commands/variable/variable.ts index 8963f376d2..88ad108a1a 100644 --- a/cli/src/commands/variable/variable.ts +++ b/cli/src/commands/variable/variable.ts @@ -107,7 +107,8 @@ export interface VariableFile { * plaintext value a user authored by hand. * * Mirrors the server guard (windmill-store/src/variables.rs): workspace - * ciphertext (AES-256-CBC, base64) is standard base64 decoding to a non-zero + * ciphertext (AES-256-GCM or legacy AES-256-CBC, base64) is standard base64 + * decoding to a non-zero * multiple of the 16-byte block size. External secret-backend markers * ($vault:/$aws_sm:/$azure_kv:) are stored verbatim too, so they count as * already-encrypted. This is a shape check only — it never decrypts. diff --git a/cli/src/commands/workspace/settings.ts b/cli/src/commands/workspace/settings.ts new file mode 100644 index 0000000000..11aca145fa --- /dev/null +++ b/cli/src/commands/workspace/settings.ts @@ -0,0 +1,75 @@ +import { colors } from "@cliffy/ansi/colors"; +import { Confirm } from "@cliffy/prompt/confirm"; +import { stringify as yamlStringify } from "yaml"; +import { GlobalOptions } from "../../types.ts"; +import * as log from "../../core/log.ts"; +import { requireLogin } from "../../core/auth.ts"; +import { resolveWorkspace } from "../../core/context.ts"; +import { yamlParseFile } from "../../utils/yaml.ts"; +import * as wmill from "../../../gen/services.gen.ts"; + +export async function getSettings( + opts: GlobalOptions & { encrypted?: boolean; json?: boolean }, +) { + await requireLogin(opts); + const workspace = await resolveWorkspace(opts); + const document = await wmill.getWorkspaceSettingsDocument({ + workspace: workspace.workspaceId, + secrets: opts.encrypted ? "encrypted" : "redacted", + }); + console.log( + opts.json ? JSON.stringify(document, null, 2) : yamlStringify(document), + ); +} + +export async function applySettings( + opts: GlobalOptions & { dryRun?: boolean; replace?: boolean; yes?: boolean }, + file: string, +) { + await requireLogin(opts); + const workspace = await resolveWorkspace(opts); + const document = await yamlParseFile(file); + if (!document || typeof document !== "object" || Array.isArray(document)) { + throw new Error(`${file} must hold a settings document (a mapping of setting to value)`); + } + const apply = (dry_run: boolean) => + wmill.applyWorkspaceSettingsDocument({ + workspace: workspace.workspaceId, + requestBody: { document, replace: opts.replace ?? false, dry_run }, + }); + + const plan = await apply(true); + for (const warning of plan.warnings ?? []) { + log.warn(warning); + } + if (plan.changes.length === 0) { + log.info(colors.green("Workspace settings are already up to date")); + return; + } + for (const change of plan.changes) { + log.info( + `${colors.bold(change.key)}: ${JSON.stringify(change.before)} -> ${JSON.stringify(change.after)}`, + ); + } + if (opts.dryRun) { + return; + } + if ( + !opts.yes && + !(await Confirm.prompt({ + message: `Apply ${plan.changes.length} change(s) to workspace ${workspace.workspaceId}?`, + default: true, + })) + ) { + return; + } + const result = await apply(false); + for (const warning of result.warnings ?? []) { + log.warn(warning); + } + log.info( + colors.bold.underline.green( + `Applied ${result.changes.length} change(s) to workspace ${workspace.workspaceId}`, + ), + ); +} diff --git a/cli/src/commands/workspace/workspace.ts b/cli/src/commands/workspace/workspace.ts index 9e12afe54f..caac17136a 100644 --- a/cli/src/commands/workspace/workspace.ts +++ b/cli/src/commands/workspace/workspace.ts @@ -18,6 +18,7 @@ import { requireLogin } from "../../core/auth.ts"; import { createWorkspaceFork, deleteWorkspaceFork } from "./fork.ts"; import { mergeWorkspaces } from "./merge.ts"; import { connectSlack, disconnectSlack } from "./slack.ts"; +import { applySettings, getSettings } from "./settings.ts"; import * as wmill from "../../../gen/services.gen.ts"; @@ -905,6 +906,22 @@ Arguments (omit both to be prompted interactively): .description( "Clear slack_team_id / slack_name on the active workspace (marks the workspace as disconnected). Does NOT remove the bot token variable/resource/folder/group — delete those from the local sync folder and run 'wmill sync push' to tear them down. Does NOT remove the workspace-level OAuth override — set slack_oauth_client_id/_secret to '' in settings.yaml and push." ) - .action(disconnectSlack as any); + .action(disconnectSlack as any) + .command("get-settings") + .description( + "Print the active workspace's settings in the layout of the settings.yaml that 'wmill sync' writes. Secrets show as __SENSITIVE_AND_UNCHANGED__ unless --encrypted. Admin only." + ) + .option("--encrypted", "Write secrets encrypted with the workspace key, as 'wmill sync pull' does") + .option("--json", "Output as JSON") + .action(getSettings as any) + .command("apply-settings") + .description( + "Apply a settings document (YAML or JSON, in the layout of settings.yaml) to the active workspace. Only the settings the file states are changed, unless --replace; a setting set to null is cleared. A secret left as __SENSITIVE_AND_UNCHANGED__ keeps its value. Shows the changes and asks before applying. Admin only." + ) + .arguments("") + .option("--dry-run", "Only show the changes") + .option("--replace", "Also clear the settings the file omits, as 'wmill sync push' does") + .option("-y --yes", "Apply without asking") + .action(applySettings as any); export default command; diff --git a/cli/src/core/conf.ts b/cli/src/core/conf.ts index 455e876292..b010b1f8e3 100644 --- a/cli/src/core/conf.ts +++ b/cli/src/core/conf.ts @@ -89,6 +89,9 @@ export interface SyncOptions { includeUsers?: boolean; includeGroups?: boolean; includeSettings?: boolean; + /** With includeSettings: settings.yaml also states who may connect to each data table as which + * role. Off by default, since tenants and roles are specific to a workspace and an instance. */ + includeDatatablePermissions?: boolean; includeKey?: boolean; skipReencryptOnKeyChange?: boolean; skipBranchValidation?: boolean; @@ -320,12 +323,6 @@ export async function readConfigFile(opts?: { warnIfMissing?: boolean }): Promis delete (conf as any)?.environments; delete conf?.git_branches; - if (conf?.defaultTs == undefined) { - log.warn( - "No defaultTs defined in your wmill.yaml. Using 'bun' as default." - ); - } - // Initialize global nonDottedPaths setting from config setNonDottedPaths(conf?.nonDottedPaths ?? false); @@ -376,7 +373,6 @@ export const DEFAULT_SYNC_OPTIONS: Readonly< Required< Pick< SyncOptions, - | "defaultTs" | "includes" | "excludes" | "codebases" @@ -395,13 +391,13 @@ export const DEFAULT_SYNC_OPTIONS: Readonly< | "includeUsers" | "includeGroups" | "includeSettings" + | "includeDatatablePermissions" | "includeKey" | "nonDottedPaths" | "syncBehavior" > > > = { - defaultTs: "bun", includes: ["f/**"], excludes: [], codebases: [], @@ -418,6 +414,7 @@ export const DEFAULT_SYNC_OPTIONS: Readonly< includeUsers: false, includeGroups: false, includeSettings: false, + includeDatatablePermissions: false, includeKey: false, skipWorkspaceDependencies: false, skipDatatableMigrations: false, diff --git a/cli/src/core/constants.ts b/cli/src/core/constants.ts index d05c4e60a7..d65b343bfe 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.827.0"; +export const VERSION = "1.841.0"; diff --git a/cli/src/core/permissioned_as.ts b/cli/src/core/permissioned_as.ts index d0301373da..dd0b3de8be 100644 --- a/cli/src/core/permissioned_as.ts +++ b/cli/src/core/permissioned_as.ts @@ -34,10 +34,14 @@ export async function buildPermissionedAsContext( return undefined; } const user = await wmill.whoami({ workspace }); + // A superadmin acts as admin in every workspace, so the backend preserves + // ownership for them even when their own `usr` row there is not an admin. const userIsAdminOrDeployer = - user.is_admin || (user.groups ?? []).includes("wm_deployers"); + user.is_admin || + user.is_super_admin || + (user.groups ?? []).includes("wm_deployers"); log.debug( - `permissioned_as: user=${user.email}, is_admin=${user.is_admin}, groups=${JSON.stringify(user.groups)}, isAdminOrDeployer=${userIsAdminOrDeployer}` + `permissioned_as: user=${user.email}, is_admin=${user.is_admin}, is_super_admin=${user.is_super_admin}, groups=${JSON.stringify(user.groups)}, isAdminOrDeployer=${userIsAdminOrDeployer}` ); return { userCache: new Map(), @@ -246,6 +250,18 @@ export async function preCheckPermissionedAs( if (match) { currentOwner = match[1]; } + } else if (typeStr === "resource") { + // An agent with `run_on_behalf_of` runs as someone, and the file never says who. + if ( + /["']?resource_type["']?\s*:\s*["']?ai_agent\b/.test(beforeContent) && + /["']?run_on_behalf_of["']?\s*:\s*true\b/.test(beforeContent) + ) { + wouldChangeItems.push({ + path: change.path, + currentOwner: "(agent owner)", + }); + } + continue; } else if (typeStr.endsWith("_trigger")) { wouldChangeItems.push({ path: change.path, diff --git a/cli/src/core/settings.ts b/cli/src/core/settings.ts index 57e89f5ded..502d0037bb 100644 --- a/cli/src/core/settings.ts +++ b/cli/src/core/settings.ts @@ -58,8 +58,35 @@ export interface SimplifiedSettings { slack_command_script?: string; slack_oauth_client_id?: string; slack_oauth_client_secret?: string; + ducklake?: any; + dbt_warehouses?: any; + deploy_ui?: any; + teams_command_script?: string | null; + public_app_execution_limit_per_minute?: number | null; + guest_access_enabled?: boolean; + guest_jwt_public_key?: string | null; + guest_jwt_jwks_url?: string | null; + error_handler_fallback_to_instance_alerts?: boolean; + add_admins_and_developers_to_forks?: boolean; + datatable_permissions?: Record | null; } +/** Settings the server manages only when settings.yaml states them: a file written before + * they existed must neither clear them nor show as differing from the workspace. */ +export const SETTINGS_MANAGED_ONLY_WHEN_PRESENT = [ + "datatable_permissions", + "ducklake", + "dbt_warehouses", + "deploy_ui", + "teams_command_script", + "public_app_execution_limit_per_minute", + "guest_access_enabled", + "guest_jwt_public_key", + "guest_jwt_jwks_url", + "error_handler_fallback_to_instance_alerts", + "add_admins_and_developers_to_forks", +] as const; + // Legacy settings interface for reading old settings.yaml files interface LegacySimplifiedSettings { auto_invite_enabled?: boolean; @@ -108,6 +135,9 @@ export function migrateToGroupedFormat(settings: any): SimplifiedSettings { if (settings.slack_command_script !== undefined) result.slack_command_script = settings.slack_command_script; if (settings.slack_oauth_client_id !== undefined) result.slack_oauth_client_id = settings.slack_oauth_client_id; if (settings.slack_oauth_client_secret !== undefined) result.slack_oauth_client_secret = settings.slack_oauth_client_secret; + for (const key of SETTINGS_MANAGED_ONLY_WHEN_PRESENT) { + if (settings[key] !== undefined) (result as any)[key] = settings[key]; + } // Handle auto_invite: check if already grouped or needs migration if (settings.auto_invite && typeof settings.auto_invite === "object") { @@ -173,10 +203,37 @@ export async function pushWorkspaceSettings( workspace: string, _path: string, settings: SimplifiedSettings | undefined, - localSettings: SimplifiedSettings | any + localSettings: SimplifiedSettings | any, + opts: { includeDatatablePermissions?: boolean } = {}, ) { + if (localSettings?.protection_rules !== undefined) { + log.warn( + "Ignoring protection_rules in settings.yaml: protection-rules.yaml syncs them (wmill protection-rules push)." + ); + } // Migrate local settings from legacy format if needed localSettings = migrateToGroupedFormat(localSettings); + if (!opts.includeDatatablePermissions) { + delete localSettings.datatable_permissions; + } + + if (await applySettingsDocument(workspace, localSettings)) { + return; + } + // The per-setting endpoints of a server without the settings document know nothing of + // these keys, nor of a secret it would have to decrypt or keep. + for (const key of SETTINGS_MANAGED_ONLY_WHEN_PRESENT) { + delete (localSettings as any)[key]; + } + const secret = localSettings.slack_oauth_client_secret; + const slackSecretUnreadable = + typeof secret === "string" && + (secret.startsWith("$encrypted:") || secret === "__SENSITIVE_AND_UNCHANGED__"); + if (slackSecretUnreadable) { + log.warn( + "Leaving the Slack OAuth client and secret unchanged: this server cannot read an encrypted or redacted secret. Upgrade it, or write the secret in plain text." + ); + } try { const remoteSettings = await wmill.getSettings({ @@ -413,7 +470,7 @@ export async function pushWorkspaceSettings( const localOperatorSettings = localSettings.operator_settings && { ...localSettings.operator_settings, }; - for (const key of ["builder_flows", "manage_schedules", "manage_triggers"] as const) { + for (const key of ["builder_flows", "builder_apps", "manage_schedules", "manage_triggers"] as const) { const remote = settings.operator_settings?.[key]; if (localOperatorSettings && localOperatorSettings[key] === undefined && remote !== undefined) { localOperatorSettings[key] = remote; @@ -456,8 +513,9 @@ export async function pushWorkspaceSettings( // every other setting): both present → upsert; anything else → delete. // Pull always emits both fields as null when remote is NULL. if ( - localSettings.slack_oauth_client_id != settings.slack_oauth_client_id || - localSettings.slack_oauth_client_secret != settings.slack_oauth_client_secret + !slackSecretUnreadable && + (localSettings.slack_oauth_client_id != settings.slack_oauth_client_id || + localSettings.slack_oauth_client_secret != settings.slack_oauth_client_secret) ) { log.debug(`Updating slack oauth config...`); if ( @@ -477,6 +535,38 @@ export async function pushWorkspaceSettings( } } +/** Applies settings.yaml server-side, which owns the rules for what an omitted or null setting + * means. Returns false on a server that predates the settings document. */ +async function applySettingsDocument( + workspace: string, + document: SimplifiedSettings, +): Promise { + let result; + try { + result = await wmill.applyWorkspaceSettingsDocument({ + workspace, + requestBody: { document: document as unknown as Record, replace: true }, + }); + } catch (err: any) { + // A missing route answers 404 with no body; a handler's own 404 carries a message. + if (err?.status === 404 && !err?.body) { + return false; + } + throw new Error(`Failed to apply workspace settings: ${err?.body ?? err}`); + } + if (result.changes.length > 0) { + log.debug( + `Updated workspace settings: ${result.changes.map((c) => c.key).join(", ")}`, + ); + } else { + log.debug(`Workspace settings are up to date`); + } + for (const warning of result.warnings ?? []) { + log.warn(warning); + } + return true; +} + export interface PushWorkspaceKeyOptions { // True when no prompt may be shown (e.g. `--yes` was passed or stdin is not a // TTY). In that case the re-encryption decision is taken from `skipReencrypt` diff --git a/cli/src/core/specific_items.ts b/cli/src/core/specific_items.ts index cbfd52530e..12cc725b53 100644 --- a/cli/src/core/specific_items.ts +++ b/cli/src/core/specific_items.ts @@ -1,6 +1,10 @@ import { minimatch } from "minimatch"; import { getCurrentGitBranch, isGitRepository } from "../utils/git.ts"; import { isFileResource, isFilesetResource } from "../utils/utils.ts"; +import { + isFolderResourcePathAnyFormat, + isScriptModulePath, +} from "../utils/resource_folders.ts"; import { SyncOptions, findWorkspaceByGitBranch, @@ -37,10 +41,32 @@ function getWorkspaceSpecificTypeKinds(): string[] { 'variable', 'resource', 'schedule', + 'custom_path', ...TRIGGER_TYPES.map(t => `${t}_trigger`), ]; } +/** + * An app's custom path is always workspace-specific, with or without + * specificItems: unless routes are workspace-prefixed it is unique across the + * instance, so one shared value can never be deployed to two workspaces. + */ +export function isCustomPathFile(path: string): boolean { + const p = path.replaceAll('\\', '/'); + const slash = p.lastIndexOf('/'); + const parts = p.slice(slash + 1).split('.'); + return ( + (parts.length == 3 || parts.length == 4) && + parts[parts.length - 2] == 'custom_path' && + (parts[parts.length - 1] == 'yaml' || parts[parts.length - 1] == 'json') && + // It sits beside its app. A file inside an item's folder (app, flow, + // fileset, script module) is that item's content, whatever its name. + !p.slice(0, slash + 1).includes('.') && + !isFolderResourcePathAnyFormat(p) && + !isScriptModulePath(p) + ); +} + /** * Check if a path ends with any trigger type */ @@ -80,7 +106,7 @@ function getFileTypeSuffix(path: string): string | null { * Build regex pattern for all supported item-kind file types */ function buildItemTypePattern(): string { - const basicTypes = ['variable', 'resource', 'schedule']; + const basicTypes = ['variable', 'resource', 'schedule', 'custom_path']; const triggerTypes = TRIGGER_TYPES.map(t => `${t}_trigger`); return `((${basicTypes.join('|')})|(${triggerTypes.join('|')}))`; } @@ -190,6 +216,9 @@ function normalizeJsonToYaml(path: string): string { * Used to determine if workspace-specific files should be used for this type. */ export function isItemTypeConfigured(path: string, specificItems: SpecificItemsConfig | undefined): boolean { + if (isCustomPathFile(path)) { + return true; + } if (!specificItems) { return false; } @@ -231,6 +260,9 @@ export function isItemTypeConfigured(path: string, specificItems: SpecificItemsC * Check if a file path should be treated as workspace-specific */ export function isSpecificItem(path: string, specificItems: SpecificItemsConfig | undefined): boolean { + if (isCustomPathFile(path)) { + return true; + } if (!specificItems) { return false; } @@ -399,7 +431,7 @@ export function getWorkspaceSpecificPath( specificItems: SpecificItemsConfig | undefined, workspaceNameOverride?: string ): string | undefined { - if (!specificItems) { + if (!specificItems && !isCustomPathFile(basePath)) { return undefined; } @@ -434,8 +466,9 @@ export function isCurrentWorkspaceFile(path: string, workspaceNameOverride?: str // Their names are arbitrary, so one can look like typed metadata — and since // the patterns match a workspace-name segment with `[^.]` (which spans `/`), // an unguarded child is dropped from the diff or, worse, remapped onto a - // sibling's key and deployed over it. - if (isFilesetResource(path)) { + // sibling's key and deployed over it. The same holds for the files inside a + // flow or app folder. + if (isFilesetResource(path) || isFolderResourcePathAnyFormat(path)) { return false; } let currentWorkspace: string | null = null; @@ -473,8 +506,8 @@ export function isCurrentWorkspaceFile(path: string, workspaceNameOverride?: str * Used to identify and skip files from other branches during sync operations */ export function isWorkspaceSpecificFile(path: string): boolean { - // Same fileset exemption as isCurrentWorkspaceFile. - if (isFilesetResource(path)) { + // Same exemptions as isCurrentWorkspaceFile. + if (isFilesetResource(path) || isFolderResourcePathAnyFormat(path)) { return false; } const typePattern = buildItemTypePattern(); diff --git a/cli/src/guidance/skills.gen.ts b/cli/src/guidance/skills.gen.ts index dc9541b4c5..7d0cf5c1cc 100644 --- a/cli/src/guidance/skills.gen.ts +++ b/cli/src/guidance/skills.gen.ts @@ -34,6 +34,8 @@ export const SKILLS: SkillMetadata[] = [ { name: "resources", description: "MUST use when managing resources." }, { name: "write-workflow-as-code", description: "MUST use when writing or modifying Windmill Workflow-as-Code scripts using workflow, task, step, sleep, approvals, taskScript, taskFlow, task_script, or task_flow." }, { name: "write-pipeline", description: "MUST use when creating or modifying a data pipeline, a set of scripts marked `pipeline` and wired together by `on` / `materialize` annotations." }, + { name: "datatables", description: "MUST use when changing a data table's schema, writing or running its migrations, or working with its roles and permissions." }, + { name: "workspace-settings", description: "MUST use when reading or changing workspace settings, or the settings.yaml file `wmill sync` keeps." }, { name: "cli-commands", description: "MUST use when using the CLI, including debugging job failures and inspecting run history via `wmill job`." }, { name: "preview", description: "MUST use when opening the Windmill dev page / visual preview of a flow, script, or app. Triggers on words like preview, open, navigate to, visualize, see the flow/app/script, and after writing a flow/script/app for visual verification." }, ]; @@ -95,6 +97,9 @@ Use \`wmill resource-type list --schema\` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named \`c_\`, which keeps it apart from a hub type synced later: the parameter takes \`RT.C\` in TypeScript, a \`c_\` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (\`type Stripe = { token: string }\`), which is still the \`stripe\` resource type; in code you write, name it the way the language section shows (\`RT.Stripe\` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run \`wmill resource-type list\`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it \`main\` (\`Main\` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no \`main\`: their language section shows how they take arguments - Where the language has a Windmill client (\`wmill\`), use it to interact with the platform @@ -259,6 +264,9 @@ Use \`wmill resource-type list --schema\` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named \`c_\`, which keeps it apart from a hub type synced later: the parameter takes \`RT.C\` in TypeScript, a \`c_\` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (\`type Stripe = { token: string }\`), which is still the \`stripe\` resource type; in code you write, name it the way the language section shows (\`RT.Stripe\` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run \`wmill resource-type list\`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it \`main\` (\`Main\` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no \`main\`: their language section shows how they take arguments - Where the language has a Windmill client (\`wmill\`), use it to interact with the platform @@ -383,6 +391,9 @@ Use \`wmill resource-type list --schema\` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named \`c_\`, which keeps it apart from a hub type synced later: the parameter takes \`RT.C\` in TypeScript, a \`c_\` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (\`type Stripe = { token: string }\`), which is still the \`stripe\` resource type; in code you write, name it the way the language section shows (\`RT.Stripe\` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run \`wmill resource-type list\`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it \`main\` (\`Main\` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no \`main\`: their language section shows how they take arguments - Where the language has a Windmill client (\`wmill\`), use it to interact with the platform @@ -500,6 +511,9 @@ Use \`wmill resource-type list --schema\` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named \`c_\`, which keeps it apart from a hub type synced later: the parameter takes \`RT.C\` in TypeScript, a \`c_\` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (\`type Stripe = { token: string }\`), which is still the \`stripe\` resource type; in code you write, name it the way the language section shows (\`RT.Stripe\` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run \`wmill resource-type list\`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it \`main\` (\`Main\` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no \`main\`: their language section shows how they take arguments - Where the language has a Windmill client (\`wmill\`), use it to interact with the platform @@ -839,6 +853,14 @@ async setProgress(percent: number, jobId?: any): Promise */ async getProgress(jobId?: any): Promise +/** + * Whether the worker running this job has received its shutdown signal. + * A draining worker waits for its current job to finish before exiting, so a + * long-running script can poll this and return early to let the worker be replaced. + * @param jobId? Job to check, defaults to the current job + */ +async workerIsDraining(jobId?: string): Promise + /** * Set a flow user state * @param key key of the state @@ -1098,6 +1120,9 @@ async sleep(seconds: number): Promise * \`fn\`'s result is encoded as JSON and decoded back before it is returned, so * the round that runs the body sees the same types every replay sees: a \`Date\` * comes back as a string, a \`Map\` as \`{}\`. {@link Jsonified} is that shape. + * + * Called from inside a task body, \`fn\` runs in place and nothing is + * checkpointed: a task is a single job and is never replayed. */ async step(name: string, fn: () => T | Promise,): Promise>> @@ -1323,6 +1348,9 @@ Use \`wmill resource-type list --schema\` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named \`c_\`, which keeps it apart from a hub type synced later: the parameter takes \`RT.C\` in TypeScript, a \`c_\` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (\`type Stripe = { token: string }\`), which is still the \`stripe\` resource type; in code you write, name it the way the language section shows (\`RT.Stripe\` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run \`wmill resource-type list\`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it \`main\` (\`Main\` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no \`main\`: their language section shows how they take arguments - Where the language has a Windmill client (\`wmill\`), use it to interact with the platform @@ -1391,7 +1419,7 @@ export async function main(url: string) { ## Pure computation: \`//no_network\` -A native script that only transforms its inputs can declare \`//no_network\` in its leading comment block (right after \`//native\`). The runtime then refuses every connection the script attempts: \`fetch\` to any host, the Windmill API (so \`windmill-client\` calls fail too), raw sockets and unix sockets, and \`WM_TOKEN\` is not set. It only takes effect on native scripts: without \`//native\` it is ignored. Use it only when the script needs no external data beyond its arguments: +A native script that only transforms its inputs can declare \`//no_network\` in its leading comment block (right after \`//native\`). The runtime then refuses every connection the script attempts: \`fetch\` to any host, the Windmill API (so \`windmill-client\` calls fail too), raw sockets and unix sockets, and \`WM_TOKEN\` is not set. Without \`//native\` it means something else: the script must run in an nsjail sandbox (\`//sandbox\`, or instance-wide sandboxing), which then loses its network, and it fails to run otherwise. Use it only when the script needs no external data beyond its arguments: \`\`\`typescript //native @@ -1674,6 +1702,14 @@ async setProgress(percent: number, jobId?: any): Promise */ async getProgress(jobId?: any): Promise +/** + * Whether the worker running this job has received its shutdown signal. + * A draining worker waits for its current job to finish before exiting, so a + * long-running script can poll this and return early to let the worker be replaced. + * @param jobId? Job to check, defaults to the current job + */ +async workerIsDraining(jobId?: string): Promise + /** * Set a flow user state * @param key key of the state @@ -1933,6 +1969,9 @@ async sleep(seconds: number): Promise * \`fn\`'s result is encoded as JSON and decoded back before it is returned, so * the round that runs the body sees the same types every replay sees: a \`Date\` * comes back as a string, a \`Map\` as \`{}\`. {@link Jsonified} is that shape. + * + * Called from inside a task body, \`fn\` runs in place and nothing is + * checkpointed: a task is a single job and is never replayed. */ async step(name: string, fn: () => T | Promise,): Promise>> @@ -2158,6 +2197,9 @@ Use \`wmill resource-type list --schema\` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named \`c_\`, which keeps it apart from a hub type synced later: the parameter takes \`RT.C\` in TypeScript, a \`c_\` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (\`type Stripe = { token: string }\`), which is still the \`stripe\` resource type; in code you write, name it the way the language section shows (\`RT.Stripe\` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run \`wmill resource-type list\`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it \`main\` (\`Main\` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no \`main\`: their language section shows how they take arguments - Where the language has a Windmill client (\`wmill\`), use it to interact with the platform @@ -2274,6 +2316,9 @@ Use \`wmill resource-type list --schema\` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named \`c_\`, which keeps it apart from a hub type synced later: the parameter takes \`RT.C\` in TypeScript, a \`c_\` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (\`type Stripe = { token: string }\`), which is still the \`stripe\` resource type; in code you write, name it the way the language section shows (\`RT.Stripe\` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run \`wmill resource-type list\`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it \`main\` (\`Main\` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no \`main\`: their language section shows how they take arguments - Where the language has a Windmill client (\`wmill\`), use it to interact with the platform @@ -2615,6 +2660,14 @@ async setProgress(percent: number, jobId?: any): Promise */ async getProgress(jobId?: any): Promise +/** + * Whether the worker running this job has received its shutdown signal. + * A draining worker waits for its current job to finish before exiting, so a + * long-running script can poll this and return early to let the worker be replaced. + * @param jobId? Job to check, defaults to the current job + */ +async workerIsDraining(jobId?: string): Promise + /** * Set a flow user state * @param key key of the state @@ -2874,6 +2927,9 @@ async sleep(seconds: number): Promise * \`fn\`'s result is encoded as JSON and decoded back before it is returned, so * the round that runs the body sees the same types every replay sees: a \`Date\` * comes back as a string, a \`Map\` as \`{}\`. {@link Jsonified} is that shape. + * + * Called from inside a task body, \`fn\` runs in place and nothing is + * checkpointed: a task is a single job and is never replayed. */ async step(name: string, fn: () => T | Promise,): Promise>> @@ -3099,6 +3155,9 @@ Use \`wmill resource-type list --schema\` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named \`c_\`, which keeps it apart from a hub type synced later: the parameter takes \`RT.C\` in TypeScript, a \`c_\` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (\`type Stripe = { token: string }\`), which is still the \`stripe\` resource type; in code you write, name it the way the language section shows (\`RT.Stripe\` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run \`wmill resource-type list\`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it \`main\` (\`Main\` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no \`main\`: their language section shows how they take arguments - Where the language has a Windmill client (\`wmill\`), use it to interact with the platform @@ -3249,6 +3308,9 @@ Use \`wmill resource-type list --schema\` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named \`c_\`, which keeps it apart from a hub type synced later: the parameter takes \`RT.C\` in TypeScript, a \`c_\` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (\`type Stripe = { token: string }\`), which is still the \`stripe\` resource type; in code you write, name it the way the language section shows (\`RT.Stripe\` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run \`wmill resource-type list\`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it \`main\` (\`Main\` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no \`main\`: their language section shows how they take arguments - Where the language has a Windmill client (\`wmill\`), use it to interact with the platform @@ -3382,6 +3444,9 @@ Use \`wmill resource-type list --schema\` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named \`c_\`, which keeps it apart from a hub type synced later: the parameter takes \`RT.C\` in TypeScript, a \`c_\` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (\`type Stripe = { token: string }\`), which is still the \`stripe\` resource type; in code you write, name it the way the language section shows (\`RT.Stripe\` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run \`wmill resource-type list\`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it \`main\` (\`Main\` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no \`main\`: their language section shows how they take arguments - Where the language has a Windmill client (\`wmill\`), use it to interact with the platform @@ -3502,6 +3567,9 @@ Use \`wmill resource-type list --schema\` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named \`c_\`, which keeps it apart from a hub type synced later: the parameter takes \`RT.C\` in TypeScript, a \`c_\` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (\`type Stripe = { token: string }\`), which is still the \`stripe\` resource type; in code you write, name it the way the language section shows (\`RT.Stripe\` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run \`wmill resource-type list\`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it \`main\` (\`Main\` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no \`main\`: their language section shows how they take arguments - Where the language has a Windmill client (\`wmill\`), use it to interact with the platform @@ -3615,6 +3683,9 @@ Use \`wmill resource-type list --schema\` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named \`c_\`, which keeps it apart from a hub type synced later: the parameter takes \`RT.C\` in TypeScript, a \`c_\` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (\`type Stripe = { token: string }\`), which is still the \`stripe\` resource type; in code you write, name it the way the language section shows (\`RT.Stripe\` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run \`wmill resource-type list\`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it \`main\` (\`Main\` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no \`main\`: their language section shows how they take arguments - Where the language has a Windmill client (\`wmill\`), use it to interact with the platform @@ -3731,6 +3802,9 @@ Use \`wmill resource-type list --schema\` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named \`c_\`, which keeps it apart from a hub type synced later: the parameter takes \`RT.C\` in TypeScript, a \`c_\` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (\`type Stripe = { token: string }\`), which is still the \`stripe\` resource type; in code you write, name it the way the language section shows (\`RT.Stripe\` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run \`wmill resource-type list\`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it \`main\` (\`Main\` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no \`main\`: their language section shows how they take arguments - Where the language has a Windmill client (\`wmill\`), use it to interact with the platform @@ -3848,6 +3922,9 @@ Use \`wmill resource-type list --schema\` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named \`c_\`, which keeps it apart from a hub type synced later: the parameter takes \`RT.C\` in TypeScript, a \`c_\` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (\`type Stripe = { token: string }\`), which is still the \`stripe\` resource type; in code you write, name it the way the language section shows (\`RT.Stripe\` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run \`wmill resource-type list\`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it \`main\` (\`Main\` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no \`main\`: their language section shows how they take arguments - Where the language has a Windmill client (\`wmill\`), use it to interact with the platform @@ -3980,6 +4057,9 @@ Use \`wmill resource-type list --schema\` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named \`c_\`, which keeps it apart from a hub type synced later: the parameter takes \`RT.C\` in TypeScript, a \`c_\` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (\`type Stripe = { token: string }\`), which is still the \`stripe\` resource type; in code you write, name it the way the language section shows (\`RT.Stripe\` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run \`wmill resource-type list\`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it \`main\` (\`Main\` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no \`main\`: their language section shows how they take arguments - Where the language has a Windmill client (\`wmill\`), use it to interact with the platform @@ -4095,6 +4175,9 @@ Use \`wmill resource-type list --schema\` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named \`c_\`, which keeps it apart from a hub type synced later: the parameter takes \`RT.C\` in TypeScript, a \`c_\` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (\`type Stripe = { token: string }\`), which is still the \`stripe\` resource type; in code you write, name it the way the language section shows (\`RT.Stripe\` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run \`wmill resource-type list\`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it \`main\` (\`Main\` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no \`main\`: their language section shows how they take arguments - Where the language has a Windmill client (\`wmill\`), use it to interact with the platform @@ -4225,6 +4308,9 @@ Use \`wmill resource-type list --schema\` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named \`c_\`, which keeps it apart from a hub type synced later: the parameter takes \`RT.C\` in TypeScript, a \`c_\` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (\`type Stripe = { token: string }\`), which is still the \`stripe\` resource type; in code you write, name it the way the language section shows (\`RT.Stripe\` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run \`wmill resource-type list\`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it \`main\` (\`Main\` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no \`main\`: their language section shows how they take arguments - Where the language has a Windmill client (\`wmill\`), use it to interact with the platform @@ -4620,6 +4706,18 @@ def set_progress(value: int, job_id: Optional[str] = None) # Progress value (0-100) or None if not set def get_progress(job_id: Optional[str] = None) -> Any +# Whether the worker running the job has received its shutdown signal. +# +# A draining worker waits for its current job to finish before exiting. A long-running +# script can poll this and return early so the worker can be replaced. +# +# Args: +# job_id: Job ID (defaults to current WM_JOB_ID) +# +# Returns: +# True if the worker running the job is draining +def worker_is_draining(job_id: Optional[str] = None) -> bool + # Set the user state of a flow at a given key def set_flow_user_state(key: str, value: Any) -> None @@ -4633,15 +4731,31 @@ def get_flow_user_state(key: str) -> Any def version() # Convenient helpers that takes an S3 resource as input and returns the settings necessary to -# initiate an S3 connection from DuckDB +# initiate an S3 connection from DuckDB. +# +# Without a resource path, the connection goes to the workspace storage through Windmill's +# S3 proxy when that storage is S3: address it as \`\`s3:///\`\` with the +# storage's own bucket, returned as \`\`s3_bucket\`\`. Pass the resource path to connect with +# the storage's own credentials instead. def get_duckdb_connection_settings(s3_resource_path: str = '') -> DuckDbConnectionSettings | None # Convenient helpers that takes an S3 resource as input and returns the settings necessary to -# initiate an S3 connection from Polars +# initiate an S3 connection from Polars. +# +# Without a resource path, the connection goes to the workspace storage through Windmill's +# S3 proxy when that storage is S3: address it as \`\`s3:///\`\` with the +# storage's own bucket, returned as \`\`s3_bucket\`\`. Pass the resource path to connect with +# the storage's own credentials instead. def get_polars_connection_settings(s3_resource_path: str = '') -> PolarsConnectionSettings # Convenient helpers that takes an S3 resource as input and returns the settings necessary to -# initiate an S3 connection using boto3 +# initiate an S3 connection using boto3. +# +# Without a resource path, the connection goes to the workspace storage through Windmill's +# S3 proxy when that storage is S3: pass the storage's own bucket as \`\`Bucket\`\`. The proxy +# serves object reads, writes, deletes, listing and multipart uploads of that bucket only; +# presigned URLs, other buckets and bucket-level APIs need the storage's own credentials, +# which passing the resource path returns. def get_boto3_connection_settings(s3_resource_path: str = '') -> Boto3ConnectionSettings # Load a file from the workspace s3 bucket and returns its content as bytes. @@ -5037,7 +5151,9 @@ def parse_sql_client_name(name: str) -> tuple[str, Optional[str]] # # - **v2 (inside @workflow)**: dispatches as a checkpoint step. # - **v1 (WM_JOB_ID set, no @workflow)**: dispatches via HTTP API. -# - **Standalone**: executes the function body directly. +# - **Standalone, or called from inside another v2 task**: executes the +# function body directly. A task runs as a single job, so the tasks it +# calls run in that same job, without their own options. # # A task runs as its own job, so its result is always encoded as JSON and # decoded back before the caller sees it: a \`\`datetime\`\` comes back as a @@ -5123,12 +5239,15 @@ def workflow(func) # \`\`fn\`\`'s result is encoded as JSON and decoded back before it is returned, # so the round that runs the body sees the same types every replay sees: # a \`\`datetime\`\` comes back as a string, a tuple as a list. +# +# Called from inside a task body, \`\`fn\`\` runs in place and nothing is +# checkpointed: a task is a single job and is never replayed. async def step(name: str, fn) # Server-side sleep — suspend the workflow for the given duration without holding a worker. # # Inside a @workflow, the parent job suspends and auto-resumes after \`\`seconds\`\`. -# Outside a workflow, falls back to \`\`asyncio.sleep\`\`. +# Outside a workflow, or inside a task body, falls back to \`\`asyncio.sleep\`\`. async def sleep(seconds: int) # Suspend the workflow and wait for an external approval. @@ -5234,6 +5353,9 @@ Use \`wmill resource-type list --schema\` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named \`c_\`, which keeps it apart from a hub type synced later: the parameter takes \`RT.C\` in TypeScript, a \`c_\` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (\`type Stripe = { token: string }\`), which is still the \`stripe\` resource type; in code you write, name it the way the language section shows (\`RT.Stripe\` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run \`wmill resource-type list\`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it \`main\` (\`Main\` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no \`main\`: their language section shows how they take arguments - Where the language has a Windmill client (\`wmill\`), use it to interact with the platform @@ -5394,6 +5516,9 @@ Use \`wmill resource-type list --schema\` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named \`c_\`, which keeps it apart from a hub type synced later: the parameter takes \`RT.C\` in TypeScript, a \`c_\` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (\`type Stripe = { token: string }\`), which is still the \`stripe\` resource type; in code you write, name it the way the language section shows (\`RT.Stripe\` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run \`wmill resource-type list\`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it \`main\` (\`Main\` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no \`main\`: their language section shows how they take arguments - Where the language has a Windmill client (\`wmill\`), use it to interact with the platform @@ -5544,6 +5669,9 @@ Use \`wmill resource-type list --schema\` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named \`c_\`, which keeps it apart from a hub type synced later: the parameter takes \`RT.C\` in TypeScript, a \`c_\` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (\`type Stripe = { token: string }\`), which is still the \`stripe\` resource type; in code you write, name it the way the language section shows (\`RT.Stripe\` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run \`wmill resource-type list\`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it \`main\` (\`Main\` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no \`main\`: their language section shows how they take arguments - Where the language has a Windmill client (\`wmill\`), use it to interact with the platform @@ -5575,6 +5703,27 @@ Name the parameters by adding comments before the statement: SELECT * FROM users WHERE name = ? AND age > ?; \`\`\` +## Array parameters + +Declare a list with a \`[]\` suffix on the element type (\`(varchar[])\`, +\`(int[])\`), or \`(array)\` for an untyped one. Snowflake cannot bind an array +directly, so Windmill binds the list as JSON text: wrap the placeholder with +\`PARSE_JSON(?)\`, and cast to \`ARRAY\` where a function expects one. + +\`\`\`sql +-- ? groups (varchar[]) +SELECT o.* FROM orders o +WHERE ARRAY_CONTAINS(o.owner_group::VARIANT, PARSE_JSON(?)::ARRAY); +\`\`\` + +Or join on the elements with \`FLATTEN\`: + +\`\`\`sql +-- ? groups (varchar[]) +SELECT o.* FROM orders o +JOIN TABLE(FLATTEN(input => PARSE_JSON(?))) g ON g.value::STRING = o.owner_group; +\`\`\` + ## Receiving an S3Object as a script parameter Declare the arg with type \`(s3object)\`. Windmill renders an S3 file picker for @@ -5844,6 +5993,10 @@ needs becomes unreachable. references. A spread, a call or a computed key leaves the composer unable to tell which input feeds which field, so it offers no control at all — a bare \`flow_input.x\` for the whole object is read instead as that one input carrying every field +- A step linked to a saved agent (\`agent\` set) has no \`provider\` of its own. It exposes the same + two controls through its \`model\` and \`reasoning_effort\` inputs, which replace what the agent + saved: \`"model": { "type": "javascript", "expr": "flow_input.model" }\`. An empty model keeps the + saved one, an empty effort sends none, and the provider resource always stays the agent's - \`memory\` is what lets the agent see earlier turns; without it every message starts from nothing - \`streaming\` on makes the answer and its thinking appear token by token instead of all at once - \`user_attachments\` points at a flow input typed as an array of s3 objects @@ -6279,6 +6432,14 @@ In the flow schema, set the property type to \`"object"\` with format \`"resourc } \`\`\` +### When No Resource Type Fits + +A connection still comes in as one resource input, not as separate string inputs (a URL, a token) or a variable read inside a step: type the input \`resource-c_\` with a custom resource type holding the service's connection fields, its secret in a variable the resource references. The \`c_\` prefix of custom types keeps one apart from a hub type synced later under the same name. + +- If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. +- Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it. +- A plain variable is fine when the user asks for it. + ### As Step Input (Static Reference) Reference a specific resource using \`$res:\` prefix: @@ -6294,7 +6455,7 @@ Reference a specific resource using \`$res:\` prefix: ## OpenFlow Schema -{"OpenFlow":{"type":"object","description":"Top-level flow definition containing metadata, configuration, and the flow structure","properties":{"summary":{"type":"string","description":"Short description of what this flow does"},"description":{"type":"string","description":"Detailed documentation for this flow"},"value":{"$ref":"#/components/schemas/FlowValue"},"schema":{"type":"object","description":"JSON Schema for flow inputs. Use this to define input parameters, their types, defaults, and validation. For resource inputs, set type to 'object' and format to 'resource-' (e.g., 'resource-stripe')"},"on_behalf_of_email":{"type":"string","description":"Address of the account the flow runs on behalf of. Derived from on_behalf_of on read; accepted on write, where it is resolved to the account it names."},"on_behalf_of":{"type":"string","description":"The flow runs with the permissions of this identity: u/{username}, g/{group}, or a bare email when the username is itself email-shaped. The only stored half of the identity; on_behalf_of_email is derived from it. Omit it when writing and it is resolved from that address instead."}},"required":["summary","value"]},"FlowValue":{"type":"object","description":"The flow structure containing modules and optional preprocessor/failure handlers","properties":{"modules":{"type":"array","description":"Array of steps that execute in sequence. Each step can be a script, subflow, loop, or branch","items":{"$ref":"#/components/schemas/FlowModule"}},"failure_module":{"description":"Special module that executes when the flow fails. Receives error object with message, name, stack, and step_id. Must have id 'failure'. Only supports script/rawscript types","$ref":"#/components/schemas/FlowModule"},"preprocessor_module":{"description":"Special module that runs before the first step on external triggers. Must have id 'preprocessor'. Only supports script/rawscript types. Cannot reference other step results","$ref":"#/components/schemas/FlowModule"},"same_worker":{"type":"boolean","description":"If true, all steps run on the same worker for better performance"},"preserve_step_tags":{"type":"boolean","description":"If true and the flow runs on a custom worker tag, steps that declare their own non-empty tag run on it instead of inheriting the flow tag. Steps without their own tag still inherit the flow tag."},"concurrent_limit":{"type":"number","description":"Maximum number of concurrent executions of this flow"},"concurrency_key":{"type":"string","description":"Expression to group concurrent executions (e.g., by user ID)"},"concurrency_time_window_s":{"type":"number","description":"Time window in seconds for concurrent_limit"},"debounce_delay_s":{"type":"integer","description":"Delay in seconds to debounce flow executions"},"debounce_key":{"type":"string","description":"Expression to group debounced executions"},"debounce_args_to_accumulate":{"type":"array","description":"Arguments to accumulate across debounced executions","items":{"type":"string"}},"max_total_debouncing_time":{"type":"integer","description":"Maximum total time in seconds that a job can be debounced"},"max_total_debounces_amount":{"type":"integer","description":"Maximum number of times a job can be debounced"},"skip_expr":{"type":"string","description":"JavaScript expression to conditionally skip the entire flow"},"cache_ttl":{"type":"number","description":"Cache duration in seconds for flow results"},"cache_ignore_s3_path":{"type":"boolean"},"delete_after_secs":{"type":"integer","description":"If set, delete the flow job's args, result and logs after this many seconds following job completion"},"flow_env":{"type":"object","description":"Environment variables available to all steps. Values can be strings, JSON values, or special references: '$var:path' (workspace variable) or '$res:path' (resource).","additionalProperties":{}},"priority":{"type":"number","description":"Execution priority (higher numbers run first)"},"early_return":{"type":"string","description":"JavaScript expression to return early from the flow"},"chat_input_enabled":{"type":"boolean","description":"Whether this flow accepts chat-style input"},"notes":{"type":"array","description":"Sticky notes attached to the flow","items":{"$ref":"#/components/schemas/FlowNote"}},"groups":{"type":"array","description":"Semantic groups of modules for organizational purposes","items":{"$ref":"#/components/schemas/FlowGroup"}}},"required":["modules"]},"Retry":{"type":"object","description":"Retry configuration for failed module executions","properties":{"constant":{"type":"object","description":"Retry with constant delay between attempts","properties":{"attempts":{"type":"integer","description":"Number of retry attempts"},"seconds":{"type":"integer","description":"Seconds to wait between retries"}}},"exponential":{"type":"object","description":"Retry with exponential backoff: the n-th retry waits multiplier \\u00d7 seconds^n","properties":{"attempts":{"type":"integer","description":"Number of retry attempts"},"multiplier":{"type":"integer","description":"Multiplier for exponential backoff"},"seconds":{"type":"integer","minimum":1,"description":"Base of the exponential (seconds); the n-th retry waits multiplier \\u00d7 seconds^n, where n counts constant retries too"},"random_factor":{"type":"integer","minimum":0,"maximum":100,"description":"Random jitter percentage (0-100) to avoid thundering herd"}}},"retry_if":{"$ref":"#/components/schemas/RetryIf"}}},"FlowNote":{"type":"object","description":"A sticky note attached to a flow for documentation and annotation","properties":{"id":{"type":"string","description":"Unique identifier for the note"},"text":{"type":"string","description":"Content of the note"},"position":{"type":"object","description":"Position of the note in the flow editor","properties":{"x":{"type":"number","description":"X coordinate"},"y":{"type":"number","description":"Y coordinate"}},"required":["x","y"]},"size":{"type":"object","description":"Size of the note in the flow editor","properties":{"width":{"type":"number","description":"Width in pixels"},"height":{"type":"number","description":"Height in pixels"}},"required":["width","height"]},"color":{"type":"string","description":"Color of the note, one of: yellow, blue, green, purple, pink, orange, red, cyan, lime, gray. Any other value renders unstyled."},"type":{"type":"string","enum":["free","group"],"description":"Type of note - 'free' for standalone notes. 'group' notes are deprecated; segment a flow with FlowValue.groups instead."},"locked":{"type":"boolean","default":false,"description":"Whether the note is locked and cannot be edited or moved"},"contained_node_ids":{"type":"array","items":{"type":"string"},"description":"For group notes, the IDs of nodes contained within this group"}},"required":["id","text","color","type"]},"FlowGroup":{"type":"object","description":"A semantic group of flow modules for organizational purposes. Does not affect execution \\u2014 modules remain in their original position in the flow. Groups provide naming and collapsibility in the editor. Members are computed dynamically from all nodes on paths between start_id and end_id.","properties":{"summary":{"type":"string","description":"Display name for this group"},"note":{"type":"string","description":"Markdown note shown below the group header"},"autocollapse":{"type":"boolean","default":false,"description":"If true, this group is collapsed by default in the flow editor. UI hint only."},"start_id":{"type":"string","description":"ID of the first flow module in this group (topological entry point)"},"end_id":{"type":"string","description":"ID of the last flow module in this group (topological exit point)"},"color":{"type":"string","description":"Color for the group in the flow editor, one of: yellow, blue, green, purple, pink, orange, red, cyan, lime, gray. Omit it to let the editor pick one."}},"required":["start_id","end_id"]},"RetryIf":{"type":"object","description":"Conditional retry based on error or result","properties":{"expr":{"type":"string","description":"JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables"}},"required":["expr"]},"StopAfterIf":{"type":"object","description":"Early termination condition for a module","properties":{"skip_if_stopped":{"type":"boolean","description":"If true, following steps are skipped when this condition triggers"},"expr":{"type":"string","description":"JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"},"error_message":{"type":"string","nullable":true,"description":"Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised."},"error_include_result":{"type":"boolean","description":"When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false."}},"required":["expr"]},"FlowModule":{"type":"object","description":"A single step in a flow. Can be a script, subflow, loop, or branch","properties":{"id":{"type":"string","description":"Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"},"value":{"$ref":"#/components/schemas/FlowModuleValue"},"stop_after_if":{"description":"Early termination condition evaluated after this step completes","$ref":"#/components/schemas/StopAfterIf"},"stop_after_all_iters_if":{"description":"For loops only - early termination condition evaluated after all iterations complete","$ref":"#/components/schemas/StopAfterIf"},"skip_if":{"type":"object","description":"Conditionally skip this step based on previous results or flow inputs","properties":{"expr":{"type":"string","description":"JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.'"}},"required":["expr"]},"sleep":{"description":"Delay before executing this step (in seconds or as expression)","$ref":"#/components/schemas/InputTransform"},"cache_ttl":{"type":"number","description":"Cache duration in seconds for this step's results"},"cache_ignore_s3_path":{"type":"boolean"},"timeout":{"description":"Maximum execution time in seconds (static value or expression)","$ref":"#/components/schemas/InputTransform"},"delete_after_secs":{"type":"integer","description":"If set, delete the step's args, result and logs after this many seconds following job completion"},"summary":{"type":"string","description":"Short description of what this step does"},"mock":{"type":"object","description":"Mock configuration for testing without executing the actual step","properties":{"enabled":{"type":"boolean","description":"If true, return mock value instead of executing"},"return_value":{"description":"Value to return when mocked"}}},"suspend":{"type":"object","description":"Configuration for approval/resume steps that wait for user input","properties":{"required_events":{"type":"integer","description":"Number of approvals required before continuing"},"timeout":{"type":"integer","description":"Timeout in seconds before auto-continuing or canceling"},"resume_form":{"type":"object","description":"Form schema for collecting input when resuming","properties":{"schema":{"type":"object","description":"JSON Schema for the resume form"}}},"user_auth_required":{"type":"boolean","description":"If true, only authenticated users can approve"},"user_groups_required":{"description":"Expression or list of groups that can approve","$ref":"#/components/schemas/InputTransform"},"self_approval_disabled":{"type":"boolean","description":"If true, the user who started the flow cannot approve"},"hide_cancel":{"type":"boolean","description":"If true, hide the cancel button on the approval form"},"continue_on_disapprove_timeout":{"type":"boolean","description":"If true, continue flow on timeout instead of canceling"},"skin":{"type":"string","enum":["detailed","minimal"],"description":"How the approval request is presented, on the approval page and in Slack/Teams approval messages. 'detailed' (used when unset) shows the flow details (arguments, graph, approvers); 'minimal' shows only the request: the step description, form and approve/reject actions"}}},"priority":{"type":"number","description":"Execution priority for this step (higher numbers run first)"},"continue_on_error":{"type":"boolean","description":"If true, flow continues even if this step fails"},"job_token_scopes":{"type":"array","nullable":true,"items":{"type":"string"},"description":"Scopes the token of this step's jobs is restricted to (domain:action[:resource], e.g. oidc:write), on top of the flow's own restriction: a step can only narrow it. Applies to everything the step runs (loop and branch bodies, AI agent tools)."},"retry":{"description":"Retry configuration if this step fails","$ref":"#/components/schemas/Retry"},"debouncing":{"description":"Debounce configuration for this step (EE only)","type":"object","properties":{"debounce_delay_s":{"type":"integer","description":"Delay in seconds to debounce this step's executions across flow runs"},"debounce_key":{"type":"string","description":"Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/-"},"debounce_args_to_accumulate":{"type":"array","description":"Array-type arguments to accumulate across debounced executions","items":{"type":"string"}},"max_total_debouncing_time":{"type":"integer","description":"Maximum total time in seconds before forced execution"},"max_total_debounces_amount":{"type":"integer","description":"Maximum number of debounces before forced execution"}}}},"required":["value","id"]},"InputTransform":{"description":"Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs","oneOf":[{"$ref":"#/components/schemas/StaticTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type","mapping":{"static":"#/components/schemas/StaticTransform","javascript":"#/components/schemas/JavascriptTransform","ai":"#/components/schemas/AiTransform"}}},"StaticTransform":{"type":"object","description":"Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'","properties":{"value":{"description":"The static value. For resources, use format '$res:path/to/resource'"},"type":{"type":"string","enum":["static"]}},"required":["type"]},"JavascriptTransform":{"type":"object","description":"JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')","properties":{"expr":{"type":"string","description":"JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"},"type":{"type":"string","enum":["javascript"]}},"required":["expr","type"]},"AiTransform":{"type":"object","description":"Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.","properties":{"type":{"type":"string","enum":["ai"]}},"required":["type"]},"AIProviderKind":{"type":"string","description":"Supported AI provider types","enum":["openai","azure_openai","azure_foundry","anthropic","mistral","deepseek","googleai","groq","openrouter","togetherai","customai","aws_bedrock","typesafe","cloudflare"]},"ProviderConfig":{"type":"object","description":"Complete AI provider configuration with resource reference and model selection","properties":{"kind":{"$ref":"#/components/schemas/AIProviderKind"},"resource":{"type":"string","description":"Resource reference in format '$res:{resource_path}' pointing to provider credentials"},"model":{"type":"string","description":"Model identifier (e.g., 'gpt-4', 'claude-3-opus-20240229', 'gemini-pro')"},"reasoning_effort":{"type":"string","description":"Provider-native reasoning effort token (e.g. 'low', 'high', 'none') for models that support extended thinking. Optional; unset leaves the provider default."}},"required":["kind","resource","model"]},"StaticProviderTransform":{"type":"object","description":"Static provider configuration passed directly to the AI agent","properties":{"value":{"$ref":"#/components/schemas/ProviderConfig"},"type":{"type":"string","enum":["static"]}},"required":["type","value"]},"ProviderTransform":{"description":"Provider configuration - can be static (ProviderConfig), JavaScript expression, or AI-determined","oneOf":[{"$ref":"#/components/schemas/StaticProviderTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type","mapping":{"static":"#/components/schemas/StaticProviderTransform","javascript":"#/components/schemas/JavascriptTransform","ai":"#/components/schemas/AiTransform"}}},"MemoryOff":{"type":"object","description":"No conversation memory/context","properties":{"kind":{"type":"string","enum":["off"]}},"required":["kind"]},"MemoryWindow":{"type":"object","description":"Keeps the most recent messages of the memory named by the run's memory id (or the step's\\n\`memory_id\`). Without a memory id the agent runs without memory.\\n","properties":{"kind":{"type":"string","enum":["window"]},"context_length":{"type":"integer","description":"Number of most recent messages to load and store. 0 turns memory off."}},"required":["kind","context_length"]},"MemoryAuto":{"type":"object","deprecated":true,"description":"Deprecated, still read as it was written: the run's memory id, else the \`memory_id\` here.\\nThe step's own \`memory_id\` is not read while this kind is set; switch the kind to \`window\`\\nto use it. Without a \`context_length\`, or with 0, it is \`off\` and reads \`previous_messages\`.\\n","properties":{"kind":{"type":"string","enum":["auto"]},"context_length":{"type":"integer","description":"Maximum number of messages to retain in context"},"memory_id":{"type":"string","description":"Identifier for persistent memory across agent invocations"}},"required":["kind"]},"MemoryCompaction":{"type":"object","description":"Keeps the whole memory named by the run's memory id (or the step's \`memory_id\`), replacing\\nits older part with a summary as the conversation approaches the model's context window.\\nWithout a memory id the agent runs without memory, and compaction bounds the run's own loop.\\n","properties":{"kind":{"type":"string","enum":["compaction"]},"context_window":{"type":"integer","description":"Overrides the context window looked up from the model, in tokens. Only a model\\nWindmill does not know needs one; those fall back to 128000.\\n"}},"required":["kind"]},"MemoryMessage":{"type":"object","description":"A single message in conversation history","properties":{"role":{"type":"string","enum":["user","assistant","system"]},"content":{"type":"string"}},"required":["role","content"]},"MemoryManual":{"type":"object","deprecated":true,"description":"Deprecated, still read as it was written. Move the step to \`off\` with \`previous_messages\` instead.","properties":{"kind":{"type":"string","enum":["manual"]},"messages":{"type":"array","items":{"$ref":"#/components/schemas/MemoryMessage"}}},"required":["kind","messages"]},"MemoryConfig":{"description":"Managed memory, stored by Windmill and replayed with each request. The memory is named by a memory id, see \`memory_id\`. While it is off, a step can supply its history in \`previous_messages\`.","oneOf":[{"$ref":"#/components/schemas/MemoryOff"},{"$ref":"#/components/schemas/MemoryWindow"},{"$ref":"#/components/schemas/MemoryCompaction"},{"$ref":"#/components/schemas/MemoryAuto"},{"$ref":"#/components/schemas/MemoryManual"}],"discriminator":{"propertyName":"kind","mapping":{"off":"#/components/schemas/MemoryOff","window":"#/components/schemas/MemoryWindow","compaction":"#/components/schemas/MemoryCompaction","auto":"#/components/schemas/MemoryAuto","manual":"#/components/schemas/MemoryManual"}}},"StaticMemoryTransform":{"type":"object","description":"Static memory configuration passed directly to the AI agent","properties":{"value":{"$ref":"#/components/schemas/MemoryConfig"},"type":{"type":"string","enum":["static"]}},"required":["type","value"]},"MemoryTransform":{"description":"Memory configuration - can be static (MemoryConfig), JavaScript expression, or AI-determined","oneOf":[{"$ref":"#/components/schemas/StaticMemoryTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type","mapping":{"static":"#/components/schemas/StaticMemoryTransform","javascript":"#/components/schemas/JavascriptTransform","ai":"#/components/schemas/AiTransform"}}},"FlowModuleValue":{"description":"The actual implementation of a flow step. Can be a script (inline or referenced), subflow, loop, branch, or special module type","oneOf":[{"$ref":"#/components/schemas/RawScript"},{"$ref":"#/components/schemas/PathScript"},{"$ref":"#/components/schemas/PathFlow"},{"$ref":"#/components/schemas/ForloopFlow"},{"$ref":"#/components/schemas/WhileloopFlow"},{"$ref":"#/components/schemas/BranchOne"},{"$ref":"#/components/schemas/BranchAll"},{"$ref":"#/components/schemas/Identity"},{"$ref":"#/components/schemas/AiAgent"},{"$ref":"#/components/schemas/AiDecision"}],"discriminator":{"propertyName":"type","mapping":{"rawscript":"#/components/schemas/RawScript","script":"#/components/schemas/PathScript","flow":"#/components/schemas/PathFlow","forloopflow":"#/components/schemas/ForloopFlow","whileloopflow":"#/components/schemas/WhileloopFlow","branchone":"#/components/schemas/BranchOne","branchall":"#/components/schemas/BranchAll","identity":"#/components/schemas/Identity","aiagent":"#/components/schemas/AiAgent","aidecision":"#/components/schemas/AiDecision"}}},"RawScript":{"type":"object","description":"Inline script with code defined directly in the flow. Use 'bun' as default language if unspecified. The script receives arguments from input_transforms","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"content":{"type":"string","description":"The script source code. Should export a 'main' function"},"language":{"type":"string","description":"Programming language for this script","enum":["deno","bun","bunnative","python3","go","bash","powershell","postgresql","mysql","bigquery","snowflake","mssql","oracledb","graphql","nativets","php","rust","ansible","csharp","nu","java","ruby","rlang","duckdb"]},"path":{"type":"string","description":"Optional path for saving this script"},"lock":{"type":"string","description":"Lock file content for dependencies"},"type":{"type":"string","enum":["rawscript"]},"tag":{"type":"string","description":"Worker group tag for execution routing"},"concurrent_limit":{"type":"number","description":"Maximum concurrent executions of this script"},"concurrency_time_window_s":{"type":"number","description":"Time window for concurrent_limit"},"custom_concurrency_key":{"type":"string","description":"Custom key for grouping concurrent executions"},"is_trigger":{"type":"boolean","description":"If true, this script is a trigger that can start the flow"},"assets":{"type":"array","description":"External resources this script accesses (S3 objects, resources, etc.)","items":{"type":"object","required":["path","kind"],"properties":{"path":{"type":"string","description":"Path to the asset"},"kind":{"type":"string","description":"Type of asset","enum":["s3object","resource","ducklake","datatable","volume","dbt"]},"access_type":{"type":"string","nullable":true,"description":"Access level for this asset","enum":["r","w","rw"]},"alt_access_type":{"type":"string","nullable":true,"description":"Alternative access level","enum":["r","w","rw"]}}}}},"required":["type","content","language","input_transforms"]},"PathScript":{"type":"object","description":"Reference to an existing script by path. Use this when calling a previously saved script instead of writing inline code","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"path":{"type":"string","description":"Path to the script in the workspace (e.g., 'f/scripts/send_email')"},"hash":{"type":"string","description":"Optional specific version hash of the script to use"},"type":{"type":"string","enum":["script"]},"tag_override":{"type":"string","description":"Override the script's default worker group tag"},"is_trigger":{"type":"boolean","description":"If true, this script is a trigger that can start the flow"}},"required":["type","path","input_transforms"]},"PathFlow":{"type":"object","description":"Reference to an existing flow by path. Use this to call another flow as a subflow","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the subflow's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"path":{"type":"string","description":"Path to the flow in the workspace (e.g., 'f/flows/process_user')"},"type":{"type":"string","enum":["flow"]}},"required":["type","path","input_transforms"]},"ForloopFlow":{"type":"object","description":"Executes nested modules in a loop over an iterator. Inside the loop, use 'flow_input.iter.value' to access the current iteration value, and 'flow_input.iter.index' for the index. Supports parallel execution for better performance on I/O-bound operations","properties":{"modules":{"type":"array","description":"Steps to execute for each iteration. These can reference the iteration value via 'flow_input.iter.value'","items":{"$ref":"#/components/schemas/FlowModule"}},"iterator":{"description":"JavaScript expression that returns an array to iterate over. Can reference 'results.step_id' or 'flow_input'","$ref":"#/components/schemas/InputTransform"},"skip_failures":{"type":"boolean","description":"If true, iteration failures don't stop the loop. Failed iterations return null"},"type":{"type":"string","enum":["forloopflow"]},"parallel":{"type":"boolean","description":"If true, iterations run concurrently (faster for I/O-bound operations). Use with parallelism to control concurrency"},"parallelism":{"description":"Maximum number of concurrent iterations when parallel=true. Limits resource usage. Can be static number or expression","$ref":"#/components/schemas/InputTransform"},"squash":{"type":"boolean"}},"required":["modules","iterator","skip_failures","type"]},"WhileloopFlow":{"type":"object","description":"Executes nested modules repeatedly until stopped. The implicit iterator is the iteration counter, so 'flow_input.iter.value' equals 'flow_input.iter.index' (0, 1, 2, ...) and never carries state. To carry state across iterations, a step reads its own previous-iteration result via 'results.' with a first-iteration fallback - the loop's stop_after_if must then be on that inner step (a plain single-step body with stop_after_if on the loop module does not resolve 'results' across iterations and never terminates); plain counters can instead be derived from 'flow_input.iter.index', which works in every configuration. stop_after_if is evaluated after each iteration - on the loop module 'result' is the last iteration's result","properties":{"modules":{"type":"array","description":"Steps to execute in each iteration","items":{"$ref":"#/components/schemas/FlowModule"}},"skip_failures":{"type":"boolean","description":"If true, iteration failures don't stop the loop. Failed iterations return null"},"type":{"type":"string","enum":["whileloopflow"]},"parallel":{"type":"boolean","description":"If true, iterations run concurrently (use with caution in while loops)"},"parallelism":{"description":"Maximum number of concurrent iterations when parallel=true","$ref":"#/components/schemas/InputTransform"},"squash":{"type":"boolean"}},"required":["modules","skip_failures","type"]},"BranchOne":{"type":"object","description":"Conditional branching where only the first matching branch executes. Branches are evaluated in order, and the first one with a true expression runs. If no branches match, the default branch executes","properties":{"branches":{"type":"array","description":"Array of branches to evaluate in order. The first branch with expr evaluating to true executes","items":{"type":"object","properties":{"summary":{"type":"string","description":"Short description of this branch condition"},"expr":{"type":"string","description":"JavaScript expression that returns boolean. Can use 'results.step_id' or 'flow_input'. First true expr wins"},"modules":{"type":"array","description":"Steps to execute if this branch's expr is true","items":{"$ref":"#/components/schemas/FlowModule"}}},"required":["modules","expr"]}},"default":{"type":"array","description":"Steps to execute if no branch expressions match","items":{"$ref":"#/components/schemas/FlowModule"}},"type":{"type":"string","enum":["branchone"]}},"required":["branches","default","type"]},"BranchAll":{"type":"object","description":"Parallel branching where all branches execute simultaneously. Unlike BranchOne, all branches run regardless of conditions. Useful for executing independent tasks concurrently","properties":{"branches":{"type":"array","description":"Array of branches that all execute (either in parallel or sequentially)","items":{"type":"object","properties":{"summary":{"type":"string","description":"Short description of this branch's purpose"},"skip_failure":{"type":"boolean","description":"If true, failure in this branch doesn't fail the entire flow"},"modules":{"type":"array","description":"Steps to execute in this branch","items":{"$ref":"#/components/schemas/FlowModule"}}},"required":["modules"]}},"type":{"type":"string","enum":["branchall"]},"parallel":{"type":"boolean","description":"If true, all branches execute concurrently. If false, they execute sequentially"}},"required":["branches","type"]},"AgentTool":{"type":"object","description":"A tool available to an AI agent. Can be a flow module or an external MCP (Model Context Protocol) tool","properties":{"id":{"type":"string","description":"Unique identifier for this tool. Cannot contain spaces - use underscores instead (e.g., 'get_user_data' not 'get user data')"},"summary":{"type":"string","description":"The name the AI agent calls this tool by, not a human label. On a flowmodule tool it must match ^[a-zA-Z0-9_]+$ - letters, numbers and underscores only (e.g. 'search_documentation', not 'Search documentation') - and always be set; on an mcp or websearch tool it is a plain label. Put the human-readable explanation in 'description'."},"description":{"type":"string","description":"Free-text description of the tool given to the AI to decide when and how to call it. Overrides the description auto-derived from the underlying script."},"job_token_scopes":{"type":"array","nullable":true,"items":{"type":"string"},"description":"Scopes the token of this tool's jobs is restricted to, on top of the agent step's own restriction: a tool can only narrow it."},"value":{"$ref":"#/components/schemas/ToolValue"}},"required":["id","value"]},"ToolValue":{"description":"The implementation of a tool. Can be a flow module (script/flow) or an MCP tool reference","oneOf":[{"$ref":"#/components/schemas/FlowModuleTool"},{"$ref":"#/components/schemas/McpToolValue"},{"$ref":"#/components/schemas/WebsearchToolValue"}],"discriminator":{"propertyName":"tool_type","mapping":{"flowmodule":"#/components/schemas/FlowModuleTool","mcp":"#/components/schemas/McpToolValue","websearch":"#/components/schemas/WebsearchToolValue"}}},"FlowModuleTool":{"description":"A tool implemented as a flow module (script, flow, etc.). The AI can call this like any other flow module","allOf":[{"type":"object","properties":{"tool_type":{"type":"string","enum":["flowmodule"]}},"required":["tool_type"]},{"$ref":"#/components/schemas/FlowModuleValue"}]},"WebsearchToolValue":{"type":"object","description":"A tool implemented as a websearch tool. The AI can call this like any other websearch tool","properties":{"tool_type":{"type":"string","enum":["websearch"]}},"required":["tool_type"]},"McpToolValue":{"type":"object","description":"Reference to an external MCP (Model Context Protocol) tool. The AI can call tools from MCP servers","properties":{"tool_type":{"type":"string","enum":["mcp"]},"resource_path":{"type":"string","description":"Path to the MCP resource/server configuration"},"include_tools":{"type":"array","description":"Whitelist of specific tools to include from this MCP server","items":{"type":"string"}},"exclude_tools":{"type":"array","description":"Blacklist of tools to exclude from this MCP server","items":{"type":"string"}}},"required":["tool_type","resource_path"]},"AiAgent":{"type":"object","description":"AI agent step that can use tools to accomplish tasks. The agent receives inputs and can call any of its configured tools to complete the task","properties":{"input_transforms":{"type":"object","description":"Input parameters for the AI agent mapped to their values","properties":{"provider":{"$ref":"#/components/schemas/ProviderTransform"},"output_type":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Output format type.\\nValid values: 'text' (default) - plain text response, 'image' - image generation\\n"},"user_message":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"The user's prompt/message to the AI agent. Supports variable interpolation with\\nflow.input syntax. Required unless memory is off and \`previous_messages\` supplies\\nthe prompt; image output always needs it.\\n"},"system_prompt":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"System instructions that guide the AI's behavior, persona, and response style. Optional."},"streaming":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Boolean. If true, stream the AI response incrementally.\\nStreaming events include: token_delta, reasoning_token_delta, tool_call, tool_call_arguments, tool_execution, tool_result\\n"},"memory":{"$ref":"#/components/schemas/MemoryTransform"},"memory_id":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"String. Names the memory this step reads and writes, overriding the memory id the run\\nwas started with (the chat conversation, an app chat session or the \`memory_id\` run\\nparameter). Leave unset to use the run's memory id. A fixed value shares one memory\\nacross every run; an expression such as \`flow_input.customer_id\` keeps one memory per\\nkey. When it evaluates to an empty value the agent runs without memory. Read only\\nwhile \`memory\` is \`window\` or \`compaction\`: it is ignored when memory is off, and an\\nolder \`auto\` or \`manual\` memory reads neither history input.\\n"},"previous_messages":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Array of MemoryMessage. History supplied by the flow, sent between the system prompt\\nand the user message. Read only while \`memory\` is off or absent: managed memory\\nignores it, and an older \`auto\` or \`manual\` memory reads neither history input.\\n"},"output_schema":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"JSON Schema object defining structured output format. Used when you need the AI to return data in a specific shape.\\nSupports standard JSON Schema properties: type, properties, required, items, enum, pattern, minLength, maxLength, minimum, maximum, etc.\\nExample: { type: 'object', properties: { name: { type: 'string' }, age: { type: 'integer' } }, required: ['name'] }\\n"},"user_attachments":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Array of file references (images or PDFs) for the AI agent.\\nFormat: Array<{ bucket: string, key: string }> - S3 object references\\nExample: [{ bucket: 'my-bucket', key: 'documents/report.pdf' }]\\n"},"enabled_tools":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Array of strings naming which of the tools configured in \`tools\` the agent may call\\nthis run. Leaving it unset carries every one of them; an empty array carries none.\\nA tool is named as the model is shown it. An entry the model is shown nothing of is\\nnamed by what identifies it instead: an MCP server by its resource path, carrying\\nevery tool it exposes (which of them stays that entry's include_tools/exclude_tools),\\nand a websearch entry by the reserved name '__wm_web_search', whatever summary it carries\\n(no tool may take that name).\\nExample: ['get_user', 'u/admin/github_mcp', '__wm_web_search']\\n"},"max_completion_tokens":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Integer. Maximum number of tokens the AI will generate in its response.\\nRange: 1 to 4,294,967,295. Typical values: 256-4096 for most use cases.\\n"},"temperature":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Float. Controls randomness/creativity of responses.\\nRange: 0.0 to 2.0 (provider-dependent)\\n- 0.0 = deterministic, focused responses\\n- 0.7 = balanced (common default)\\n- 1.0+ = more creative/random\\n"},"max_iterations":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Number. Limits how many times the agent can loop through reasoning and tool use.\\nRange: 1-1000.\\n"}}},"tools":{"type":"array","description":"Array of tools the agent can use. The agent decides which tools to call based on the task","items":{"$ref":"#/components/schemas/AgentTool"}},"type":{"type":"string","enum":["aiagent"]},"tag":{"type":"string","description":"Worker group tag for execution routing. If not set, the AI agent step runs on the flow's tag (default \`flow\`)"},"omit_output_from_conversation":{"type":"boolean","default":false,"description":"If true, this AI agent step does not persist its assistant or tool messages to the flow conversation when chat mode is enabled."},"agent":{"type":"string","description":"Path of a reusable \`ai_agent\` resource (hybrid linking). When set, the agent brain\\nconfig (provider/model/system prompt/etc.) and tool set are resolved at runtime from\\nthat resource; the module's input_transforms then only carry the flow-local inputs\\n(user_message, user_attachments, enabled_tools and the history inputs memory_id and previous_messages).\\n"},"tool_inputs":{"type":"object","description":"Host-local wiring for an agent's tool inputs, keyed by tool id then input key. Binds the\\nreferenced agent's tools to this flow's context (flow_input/results) without mutating the\\nshared resource; overlaid onto the tools' input_transforms at runtime \\u2014 including when\\n\`agent\` is unset, since a step forked for editing keeps these overrides until it is saved\\nback or unlinked.\\n","additionalProperties":{"type":"object","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}}},"parallel":{"type":"boolean","description":"If true, the agent can execute multiple tool calls in parallel"}},"required":["type","input_transforms"]},"AiDecision":{"type":"object","description":"AI decision step: one call to a decision model (TypeSafe's Jev, Cloudflare's\\nJev-compatible Clef, or OpenAI's Decisions API) that answers typed questions about a\\nstate with calibrated probabilities, instead of generating text.\\nPrefer it over an AI agent to classify, route, score or check something: it is fast,\\ncheap and its answers are structured. Its result is { output: { : answer },\\nmodel, usage }, so a later step reads e.g. results..output.intent.choice. To route on\\nthe answers, follow it with a branchone whose branch exprs read\\nresults..output..choice. Usable as an AI agent tool, where the calling agent\\nsupplies the state.\\n","properties":{"input_transforms":{"type":"object","description":"Input parameters for the decision mapped to their values","properties":{"provider":{"$ref":"#/components/schemas/ProviderTransform"},"state":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"What the questions are asked about: a string, an object or an array of strings.\\nAn object with descriptive keys holding only what the questions need works best.\\nExample: { message: flow_input.message, plan: results.a.plan }\\n"},"questions":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Object mapping each question name to { type, instructions, criteria }, where type is:\\n- 'choice': criteria maps each option to its description (up to 255); the answer\\n has choice, probabilities and confidence\\n- 'score': criteria is an ordered array of 2 to 10 level descriptions; the answer\\n has score, legend, probabilities and confidence\\n- 'noul': yes/no, criteria optionally { true, false } descriptions; the answer has\\n noul, the probability of yes (0 to 1)\\nExample: { intent: { type: 'choice', instructions: 'What does the customer want?',\\ncriteria: { refund: 'Money back', bug: 'Something is broken' } } }\\n"}},"required":["provider","state","questions"]},"type":{"type":"string","enum":["aidecision"]},"tag":{"type":"string","description":"Worker group tag for execution routing. If not set, the step runs on the flow's tag (default \`flow\`)"}},"required":["type","input_transforms"]},"Identity":{"type":"object","description":"Pass-through module that returns its input unchanged. Useful for flow structure or as a placeholder","properties":{"type":{"type":"string","enum":["identity"]},"flow":{"type":"boolean","description":"If true, marks this as a flow identity (special handling)"}},"required":["type"]},"FlowStatus":{"type":"object","properties":{"step":{"type":"integer"},"modules":{"type":"array","items":{"$ref":"#/components/schemas/FlowStatusModule"}},"user_states":{"additionalProperties":true},"preprocessor_module":{"allOf":[{"$ref":"#/components/schemas/FlowStatusModule"}]},"failure_module":{"allOf":[{"$ref":"#/components/schemas/FlowStatusModule"},{"type":"object","properties":{"parent_module":{"type":"string"}}}]},"retry":{"type":"object","properties":{"fail_count":{"type":"integer"},"failed_jobs":{"type":"array","items":{"type":"string","format":"uuid"}}}}},"required":["step","modules","failure_module"]},"FlowStatusModule":{"type":"object","properties":{"type":{"type":"string","enum":["WaitingForPriorSteps","WaitingForEvents","WaitingForExecutor","InProgress","Success","Failure"]},"id":{"type":"string"},"job":{"type":"string","format":"uuid"},"count":{"type":"integer"},"progress":{"type":"integer"},"iterator":{"type":"object","properties":{"index":{"type":"integer"},"itered":{"type":"array","items":{}},"itered_len":{"type":"integer"},"args":{}}},"flow_jobs":{"type":"array","items":{"type":"string"}},"flow_jobs_success":{"type":"array","items":{"type":"boolean"}},"flow_jobs_duration":{"type":"object","properties":{"started_at":{"type":"array","items":{"type":"string"}},"duration_ms":{"type":"array","items":{"type":"integer"}}}},"branch_chosen":{"type":"object","properties":{"type":{"type":"string","enum":["branch","default"]},"branch":{"type":"integer"}},"required":["type"]},"branchall":{"type":"object","properties":{"branch":{"type":"integer"},"len":{"type":"integer"}},"required":["branch","len"]},"approvers":{"type":"array","items":{"type":"object","properties":{"resume_id":{"type":"integer"},"approver":{"type":"string"}},"required":["resume_id","approver"]}},"failed_retries":{"type":"array","items":{"type":"string","format":"uuid"}},"skipped":{"type":"boolean"},"agent_actions":{"type":"array","items":{"type":"object","oneOf":[{"type":"object","properties":{"job_id":{"type":"string","format":"uuid"},"function_name":{"type":"string"},"type":{"type":"string","enum":["tool_call"]},"module_id":{"type":"string"}},"required":["job_id","function_name","type","module_id"]},{"type":"object","properties":{"call_id":{"type":"string","format":"uuid"},"function_name":{"type":"string"},"resource_path":{"type":"string"},"type":{"type":"string","enum":["mcp_tool_call"]},"arguments":{"type":"object"}},"required":["call_id","function_name","resource_path","type"]},{"type":"object","properties":{"type":{"type":"string","enum":["web_search"]}},"required":["type"]},{"type":"object","properties":{"type":{"type":"string","enum":["message"]}},"required":["content","type"]}]}},"agent_actions_success":{"type":"array","items":{"type":"boolean"}}},"required":["type"]}} +{"OpenFlow":{"type":"object","description":"Top-level flow definition containing metadata, configuration, and the flow structure","properties":{"summary":{"type":"string","description":"Short description of what this flow does"},"description":{"type":"string","description":"Detailed documentation for this flow"},"value":{"$ref":"#/components/schemas/FlowValue"},"schema":{"type":"object","description":"JSON Schema for flow inputs. Use this to define input parameters, their types, defaults, and validation. For resource inputs, set type to 'object' and format to 'resource-' (e.g., 'resource-stripe')"},"on_behalf_of_email":{"type":"string","description":"Address of the account the flow runs on behalf of. Derived from on_behalf_of on read; accepted on write, where it is resolved to the account it names."},"on_behalf_of":{"type":"string","description":"The flow runs with the permissions of this identity: u/{username}, g/{group}, or a bare email when the username is itself email-shaped. The only stored half of the identity; on_behalf_of_email is derived from it. Omit it when writing and it is resolved from that address instead."}},"required":["summary","value"]},"FlowValue":{"type":"object","description":"The flow structure containing modules and optional preprocessor/failure handlers","properties":{"modules":{"type":"array","description":"Array of steps that execute in sequence. Each step can be a script, subflow, loop, or branch","items":{"$ref":"#/components/schemas/FlowModule"}},"failure_module":{"description":"Special module that executes when the flow fails. Receives error object with message, name, stack, and step_id. Must have id 'failure'. Only supports script/rawscript types","$ref":"#/components/schemas/FlowModule"},"preprocessor_module":{"description":"Special module that runs before the first step on external triggers. Must have id 'preprocessor'. Only supports script/rawscript types. Cannot reference other step results","$ref":"#/components/schemas/FlowModule"},"same_worker":{"type":"boolean","description":"If true, all steps run on the same worker for better performance"},"preserve_step_tags":{"type":"boolean","description":"If true and the flow runs on a custom worker tag, steps that declare their own non-empty tag run on it instead of inheriting the flow tag. Steps without their own tag still inherit the flow tag."},"concurrent_limit":{"type":"number","description":"Maximum number of concurrent executions of this flow"},"concurrency_key":{"type":"string","description":"Expression to group concurrent executions (e.g., by user ID)"},"concurrency_time_window_s":{"type":"number","description":"Time window in seconds for concurrent_limit"},"debounce_delay_s":{"type":"integer","description":"Delay in seconds to debounce flow executions"},"debounce_key":{"type":"string","description":"Expression to group debounced executions"},"debounce_args_to_accumulate":{"type":"array","description":"Arguments to accumulate across debounced executions","items":{"type":"string"}},"max_total_debouncing_time":{"type":"integer","description":"Maximum total time in seconds that a job can be debounced"},"max_total_debounces_amount":{"type":"integer","description":"Maximum number of times a job can be debounced"},"skip_expr":{"type":"string","description":"JavaScript expression to conditionally skip the entire flow"},"cache_ttl":{"type":"number","description":"Cache duration in seconds for flow results"},"cache_ignore_s3_path":{"type":"boolean"},"delete_after_secs":{"type":"integer","description":"If set, delete the flow job's args, result and logs after this many seconds following job completion"},"flow_env":{"type":"object","description":"Environment variables available to all steps. Values can be strings, JSON values, or special references: '$var:path' (workspace variable) or '$res:path' (resource).","additionalProperties":{}},"priority":{"type":"number","description":"Execution priority (higher numbers run first)"},"early_return":{"type":"string","description":"Id of the step whose result a sync webhook returns as soon as that step completes, while the rest of the flow keeps running. When the step does not run, or fails while the flow has a failure module, the flow's final result is returned instead."},"chat_input_enabled":{"type":"boolean","description":"Whether this flow accepts chat-style input"},"notes":{"type":"array","description":"Sticky notes attached to the flow","items":{"$ref":"#/components/schemas/FlowNote"}},"groups":{"type":"array","description":"Semantic groups of modules for organizational purposes","items":{"$ref":"#/components/schemas/FlowGroup"}}},"required":["modules"]},"Retry":{"type":"object","description":"Retry configuration for failed module executions","properties":{"constant":{"type":"object","description":"Retry with constant delay between attempts","properties":{"attempts":{"type":"integer","description":"Number of retry attempts"},"seconds":{"type":"integer","description":"Seconds to wait between retries"}}},"exponential":{"type":"object","description":"Retry with exponential backoff: the n-th retry waits multiplier \\u00d7 seconds^n","properties":{"attempts":{"type":"integer","description":"Number of retry attempts"},"multiplier":{"type":"integer","description":"Multiplier for exponential backoff"},"seconds":{"type":"integer","minimum":1,"description":"Base of the exponential (seconds); the n-th retry waits multiplier \\u00d7 seconds^n, where n counts constant retries too"},"random_factor":{"type":"integer","minimum":0,"maximum":100,"description":"Random jitter percentage (0-100) to avoid thundering herd"}}},"retry_if":{"$ref":"#/components/schemas/RetryIf"}}},"FlowNote":{"type":"object","description":"A sticky note attached to a flow for documentation and annotation","properties":{"id":{"type":"string","description":"Unique identifier for the note"},"text":{"type":"string","description":"Content of the note"},"position":{"type":"object","description":"Position of the note in the flow editor","properties":{"x":{"type":"number","description":"X coordinate"},"y":{"type":"number","description":"Y coordinate"}},"required":["x","y"]},"size":{"type":"object","description":"Size of the note in the flow editor","properties":{"width":{"type":"number","description":"Width in pixels"},"height":{"type":"number","description":"Height in pixels"}},"required":["width","height"]},"color":{"type":"string","description":"Color of the note, one of: yellow, blue, green, purple, pink, orange, red, cyan, lime, gray. Any other value renders unstyled."},"type":{"type":"string","enum":["free","group"],"description":"Type of note - 'free' for standalone notes. 'group' notes are deprecated; segment a flow with FlowValue.groups instead."},"locked":{"type":"boolean","default":false,"description":"Whether the note is locked and cannot be edited or moved"},"contained_node_ids":{"type":"array","items":{"type":"string"},"description":"For group notes, the IDs of nodes contained within this group"}},"required":["id","text","color","type"]},"FlowGroup":{"type":"object","description":"A semantic group of flow modules for organizational purposes. Does not affect execution \\u2014 modules remain in their original position in the flow. Groups provide naming and collapsibility in the editor. Members are computed dynamically from all nodes on paths between start_id and end_id.","properties":{"summary":{"type":"string","description":"Display name for this group"},"note":{"type":"string","description":"Markdown note shown below the group header"},"autocollapse":{"type":"boolean","default":false,"description":"If true, this group is collapsed by default in the flow editor. UI hint only."},"start_id":{"type":"string","description":"ID of the first flow module in this group (topological entry point)"},"end_id":{"type":"string","description":"ID of the last flow module in this group (topological exit point)"},"color":{"type":"string","description":"Color for the group in the flow editor, one of: yellow, blue, green, purple, pink, orange, red, cyan, lime, gray. Omit it to let the editor pick one."}},"required":["start_id","end_id"]},"RetryIf":{"type":"object","description":"Conditional retry based on error or result","properties":{"expr":{"type":"string","description":"JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables"}},"required":["expr"]},"StopAfterIf":{"type":"object","description":"Early termination condition for a module","properties":{"skip_if_stopped":{"type":"boolean","description":"If true, following steps are skipped when this condition triggers"},"expr":{"type":"string","description":"JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"},"error_message":{"type":"string","nullable":true,"description":"Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised."},"error_include_result":{"type":"boolean","description":"When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false."}},"required":["expr"]},"FlowModule":{"type":"object","description":"A single step in a flow. Can be a script, subflow, loop, or branch","properties":{"id":{"type":"string","description":"Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"},"value":{"$ref":"#/components/schemas/FlowModuleValue"},"stop_after_if":{"description":"Early termination condition evaluated after this step completes","$ref":"#/components/schemas/StopAfterIf"},"stop_after_all_iters_if":{"description":"For loops only - early termination condition evaluated after all iterations complete","$ref":"#/components/schemas/StopAfterIf"},"skip_if":{"type":"object","description":"Conditionally skip this step based on previous results or flow inputs","properties":{"expr":{"type":"string","description":"JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.'"}},"required":["expr"]},"sleep":{"description":"Delay before executing this step (in seconds or as expression)","$ref":"#/components/schemas/InputTransform"},"cache_ttl":{"type":"number","description":"Cache duration in seconds for this step's results"},"cache_ignore_s3_path":{"type":"boolean"},"timeout":{"description":"Maximum execution time in seconds (static value or expression)","$ref":"#/components/schemas/InputTransform"},"delete_after_secs":{"type":"integer","description":"If set, delete the step's args, result and logs after this many seconds following job completion"},"summary":{"type":"string","description":"Short description of what this step does"},"mock":{"type":"object","description":"Mock configuration for testing without executing the actual step","properties":{"enabled":{"type":"boolean","description":"If true, return mock value instead of executing"},"return_value":{"description":"Value to return when mocked"}}},"suspend":{"type":"object","description":"Configuration for approval/resume steps that wait for user input","properties":{"required_events":{"type":"integer","description":"Number of approvals required before continuing"},"timeout":{"type":"integer","description":"Timeout in seconds before auto-continuing or canceling"},"resume_form":{"type":"object","description":"Form schema for collecting input when resuming","properties":{"schema":{"type":"object","description":"JSON Schema for the resume form"}}},"user_auth_required":{"type":"boolean","description":"If true, only authenticated users can approve"},"user_groups_required":{"description":"Expression or list of groups that can approve","$ref":"#/components/schemas/InputTransform"},"self_approval_disabled":{"type":"boolean","description":"If true, the user who started the flow cannot approve"},"hide_cancel":{"type":"boolean","description":"If true, hide the cancel button on the approval form"},"continue_on_disapprove_timeout":{"type":"boolean","description":"If true, continue flow on timeout instead of canceling"},"skin":{"type":"string","enum":["detailed","minimal"],"description":"How the approval request is presented, on the approval page and in Slack/Teams approval messages. 'detailed' (used when unset) shows the flow details (arguments, graph, approvers); 'minimal' shows only the request: the step description, form and approve/reject actions"}}},"priority":{"type":"number","description":"Execution priority for this step (higher numbers run first)"},"continue_on_error":{"type":"boolean","description":"If true, flow continues even if this step fails"},"job_token_scopes":{"type":"array","nullable":true,"items":{"type":"string"},"description":"Scopes the token of this step's jobs is restricted to (domain:action[:resource], e.g. oidc:write), on top of the flow's own restriction: a step can only narrow it. Applies to everything the step runs (loop and branch bodies, AI agent tools)."},"retry":{"description":"Retry configuration if this step fails","$ref":"#/components/schemas/Retry"},"debouncing":{"description":"Debounce configuration for this step (EE only)","type":"object","properties":{"debounce_delay_s":{"type":"integer","description":"Delay in seconds to debounce this step's executions across flow runs"},"debounce_key":{"type":"string","description":"Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/-"},"debounce_args_to_accumulate":{"type":"array","description":"Array-type arguments to accumulate across debounced executions","items":{"type":"string"}},"max_total_debouncing_time":{"type":"integer","description":"Maximum total time in seconds before forced execution"},"max_total_debounces_amount":{"type":"integer","description":"Maximum number of debounces before forced execution"}}}},"required":["value","id"]},"InputTransform":{"description":"Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs","oneOf":[{"$ref":"#/components/schemas/StaticTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type","mapping":{"static":"#/components/schemas/StaticTransform","javascript":"#/components/schemas/JavascriptTransform","ai":"#/components/schemas/AiTransform"}}},"StaticTransform":{"type":"object","description":"Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'","properties":{"value":{"description":"The static value. For resources, use format '$res:path/to/resource'"},"type":{"type":"string","enum":["static"]}},"required":["type"]},"JavascriptTransform":{"type":"object","description":"JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')","properties":{"expr":{"type":"string","description":"JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"},"type":{"type":"string","enum":["javascript"]}},"required":["expr","type"]},"AiTransform":{"type":"object","description":"Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.","properties":{"type":{"type":"string","enum":["ai"]}},"required":["type"]},"AIProviderKind":{"type":"string","description":"Supported AI provider types","enum":["openai","azure_openai","azure_foundry","anthropic","mistral","deepseek","googleai","groq","openrouter","togetherai","customai","aws_bedrock","typesafe","cloudflare"]},"ProviderConfig":{"type":"object","description":"Complete AI provider configuration with resource reference and model selection","properties":{"kind":{"$ref":"#/components/schemas/AIProviderKind"},"resource":{"type":"string","description":"Resource reference in format '$res:{resource_path}' pointing to provider credentials"},"model":{"type":"string","description":"Model identifier (e.g., 'gpt-4', 'claude-3-opus-20240229', 'gemini-pro')"},"reasoning_effort":{"type":"string","description":"Provider-native reasoning effort token (e.g. 'low', 'high', 'none') for models that support extended thinking. Optional; unset leaves the provider default."}},"required":["kind","resource","model"]},"StaticProviderTransform":{"type":"object","description":"Static provider configuration passed directly to the AI agent","properties":{"value":{"$ref":"#/components/schemas/ProviderConfig"},"type":{"type":"string","enum":["static"]}},"required":["type","value"]},"ProviderTransform":{"description":"Provider configuration - can be static (ProviderConfig), JavaScript expression, or AI-determined","oneOf":[{"$ref":"#/components/schemas/StaticProviderTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type","mapping":{"static":"#/components/schemas/StaticProviderTransform","javascript":"#/components/schemas/JavascriptTransform","ai":"#/components/schemas/AiTransform"}}},"MemoryOff":{"type":"object","description":"No conversation memory/context","properties":{"kind":{"type":"string","enum":["off"]}},"required":["kind"]},"MemoryWindow":{"type":"object","description":"Keeps the most recent messages of the memory named by the run's memory id (or the step's\\n\`memory_id\`). Without a memory id the agent runs without memory.\\n","properties":{"kind":{"type":"string","enum":["window"]},"context_length":{"type":"integer","description":"Number of most recent messages to load and store. 0 turns memory off."}},"required":["kind","context_length"]},"MemoryAuto":{"type":"object","deprecated":true,"description":"Deprecated, still read as it was written: the run's memory id, else the \`memory_id\` here.\\nThe step's own \`memory_id\` is not read while this kind is set; switch the kind to \`window\`\\nto use it. Without a \`context_length\`, or with 0, it is \`off\` and reads \`previous_messages\`.\\n","properties":{"kind":{"type":"string","enum":["auto"]},"context_length":{"type":"integer","description":"Maximum number of messages to retain in context"},"memory_id":{"type":"string","description":"Identifier for persistent memory across agent invocations"}},"required":["kind"]},"MemoryCompaction":{"type":"object","description":"Keeps the whole memory named by the run's memory id (or the step's \`memory_id\`), replacing\\nits older part with a summary as the conversation approaches the model's context window.\\nWithout a memory id the agent runs without memory, and compaction bounds the run's own loop.\\n","properties":{"kind":{"type":"string","enum":["compaction"]},"context_window":{"type":"integer","description":"Overrides the context window looked up from the model, in tokens. Only a model\\nWindmill does not know needs one; those fall back to 128000.\\n"}},"required":["kind"]},"MemoryMessage":{"type":"object","description":"A single message in conversation history","properties":{"role":{"type":"string","enum":["user","assistant","system"]},"content":{"type":"string"}},"required":["role","content"]},"MemoryManual":{"type":"object","deprecated":true,"description":"Deprecated, still read as it was written. Move the step to \`off\` with \`previous_messages\` instead.","properties":{"kind":{"type":"string","enum":["manual"]},"messages":{"type":"array","items":{"$ref":"#/components/schemas/MemoryMessage"}}},"required":["kind","messages"]},"MemoryConfig":{"description":"Managed memory, stored by Windmill and replayed with each request. The memory is named by a memory id, see \`memory_id\`. While it is off, a step can supply its history in \`previous_messages\`.","oneOf":[{"$ref":"#/components/schemas/MemoryOff"},{"$ref":"#/components/schemas/MemoryWindow"},{"$ref":"#/components/schemas/MemoryCompaction"},{"$ref":"#/components/schemas/MemoryAuto"},{"$ref":"#/components/schemas/MemoryManual"}],"discriminator":{"propertyName":"kind","mapping":{"off":"#/components/schemas/MemoryOff","window":"#/components/schemas/MemoryWindow","compaction":"#/components/schemas/MemoryCompaction","auto":"#/components/schemas/MemoryAuto","manual":"#/components/schemas/MemoryManual"}}},"StaticMemoryTransform":{"type":"object","description":"Static memory configuration passed directly to the AI agent","properties":{"value":{"$ref":"#/components/schemas/MemoryConfig"},"type":{"type":"string","enum":["static"]}},"required":["type","value"]},"MemoryTransform":{"description":"Memory configuration - can be static (MemoryConfig), JavaScript expression, or AI-determined","oneOf":[{"$ref":"#/components/schemas/StaticMemoryTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type","mapping":{"static":"#/components/schemas/StaticMemoryTransform","javascript":"#/components/schemas/JavascriptTransform","ai":"#/components/schemas/AiTransform"}}},"FlowModuleValue":{"description":"The actual implementation of a flow step. Can be a script (inline or referenced), subflow, loop, branch, or special module type","oneOf":[{"$ref":"#/components/schemas/RawScript"},{"$ref":"#/components/schemas/PathScript"},{"$ref":"#/components/schemas/PathFlow"},{"$ref":"#/components/schemas/ForloopFlow"},{"$ref":"#/components/schemas/WhileloopFlow"},{"$ref":"#/components/schemas/BranchOne"},{"$ref":"#/components/schemas/BranchAll"},{"$ref":"#/components/schemas/Identity"},{"$ref":"#/components/schemas/AiAgent"},{"$ref":"#/components/schemas/AiDecision"}],"discriminator":{"propertyName":"type","mapping":{"rawscript":"#/components/schemas/RawScript","script":"#/components/schemas/PathScript","flow":"#/components/schemas/PathFlow","forloopflow":"#/components/schemas/ForloopFlow","whileloopflow":"#/components/schemas/WhileloopFlow","branchone":"#/components/schemas/BranchOne","branchall":"#/components/schemas/BranchAll","identity":"#/components/schemas/Identity","aiagent":"#/components/schemas/AiAgent","aidecision":"#/components/schemas/AiDecision"}}},"RawScript":{"type":"object","description":"Inline script with code defined directly in the flow. Use 'bun' as default language if unspecified. The script receives arguments from input_transforms","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"content":{"type":"string","description":"The script source code. Should export a 'main' function"},"language":{"type":"string","description":"Programming language for this script","enum":["deno","bun","bunnative","python3","go","bash","powershell","postgresql","mysql","bigquery","snowflake","mssql","oracledb","graphql","nativets","php","rust","ansible","csharp","nu","java","ruby","rlang","duckdb"]},"path":{"type":"string","description":"Optional path for saving this script"},"lock":{"type":"string","description":"Lock file content for dependencies"},"type":{"type":"string","enum":["rawscript"]},"tag":{"type":"string","description":"Worker group tag for execution routing"},"concurrent_limit":{"type":"number","description":"Maximum concurrent executions of this script"},"concurrency_time_window_s":{"type":"number","description":"Time window for concurrent_limit"},"custom_concurrency_key":{"type":"string","description":"Custom key for grouping concurrent executions"},"is_trigger":{"type":"boolean","description":"If true, this script is a trigger that can start the flow"},"assets":{"type":"array","description":"External resources this script accesses (S3 objects, resources, etc.)","items":{"type":"object","required":["path","kind"],"properties":{"path":{"type":"string","description":"Path to the asset"},"kind":{"type":"string","description":"Type of asset","enum":["s3object","resource","ducklake","datatable","volume","dbt"]},"access_type":{"type":"string","nullable":true,"description":"Access level for this asset","enum":["r","w","rw"]},"alt_access_type":{"type":"string","nullable":true,"description":"Alternative access level","enum":["r","w","rw"]}}}}},"required":["type","content","language","input_transforms"]},"PathScript":{"type":"object","description":"Reference to an existing script by path. Use this when calling a previously saved script instead of writing inline code","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"path":{"type":"string","description":"Path to the script in the workspace (e.g., 'f/scripts/send_email')"},"hash":{"type":"string","description":"Optional specific version hash of the script to use"},"type":{"type":"string","enum":["script"]},"tag_override":{"type":"string","description":"Override the script's default worker group tag"},"is_trigger":{"type":"boolean","description":"If true, this script is a trigger that can start the flow"}},"required":["type","path","input_transforms"]},"PathFlow":{"type":"object","description":"Reference to an existing flow by path. Use this to call another flow as a subflow","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the subflow's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"path":{"type":"string","description":"Path to the flow in the workspace (e.g., 'f/flows/process_user')"},"type":{"type":"string","enum":["flow"]}},"required":["type","path","input_transforms"]},"ForloopFlow":{"type":"object","description":"Executes nested modules in a loop over an iterator. Inside the loop, use 'flow_input.iter.value' to access the current iteration value, and 'flow_input.iter.index' for the index. Supports parallel execution for better performance on I/O-bound operations","properties":{"modules":{"type":"array","description":"Steps to execute for each iteration. These can reference the iteration value via 'flow_input.iter.value'","items":{"$ref":"#/components/schemas/FlowModule"}},"iterator":{"description":"JavaScript expression that returns an array to iterate over. Can reference 'results.step_id' or 'flow_input'","$ref":"#/components/schemas/InputTransform"},"skip_failures":{"type":"boolean","description":"If true, iteration failures don't stop the loop. Failed iterations return null"},"type":{"type":"string","enum":["forloopflow"]},"parallel":{"type":"boolean","description":"If true, iterations run concurrently (faster for I/O-bound operations). Use with parallelism to control concurrency"},"parallelism":{"description":"Maximum number of concurrent iterations when parallel=true. Limits resource usage. Can be static number or expression","$ref":"#/components/schemas/InputTransform"},"squash":{"type":"boolean"}},"required":["modules","iterator","skip_failures","type"]},"WhileloopFlow":{"type":"object","description":"Executes nested modules repeatedly until stopped. The implicit iterator is the iteration counter, so 'flow_input.iter.value' equals 'flow_input.iter.index' (0, 1, 2, ...) and never carries state. To carry state across iterations, a step reads its own previous-iteration result via 'results.' with a first-iteration fallback - the loop's stop_after_if must then be on that inner step (a plain single-step body with stop_after_if on the loop module does not resolve 'results' across iterations and never terminates); plain counters can instead be derived from 'flow_input.iter.index', which works in every configuration. stop_after_if is evaluated after each iteration - on the loop module 'result' is the last iteration's result","properties":{"modules":{"type":"array","description":"Steps to execute in each iteration","items":{"$ref":"#/components/schemas/FlowModule"}},"skip_failures":{"type":"boolean","description":"If true, iteration failures don't stop the loop. Failed iterations return null"},"type":{"type":"string","enum":["whileloopflow"]},"parallel":{"type":"boolean","description":"If true, iterations run concurrently (use with caution in while loops)"},"parallelism":{"description":"Maximum number of concurrent iterations when parallel=true","$ref":"#/components/schemas/InputTransform"},"squash":{"type":"boolean"}},"required":["modules","skip_failures","type"]},"BranchOne":{"type":"object","description":"Conditional branching where only the first matching branch executes. Branches are evaluated in order, and the first one with a true expression runs. If no branches match, the default branch executes","properties":{"branches":{"type":"array","description":"Array of branches to evaluate in order. The first branch with expr evaluating to true executes","items":{"type":"object","properties":{"summary":{"type":"string","description":"Short description of this branch condition"},"expr":{"type":"string","description":"JavaScript expression that returns boolean. Can use 'results.step_id' or 'flow_input'. First true expr wins"},"modules":{"type":"array","description":"Steps to execute if this branch's expr is true","items":{"$ref":"#/components/schemas/FlowModule"}}},"required":["modules","expr"]}},"default":{"type":"array","description":"Steps to execute if no branch expressions match","items":{"$ref":"#/components/schemas/FlowModule"}},"type":{"type":"string","enum":["branchone"]}},"required":["branches","default","type"]},"BranchAll":{"type":"object","description":"Parallel branching where all branches execute simultaneously. Unlike BranchOne, all branches run regardless of conditions. Useful for executing independent tasks concurrently","properties":{"branches":{"type":"array","description":"Array of branches that all execute (either in parallel or sequentially)","items":{"type":"object","properties":{"summary":{"type":"string","description":"Short description of this branch's purpose"},"skip_failure":{"type":"boolean","description":"If true, failure in this branch doesn't fail the entire flow"},"modules":{"type":"array","description":"Steps to execute in this branch","items":{"$ref":"#/components/schemas/FlowModule"}}},"required":["modules"]}},"type":{"type":"string","enum":["branchall"]},"parallel":{"type":"boolean","description":"If true, all branches execute concurrently. If false, they execute sequentially"}},"required":["branches","type"]},"AgentTool":{"type":"object","description":"A tool available to an AI agent. Can be a flow module or an external MCP (Model Context Protocol) tool","properties":{"id":{"type":"string","description":"Unique identifier for this tool. Cannot contain spaces - use underscores instead (e.g., 'get_user_data' not 'get user data')"},"summary":{"type":"string","description":"The name the AI agent calls this tool by, not a human label. On a flowmodule tool it must match ^[a-zA-Z0-9_]+$ - letters, numbers and underscores only (e.g. 'search_documentation', not 'Search documentation') - and always be set; on an mcp or websearch tool it is a plain label. Put the human-readable explanation in 'description'."},"description":{"type":"string","description":"Free-text description of the tool given to the AI to decide when and how to call it. Overrides the description auto-derived from the underlying script."},"job_token_scopes":{"type":"array","nullable":true,"items":{"type":"string"},"description":"Scopes the token of this tool's jobs is restricted to, on top of the agent step's own restriction: a tool can only narrow it."},"value":{"$ref":"#/components/schemas/ToolValue"}},"required":["id","value"]},"ToolValue":{"description":"The implementation of a tool. Can be a flow module (script/flow) or an MCP tool reference","oneOf":[{"$ref":"#/components/schemas/FlowModuleTool"},{"$ref":"#/components/schemas/McpToolValue"},{"$ref":"#/components/schemas/WebsearchToolValue"}],"discriminator":{"propertyName":"tool_type","mapping":{"flowmodule":"#/components/schemas/FlowModuleTool","mcp":"#/components/schemas/McpToolValue","websearch":"#/components/schemas/WebsearchToolValue"}}},"FlowModuleTool":{"description":"A tool implemented as a flow module (script, flow, etc.). The AI can call this like any other flow module","allOf":[{"type":"object","properties":{"tool_type":{"type":"string","enum":["flowmodule"]}},"required":["tool_type"]},{"$ref":"#/components/schemas/FlowModuleValue"}]},"WebsearchToolValue":{"type":"object","description":"A tool implemented as a websearch tool. The AI can call this like any other websearch tool","properties":{"tool_type":{"type":"string","enum":["websearch"]}},"required":["tool_type"]},"McpToolValue":{"type":"object","description":"Reference to an external MCP (Model Context Protocol) tool. The AI can call tools from MCP servers","properties":{"tool_type":{"type":"string","enum":["mcp"]},"resource_path":{"type":"string","description":"Path to the MCP resource/server configuration"},"include_tools":{"type":"array","description":"Whitelist of specific tools to include from this MCP server","items":{"type":"string"}},"exclude_tools":{"type":"array","description":"Blacklist of tools to exclude from this MCP server","items":{"type":"string"}}},"required":["tool_type","resource_path"]},"AiAgent":{"type":"object","description":"AI agent step that can use tools to accomplish tasks. The agent receives inputs and can call any of its configured tools to complete the task","properties":{"input_transforms":{"type":"object","description":"Input parameters for the AI agent mapped to their values","properties":{"provider":{"$ref":"#/components/schemas/ProviderTransform"},"output_type":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Output format type.\\nValid values: 'text' (default) - plain text response, 'image' - image generation\\n"},"user_message":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"The user's prompt/message to the AI agent. Supports variable interpolation with\\nflow.input syntax. Required unless memory is off and \`previous_messages\` supplies\\nthe prompt; image output always needs it.\\n"},"system_prompt":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"System instructions that guide the AI's behavior, persona, and response style. Optional."},"streaming":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Boolean. If true, stream the AI response incrementally.\\nStreaming events include: token_delta, reasoning_token_delta, tool_call, tool_call_arguments, tool_execution, tool_result\\n"},"memory":{"$ref":"#/components/schemas/MemoryTransform"},"memory_id":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"String. Names the memory this step reads and writes, overriding the memory id the run\\nwas started with (the chat conversation, an app chat session or the \`memory_id\` run\\nparameter). Leave unset to use the run's memory id. A fixed value shares one memory\\nacross every run; an expression such as \`flow_input.customer_id\` keeps one memory per\\nkey. When it evaluates to an empty value the agent runs without memory. Read only\\nwhile \`memory\` is \`window\` or \`compaction\`: it is ignored when memory is off, and an\\nolder \`auto\` or \`manual\` memory reads neither history input.\\n"},"previous_messages":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Array of MemoryMessage. History supplied by the flow, sent between the system prompt\\nand the user message. Read only while \`memory\` is off or absent: managed memory\\nignores it, and an older \`auto\` or \`manual\` memory reads neither history input.\\n"},"output_schema":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"JSON Schema object defining structured output format. Used when you need the AI to return data in a specific shape.\\nSupports standard JSON Schema properties: type, properties, required, items, enum, pattern, minLength, maxLength, minimum, maximum, etc.\\nExample: { type: 'object', properties: { name: { type: 'string' }, age: { type: 'integer' } }, required: ['name'] }\\n"},"user_attachments":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Array of file references (images or PDFs) for the AI agent.\\nFormat: Array<{ bucket: string, key: string }> - S3 object references\\nExample: [{ bucket: 'my-bucket', key: 'documents/report.pdf' }]\\n"},"enabled_tools":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Array of strings naming which of the tools configured in \`tools\` the agent may call\\nthis run. Leaving it unset carries every one of them; an empty array carries none.\\nA tool is named as the model is shown it. An entry the model is shown nothing of is\\nnamed by what identifies it instead: an MCP server by its resource path, carrying\\nevery tool it exposes (which of them stays that entry's include_tools/exclude_tools),\\nand a websearch entry by the reserved name '__wm_web_search', whatever summary it carries\\n(no tool may take that name).\\nExample: ['get_user', 'u/admin/github_mcp', '__wm_web_search']\\n"},"max_completion_tokens":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Integer. Maximum number of tokens the AI will generate in its response.\\nRange: 1 to 4,294,967,295. Typical values: 256-4096 for most use cases.\\n"},"temperature":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Float. Controls randomness/creativity of responses.\\nRange: 0.0 to 2.0 (provider-dependent)\\n- 0.0 = deterministic, focused responses\\n- 0.7 = balanced (common default)\\n- 1.0+ = more creative/random\\n"},"max_iterations":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Number. Limits how many times the agent can loop through reasoning and tool use.\\nRange: 1-1000.\\n"},"model":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"String. Only on a step linked to a saved agent (see \`agent\`): replaces the model\\nsaved on the agent for this step's runs, on the agent's own provider resource. An\\nempty value keeps the saved model. Set it to an expression such as\\n\`flow_input.model\` to choose the model per run.\\n"},"reasoning_effort":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"String. Only on a step linked to a saved agent (see \`agent\`): replaces the reasoning\\neffort saved on the agent for this step's runs, as a provider-native token (e.g.\\n'low', 'high', 'none'). An empty value sends no effort, so the model runs at its\\ndefault. Leave the input out to keep the saved effort, which holds only while the\\nstep runs the saved model. A step that is not linked sets both inside \`provider\`.\\n"}}},"tools":{"type":"array","description":"Array of tools the agent can use. The agent decides which tools to call based on the task","items":{"$ref":"#/components/schemas/AgentTool"}},"type":{"type":"string","enum":["aiagent"]},"tag":{"type":"string","description":"Worker group tag for execution routing. If not set, the AI agent step runs on the flow's tag (default \`flow\`)"},"omit_output_from_conversation":{"type":"boolean","default":false,"description":"If true, this AI agent step does not persist its assistant or tool messages to the flow conversation when chat mode is enabled."},"agent":{"type":"string","description":"Path of a reusable \`ai_agent\` resource (hybrid linking). When set, the agent brain\\nconfig (provider/model/system prompt/etc.) and tool set are resolved at runtime from\\nthat resource; the module's input_transforms then only carry the flow-local inputs\\n(user_message, user_attachments, enabled_tools and the history inputs memory_id and previous_messages)\\nand, optionally, the \`model\` and \`reasoning_effort\` overrides of what the agent saved.\\n"},"tool_inputs":{"type":"object","description":"Host-local wiring for an agent's tool inputs, keyed by tool id then input key. Binds the\\nreferenced agent's tools to this flow's context (flow_input/results) without mutating the\\nshared resource; overlaid onto the tools' input_transforms at runtime \\u2014 including when\\n\`agent\` is unset, since a step forked for editing keeps these overrides until it is saved\\nback or unlinked.\\n","additionalProperties":{"type":"object","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}}},"parallel":{"type":"boolean","description":"If true, the agent can execute multiple tool calls in parallel"}},"required":["type","input_transforms"]},"AiDecision":{"type":"object","description":"AI decision step: one call to a decision model (TypeSafe's Jev, Cloudflare's\\nJev-compatible Clef, or OpenAI's Decisions API) that answers typed questions about a\\nstate with calibrated probabilities, instead of generating text.\\nPrefer it over an AI agent to classify, route, score or check something: it is fast,\\ncheap and its answers are structured. Its result is { output: { : answer },\\nmodel, usage }, so a later step reads e.g. results..output.intent.choice. To route on\\nthe answers, follow it with a branchone whose branch exprs read\\nresults..output..choice. Usable as an AI agent tool, where the calling agent\\nsupplies the state.\\n","properties":{"input_transforms":{"type":"object","description":"Input parameters for the decision mapped to their values","properties":{"provider":{"$ref":"#/components/schemas/ProviderTransform"},"state":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"What the questions are asked about: a string, an object or an array of strings.\\nAn object with descriptive keys holding only what the questions need works best.\\nExample: { message: flow_input.message, plan: results.a.plan }\\n"},"questions":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Object mapping each question name to { type, instructions, criteria }, where type is:\\n- 'choice': criteria maps each option to its description (up to 255); the answer\\n has choice, probabilities and confidence\\n- 'score': criteria is an ordered array of 2 to 10 level descriptions; the answer\\n has score, legend, probabilities and confidence\\n- 'noul': yes/no, criteria optionally { true, false } descriptions; the answer has\\n noul, the probability of yes (0 to 1)\\nExample: { intent: { type: 'choice', instructions: 'What does the customer want?',\\ncriteria: { refund: 'Money back', bug: 'Something is broken' } } }\\n"}},"required":["provider","state","questions"]},"type":{"type":"string","enum":["aidecision"]},"tag":{"type":"string","description":"Worker group tag for execution routing. If not set, the step runs on the flow's tag (default \`flow\`)"}},"required":["type","input_transforms"]},"Identity":{"type":"object","description":"Pass-through module that returns its input unchanged. Useful for flow structure or as a placeholder","properties":{"type":{"type":"string","enum":["identity"]},"flow":{"type":"boolean","description":"If true, marks this as a flow identity (special handling)"}},"required":["type"]},"FlowStatus":{"type":"object","properties":{"step":{"type":"integer"},"modules":{"type":"array","items":{"$ref":"#/components/schemas/FlowStatusModule"}},"user_states":{"additionalProperties":true},"preprocessor_module":{"allOf":[{"$ref":"#/components/schemas/FlowStatusModule"}]},"failure_module":{"allOf":[{"$ref":"#/components/schemas/FlowStatusModule"},{"type":"object","properties":{"parent_module":{"type":"string"}}}]},"retry":{"type":"object","properties":{"fail_count":{"type":"integer"},"failed_jobs":{"type":"array","items":{"type":"string","format":"uuid"}}}}},"required":["step","modules","failure_module"]},"FlowStatusModule":{"type":"object","properties":{"type":{"type":"string","enum":["WaitingForPriorSteps","WaitingForEvents","WaitingForExecutor","InProgress","Success","Failure"]},"id":{"type":"string"},"job":{"type":"string","format":"uuid"},"count":{"type":"integer"},"progress":{"type":"integer"},"iterator":{"type":"object","properties":{"index":{"type":"integer"},"itered":{"type":"array","items":{}},"itered_len":{"type":"integer"},"args":{}}},"flow_jobs":{"type":"array","items":{"type":"string"}},"flow_jobs_success":{"type":"array","items":{"type":"boolean"}},"flow_jobs_duration":{"type":"object","properties":{"started_at":{"type":"array","items":{"type":"string"}},"duration_ms":{"type":"array","items":{"type":"integer"}}}},"branch_chosen":{"type":"object","properties":{"type":{"type":"string","enum":["branch","default"]},"branch":{"type":"integer"}},"required":["type"]},"branchall":{"type":"object","properties":{"branch":{"type":"integer"},"len":{"type":"integer"}},"required":["branch","len"]},"approvers":{"type":"array","items":{"type":"object","properties":{"resume_id":{"type":"integer"},"approver":{"type":"string"}},"required":["resume_id","approver"]}},"failed_retries":{"type":"array","items":{"type":"string","format":"uuid"}},"skipped":{"type":"boolean"},"agent_actions":{"type":"array","items":{"type":"object","oneOf":[{"type":"object","properties":{"job_id":{"type":"string","format":"uuid"},"function_name":{"type":"string"},"type":{"type":"string","enum":["tool_call"]},"module_id":{"type":"string"}},"required":["job_id","function_name","type","module_id"]},{"type":"object","properties":{"call_id":{"type":"string","format":"uuid"},"function_name":{"type":"string"},"resource_path":{"type":"string"},"type":{"type":"string","enum":["mcp_tool_call"]},"arguments":{"type":"object"}},"required":["call_id","function_name","resource_path","type"]},{"type":"object","properties":{"type":{"type":"string","enum":["web_search"]}},"required":["type"]},{"type":"object","properties":{"type":{"type":"string","enum":["message"]}},"required":["content","type"]}]}},"agent_actions_success":{"type":"array","items":{"type":"boolean"}}},"required":["type"]}} `, "raw-app": `--- name: raw-app @@ -6315,7 +6476,7 @@ You need three values to run the command: 1. **summary** — a short description of the app 2. **path** — the windmill path, e.g. \`f/folder/my_app\` or \`u/username/my_app\` -3. **framework** — one of \`react19\` (recommended), \`react18\`, \`svelte5\`, \`vue\` +3. **framework** — one of \`react19\` (recommended), \`react18\`, \`svelte5\` **summary and path**: if the user's request did not supply them, ask. Do not guess values and do not invent paths. @@ -6387,7 +6548,7 @@ my_app{{RAW_APP_SUFFIX}}/ ├── DATATABLES.md # Database schemas (run 'wmill app generate-agents' to refresh) ├── raw_app.yaml # App configuration (summary, path, data settings) ├── index.tsx # Frontend entry point -├── App.tsx # Main React/Svelte/Vue component +├── App.tsx # Main React/Svelte component ├── index.css # Styles ├── package.json # Frontend dependencies ├── wmill.ts # Auto-generated backend type definitions (DO NOT EDIT) @@ -6450,6 +6611,8 @@ fields: value: "default_user" \`\`\` +\`viewer_data_access: true\` makes an inline runnable read data tables and object storage as the person using the app instead of as the app's identity (see "Reading data as the viewer"). + ### Referencing existing scripts To use an existing Windmill script instead of inline code: @@ -6486,7 +6649,7 @@ data: - \`/
\` — Specific table in public schema - \`/:
\` — Table in specific schema -**Roles:** when a datatable is under roles, its queries run as a role, which only reaches what it was granted. \`roles\` records the role the app uses each datatable through; the app's code must pass the same role: \`wmill.datatable('main', { role: 'analyst' })\` in TypeScript, \`wmill.datatable('main', role='analyst')\` in Python. A datatable without an entry is used as its default role. +**Roles:** when a datatable is under roles, its queries run as a role, which only reaches what it was granted. \`roles\` records the role the app uses each datatable through; the app's code must pass the same role: \`wmill.datatable('main', { role: 'analyst' })\` in TypeScript, \`wmill.datatable('main', role='analyst')\` in Python. A datatable without an entry is used as its default role, if it has one, plus the roles of the app's identity, or of whoever is using the app for a runnable with \`viewer_data_access: true\`, unless that default is \`admin\`. ## SQL Migrations (sql_to_apply/) @@ -6545,7 +6708,7 @@ For the rest, tell the user which command fits their intent and let them run it # Windmill Raw Apps -Raw apps let you build custom frontends with React, Svelte, or Vue that connect to Windmill backend runnables and datatables. +Raw apps let you build custom frontends with React or Svelte that connect to Windmill backend runnables and datatables. ## App shape @@ -6561,7 +6724,7 @@ A new app gets the setup Windmill's own new-app dialog gives one: a framework, t ### Framework -Use the framework the user named. When they named none, follow what there is to follow: the app being edited, or the apps the request points at. With nothing to follow, use **React 19**, the recommended default, **without asking**. React 18, Svelte 5 and Vue are for when they are asked for. +Use the framework the user named. When they named none, follow what there is to follow: the app being edited, or the apps the request points at. With nothing to follow, use **React 19**, the recommended default, **without asking**. React 18 and Svelte 5 are for when they are asked for. These three are the only frameworks the raw app bundler builds. When the user asks to build or convert an app in another framework, write no code in it: say it is not available and offer these three instead. ### Data setup @@ -6591,7 +6754,7 @@ Then build what was chosen: the data table and schema become the app's \`data.da ### Entrypoint -The entrypoint is \`index.tsx\` for React and \`index.ts\` for Svelte and Vue. It is both the bundling entrypoint (the bundler is esbuild) and the **mount** entrypoint: the preview executes the bundle against an empty \`
\` and auto-renders nothing, so the entrypoint must mount a top-level \`App\` itself. Keep the UI in \`App.tsx\` / \`App.svelte\` / \`App.vue\` and keep the entrypoint as the mount shim. +The entrypoint is \`index.tsx\` for React and \`index.ts\` for Svelte. It is both the bundling entrypoint (the bundler is esbuild) and the **mount** entrypoint: the preview executes the bundle against an empty \`
\` and auto-renders nothing, so the entrypoint must mount a top-level \`App\` itself. Keep the UI in \`App.tsx\` / \`App.svelte\` and keep the entrypoint as the mount shim. React (\`index.tsx\`): @@ -6603,10 +6766,12 @@ import App from './App' createRoot(document.getElementById('root')!).render() \`\`\` -Svelte (\`index.ts\`): \`mount(App, { target: document.getElementById('root')! })\`. Vue (\`index.ts\`): \`createApp(App).mount('#root')\`. +Svelte (\`index.ts\`): \`mount(App, { target: document.getElementById('root')! })\`. **Never replace the entrypoint with a bare component** (\`export default function App() { ... }\` and no mount call). A component that is defined but never mounted renders a blank screen with **no error thrown** — it never executes, so nothing reaches the console or the error overlay. If an app renders blank, check that the entrypoint still mounts \`App\` into \`#root\`. +**Set the browser tab title with \`document.title = '...'\`** (or a \`\` the framework renders into \`<head>\`). The app has no \`index.html\` of its own, so a \`<title>\` written there is never served; the deployed app's page shows whatever \`document.title\` holds, and follows it when it changes. + **Always begin every React file (\`.tsx\`/\`.jsx\`) that uses JSX with \`import React from 'react'\`.** esbuild uses the classic JSX transform, so \`React\` must be in scope wherever JSX appears — a missing import compiles fine but throws \`React is not defined\` at runtime, leaving a blank screen. ### Generated bindings (\`wmill.d.ts\` / \`wmill.ts\`) @@ -6676,16 +6841,16 @@ Apply it to customer data, internal notes and anything else a viewer of the demo ### Chat UIs over a flow in chat mode -A flow deployed with chat mode on is a chat backend (streaming answer, tool calls, memory, conversation history). Do not drive it through a runnable: add \`windmill-chat\` to \`package.json\` and use it directly, it detects the app's Windmill and credential. +A flow deployed with chat mode on is a chat backend (streaming answer, tool calls, memory, conversation history). Do not drive it through a runnable: add \`@windmill-labs/chat-sdk\` to \`package.json\` and use it directly, it detects the app's Windmill and credential. \`\`\`tsx -import { useWindmillChat } from 'windmill-chat/react' +import { useWindmillChat } from '@windmill-labs/chat-sdk/react' const chat = useWindmillChat({ flowPath: 'f/support/assistant' }) // chat.messages ({ role, content, pending, success, tool? }), chat.status, chat.sendMessage(text), chat.stop() \`\`\` -\`windmill-chat/ai-sdk\` gives a \`ChatTransport\` for the Vercel AI SDK's \`useChat\`, \`windmill-chat/assistant-ui\` a runtime for assistant-ui. The flow must be deployed, not a draft. A sandboxed app needs \`jobs:run\` in its frontend SDK scopes, plus \`flow_conversations:write\` for the conversation sidebar; without them the chat keeps history in the browser. +\`@windmill-labs/chat-sdk/ai-sdk\` gives a \`ChatTransport\` for the Vercel AI SDK's \`useChat\`, \`@windmill-labs/chat-sdk/assistant-ui\` a runtime for assistant-ui. The flow must be deployed, not a draft. A sandboxed app needs \`jobs:run\` in its frontend SDK scopes, plus \`flow_conversations:write\` for the conversation sidebar; without them the chat keeps history in the browser. ## Backend runnables @@ -6726,6 +6891,10 @@ def main(user_id: str): return user \`\`\` +#### Sharing code between runnables + +An inline runnable can import another inline runnable of the same app by its id, as a relative import: \`import { getDb } from './shared'\` (TypeScript, Bun) or \`from .shared import get_db\` (Python). This works across TypeScript (Bun) runnables and across Python runnables, not between the two. The imported runnable's own dependencies are picked up, and it can import further runnables in turn. A runnable that only holds helpers needs no \`main\`; the frontend just never calls it. A TypeScript runnable whose id is \`main\` cannot be imported, because that name is taken by the entrypoint file of every TypeScript job: give shared code any other id. + #### The \`wmill\` client is already authenticated An inline runnable runs as an ordinary Windmill job. \`import * as wmill from 'windmill-client'\` (TypeScript) and \`import wmill\` (Python) are already pointed at this instance and this workspace — there is nothing to configure. @@ -6769,6 +6938,27 @@ A draft app is reachable by nobody; deploying is what exposes it, and its backen Either one lets those people run the app's backend runnables, so never open an app up unless the user asks. \`public: true\` in \`raw_app.yaml\` deploys the app for anonymous users, and \`guests: true\` for guests. Remove the line and the next push closes the app again. +An app's custom URL is not in \`raw_app.yaml\`: each workspace has its own file next to the app folder, \`<app path>.<workspace>.custom_path.yaml\` (for example \`f/sales/dashboard.prod.custom_path.yaml\` holding \`custom_path: dashboard\`), where \`<workspace>\` is the workspace's name in \`wmill.yaml\`, or its id. A push applies only the target workspace's file and leaves the deployed custom URL alone when there is none, so deleting the file does not remove the URL: \`custom_path: ''\` does. Setting or clearing one takes a workspace admin. + +## Sandbox isolation and frontend API access + +New apps are sandboxed: the frontend is isolated from the viewer's own Windmill session and reaches Windmill only through its backend runnables, plus whatever frontend API scopes the app declares, which each viewer approves before the app runs. With isolation turned off, the frontend runs with the viewer's full session. The scopes are \`jobs:run\`, \`jobs:read\`, \`resources:read\`, \`variables:read\`, \`flow_conversations:read\` and \`flow_conversations:write\`; grant only the ones the frontend calls. The viewer's identity needs no scope: it is in \`window.ctx\`, and whoami works with any of them. + +Inside the sandbox, IndexedDB is unavailable, third-party sign-in and OAuth redirects fail, and requests to other services carry \`Origin: null\`, which an API that checks the origin rejects. Work around these first: call the service from a backend runnable, keep state in a data table or \`localStorage\`, or grant the frontend API scope the code needs. Suggest turning isolation off only when none of that works, and say plainly that it is a security risk: the app's code, and any XSS bug in it, then runs with the full Windmill permissions of everyone who opens the app. +In \`raw_app.yaml\`: + +\`\`\`yaml +sandbox: true +frontend_api: [jobs:run] +\`\`\` + +A file with a \`sandbox\` key states both settings: \`sandbox: false\` turns isolation off, and a missing \`frontend_api\` means no scopes. A file without the key leaves the deployed app's isolation and scopes as they are, so removing \`sandbox: true\` does not unsandbox it. \`frontend_api\` needs \`sandbox: true\`; the push fails otherwise. + +## Reading data as the viewer + +A backend runnable reads data as the app's identity (the publisher in publisher mode), the same for every viewer. An inline runnable can instead read data as the person using the app: its data table connections that name no role hold that viewer's roles, and object storage permission rules (which paths may be listed, read, written) are checked against the viewer. Resources, variables and everything else stay the app's, and an anonymous viewer is refused. Turn it on only when what the runnable reads should differ per viewer: row-level security on a data table, or per-user paths in object storage. Both are Enterprise Edition features. +Set it with \`viewer_data_access: true\` in the runnable's \`backend/<id>.yaml\`. + ## Data Tables Data tables are PostgreSQL databases managed by Windmill. Backend runnables query them via the \`wmill\` client; the frontend never queries them directly. **When the app needs to store or persist data** (user data, settings, application state, records, logs), use a data table. @@ -6780,6 +6970,7 @@ Data tables are PostgreSQL databases managed by Windmill. Backend runnables quer 3. **No DDL inside runnables**: runnables only read and write rows (SELECT, INSERT, UPDATE, DELETE) on existing tables. Never CREATE, ALTER or DROP a table from a runnable. 4. **Qualify table names**: an unqualified name means the \`public\` schema, so write every other table as \`schema.table\`, in table creation and queries alike. The app's \`data\` config sets the default datatable and schema its tables go in; use them consistently across runnables. 5. **Pass the role**: when the app's \`data.roles\` gives a data table a role, every \`wmill.datatable\` call on it passes that role (\`wmill.datatable('main', { role: 'analyst' })\` in TypeScript, \`wmill.datatable('main', role='analyst')\` in Python). The role only reaches what it was granted, so a query outside it fails with \`permission denied\`. +6. **Per-viewer rows**: a data table with no entry in \`data.roles\` is called with no role. Unless its default role is \`admin\`, the connection then holds the default role, if it may use it, plus every role it is a tenant of, and is refused when that is none. Whose roles those are follows the runnable's identity (see "Reading data as the viewer"). Row-level security policies written as \`pg_has_role(current_user, '<role>', 'member')\` then return the right rows with nothing added to the code. A role pins the connection to that one role either way, so a data table whose rows should differ per viewer gets no \`data.roles\` entry. Data table roles are an Enterprise Edition feature, self-hosted only. \`wmill datatable list\` lists the workspace's data tables. Create or change tables with a migration in \`sql_to_apply/\` (see "SQL Migrations" above), then add them to \`data.tables\` in \`raw_app.yaml\`. @@ -6833,7 +7024,7 @@ def main(user_id: str): 7. **Mark sensitive UI with \`data-wm-no-record\`** — it is what keeps that data out of a recorded demo; passwords are handled for you. 8. **Reach for \`backendAsync\` + \`waitJob\`** for long work — never a hand-written job-polling runnable. 9. **Deploy what a path runnable points at** — a path runnable aimed at a draft fails at runtime; tell the user what needs deploying. -10. **Use \`windmill-chat\` for a chat over a chat-mode flow** — never a runnable that runs the flow and polls its stream. +10. **Use \`@windmill-labs/chat-sdk\` for a chat over a chat-mode flow** — never a runnable that runs the flow and polls its stream. `, "triggers": `--- name: triggers @@ -6998,6 +7189,12 @@ Example: \`f/databases/postgres_prod.resource.json\` - \`value\` - Object containing the resource configuration - \`resource_type\` - Name of the resource type (e.g., "postgresql", "slack") +## Agents + +An agent, as the Agents page lists it, is a resource of type \`ai_agent\`. Its value holds the +agent's provider, system prompt, tools and memory settings, and a flow step uses a saved agent by +linking its path. + ## Variable References Reference variables in resource values: @@ -7178,13 +7375,23 @@ The prefix must be on the string itself. } \`\`\` +## When No Resource Type Fits + +The Windmill Hub publishes resource types for most services, and an instance gets them by syncing with the hub. When none fits the service: + +- If the instance is reported as not having synced the hub's types, mention that a superadmin can sync them: the hub most likely has one for the service. That holds for a type a hub script takes too: it is missing here until the sync, so say so before asking for a resource of it. Create one of your own only if the user still wants it, since after a sync the workspace would hold both. +- Otherwise, or when the user prefers it to syncing, propose a custom resource type named \`c_<name>\` holding the service's connection fields (base URL, account or region identifiers, credentials), as in "Custom Resource Types" below, and ask the user before creating it: every resource of that type and every script taking one depends on its fields. +- A plain variable instead of a resource is fine when the user asks for it; without that, default to the resource, its secret in a variable it references. + ## Custom Resource Types +A custom type's name starts with \`c_\`: the hub's types reach every instance under their plain names, so the prefix keeps a custom type from clashing with one synced later. Scripts and flows refer to the full name: \`format: resource-c_custom_api\`, \`RT.CCustomApi\` in TypeScript, a \`c_custom_api\` TypedDict in Python. + Create custom resource types with JSON Schema: \`\`\`json { - "name": "custom_api", + "name": "c_custom_api", "schema": { "type": "object", "properties": { @@ -7198,7 +7405,7 @@ Create custom resource types with JSON Schema: } \`\`\` -Save as: \`custom_api.resource-type.json\` +Save as: \`c_custom_api.resource-type.json\` ## OAuth Resources @@ -7400,6 +7607,8 @@ async def enrich(customer_id: str): In TypeScript, prefer assigning each task to a named top-level const. In Python, prefer top-level async functions decorated with \`@task()\` or \`@task\`. +Only the workflow body dispatches steps. A task runs as a single job, so a task or \`step()\` called from inside a task body runs in place in that job, as a plain function call: no child job, no checkpoint, and its task options (retry, timeout, tag) do not apply. \`sleep()\` there waits in the job, and \`taskScript()\` / \`taskFlow()\` / \`waitForApproval()\` (\`task_script()\` / \`task_flow()\` / \`wait_for_approval()\`) throw. To get separate jobs, call the tasks one after another from the workflow body and pass results between them. + For existing scripts: \`\`\`typescript @@ -7565,8 +7774,9 @@ export async function getResumeUrls(approver?: string, flowLevel?: boolean): Pro * const call_api = task(fetchOrders, { retry: { attempts: 3, delay: 30, multiplier: 2 } }); * * Inside a \`workflow()\`, calling a task dispatches it as a step. - * Outside a workflow, the function body executes directly and - * {@link TaskOptions} — retry included — does not apply. + * Outside a workflow, or called from inside another task, the function body + * executes directly and {@link TaskOptions} — retry included — does not apply: + * a task runs as a single job, so the tasks it calls run in that same job. * * A task runs as its own job, so its result is always encoded as JSON and * decoded back before the caller sees it: a \`Date\` comes back as a string, a @@ -7610,6 +7820,9 @@ export function workflow<T>(fn: (...args: any[]) => Promise<T>) * \`fn\`'s result is encoded as JSON and decoded back before it is returned, so * the round that runs the body sees the same types every replay sees: a \`Date\` * comes back as a string, a \`Map\` as \`{}\`. {@link Jsonified} is that shape. + * + * Called from inside a task body, \`fn\` runs in place and nothing is + * checkpointed: a task is a single job and is never replayed. */ export async function step<T>(name: string, fn: () => T | Promise<T>,): Promise<Jsonified<Awaited<T>>> @@ -7708,7 +7921,9 @@ def get_resume_urls(approver: str = None, flow_level: bool = None) -> dict # # - **v2 (inside @workflow)**: dispatches as a checkpoint step. # - **v1 (WM_JOB_ID set, no @workflow)**: dispatches via HTTP API. -# - **Standalone**: executes the function body directly. +# - **Standalone, or called from inside another v2 task**: executes the +# function body directly. A task runs as a single job, so the tasks it +# calls run in that same job, without their own options. # # A task runs as its own job, so its result is always encoded as JSON and # decoded back before the caller sees it: a \`\`datetime\`\` comes back as a @@ -7794,12 +8009,15 @@ def workflow(func) # \`\`fn\`\`'s result is encoded as JSON and decoded back before it is returned, # so the round that runs the body sees the same types every replay sees: # a \`\`datetime\`\` comes back as a string, a tuple as a list. +# +# Called from inside a task body, \`\`fn\`\` runs in place and nothing is +# checkpointed: a task is a single job and is never replayed. async def step(name: str, fn) # Server-side sleep — suspend the workflow for the given duration without holding a worker. # # Inside a @workflow, the parent job suspends and auto-resumes after \`\`seconds\`\`. -# Outside a workflow, falls back to \`\`asyncio.sleep\`\`. +# Outside a workflow, or inside a task body, falls back to \`\`asyncio.sleep\`\`. async def sleep(seconds: int) # Suspend the workflow and wait for an external approval. @@ -7879,10 +8097,48 @@ A **data pipeline** is NOT a flow. A flow is one runnable that orchestrates step A pipeline node that produces a table should almost always be a **\`duckdb\`** node that materializes its output into a **DuckLake** table with \`-- materialize ducklake://<name>/<table>\` (in a DuckDB node the annotation uses SQL \`--\` comment syntax; write the body as a bare \`SELECT\` and let the runtime do the write). DuckLake is the default lakehouse store for pipelines and is the shape the pipeline editor is built around, so prefer it unless the work specifically calls for something else: - \`postgresql\` / data tables — only for row-level, OLTP-style mutations against an existing Postgres data table (frequent single-row upserts/updates, transactional reads that an app queries live). -- \`bun\` / \`python3\` — only for non-tabular work that doesn't map to SQL: calling an external API, wrangling files, arbitrary glue. When such a node still produces tabular data for downstream steps, land it in DuckLake (write it with the wmill SDK / ducklake helpers) rather than inventing a parallel store. +- \`bun\` / \`python3\` — only for work that doesn't map to SQL: calling an external API, wrangling files, arbitrary glue. When such a node produces tabular data for downstream steps, write it **straight into DuckLake** (or a data table) from the same script — see "Ingesting from Python / TypeScript" below — rather than inventing a parallel store. Do not spread a pipeline across postgres, S3, and DuckLake when one DuckLake lake would do; a consistent DuckLake lakehouse is the goal. +## Ingesting from Python / TypeScript + +A node that fetches data in code (an API, a SaaS export, a scraper) writes the rows **directly** into their DuckLake table with \`wmill.ducklake()\`, or into a data table with \`wmill.datatable()\`. DuckLake already stores every table as parquet files in the workspace object storage, so **never stage the raw payload first** — no intermediate JSON / CSV / parquet file in S3 and no second "load the raw file" node. One ingestion node, one table. + +Pass the rows as a query argument (a list of dicts / array of objects is sent as JSON) and let SQL unnest them; declare the column types so the table gets a real schema: + +\`\`\`python +# pipeline +# on schedule +import wmill + +def main(): + rows = fetch_charges() # list[dict] + lake = wmill.ducklake() + lake.query(""" + CREATE OR REPLACE TABLE stripe_charges AS + SELECT unnest(from_json($rows, '[{"id":"VARCHAR","amount":"BIGINT","created":"BIGINT"}]'), recursive := true) + """, rows=rows).fetch() +\`\`\` + +\`\`\`ts +// pipeline +// on schedule +import * as wmill from "windmill-client" + +export async function main() { + const rows = await fetchCharges() + const lake = wmill.ducklake() + await lake\`CREATE OR REPLACE TABLE stripe_charges AS + SELECT unnest(from_json(\${rows}, '[{"id":"VARCHAR","amount":"BIGINT","created":"BIGINT"}]'), recursive := true)\`.fetch() +} +\`\`\` + +- Use \`INSERT INTO <table> SELECT ...\` instead of \`CREATE OR REPLACE\` to append (an incremental pull), with a one-time \`CREATE TABLE IF NOT EXISTS\` first. +- Assign the client to a variable (\`lake = wmill.ducklake()\`) and keep the SQL a **string literal** (Python) or a template without \`sql.raw\` (TS): that is what lets the graph record the node's write to \`ducklake://main/<table>\`. A chained \`wmill.ducklake().query(...)\` or SQL built in a variable records no output, so the downstream edge never forms. +- \`wmill.ducklake("<name>")\` targets a non-default catalog; \`wmill.datatable("<name>")\` writes a Postgres data table the same way (Python \`db.query(sql, *args)\` with \`$1\` placeholders, TS the same template form) — use it only when the data belongs in Postgres (see above). +- The downstream node triggers on the table itself: \`-- on ducklake://main/stripe_charges\`. + ## Storage prerequisites A DuckLake pipeline only runs once the workspace has **object storage** (S3 / Azure Blob / GCS) **and a DuckLake catalog** configured — DuckLake tables and \`s3://\` assets can't be materialized or read without it. Check which DuckLake catalogs the workspace has before you build. @@ -7926,7 +8182,7 @@ The key must be a **string literal** — the graph parser is static and cannot f ## Materialize (the managed output) -> **A MANAGED \`// materialize\` is DuckDB-only**, and its target must be a DuckLake table (\`ducklake://<name>/<table>\`). Deploy **rejects** a \`ducklake://\` \`// materialize\` on any other language (\`python3\`, \`bun\`, \`postgresql\`). For a non-DuckDB node writing the lake, do **not** use \`// materialize\` — write the output via the SDK (\`wmill.writeS3File(...)\`, ducklake helpers, …) and let it be inferred. Use \`duckdb\` when a node should materialize a DuckLake table. +> **A MANAGED \`// materialize\` is DuckDB-only**, and its target must be a DuckLake table (\`ducklake://<name>/<table>\`). Deploy **rejects** a \`ducklake://\` \`// materialize\` on any other language (\`python3\`, \`bun\`, \`postgresql\`). For a non-DuckDB node writing the lake, do **not** use \`// materialize\` — write the table itself with \`wmill.ducklake()\` (see "Ingesting from Python / TypeScript") and let the output be inferred. Use \`duckdb\` when a node should materialize a DuckLake table. > > The one target ANY language may declare (except a dbt script, whose writes come from its manifest) is a **warehouse relation**: \`// materialize manual dbt://<warehouse>/<schema>/<name>\`, where \`<warehouse>\` is a warehouse the workspace configures under Settings → dbt. \`manual\` is the only mode it has — nothing generates warehouse DDL, so the node issues its own write (a postgresql \`CREATE TABLE\` / \`INSERT\`, an SDK load, …) and the annotation records the outcome. Use it on an ingestion node whose output a dbt project reads as a \`source\`: the declared relation and the dbt model land on ONE graph node, and a downstream \`// on dbt://<warehouse>/<schema>/<name>\` fires when the ingestion node completes. @@ -7990,6 +8246,139 @@ Node \`f/sales/orders_daily\` (runs when \`orders\` is produced, writes a rollup SELECT date_trunc('day', ts) AS day, count(*) AS n FROM ducklake.main.orders GROUP BY 1 \`\`\` +`, + "datatables": `--- +name: datatables +description: MUST use when changing a data table's schema, writing or running its migrations, or working with its roles and permissions. +--- + +# Data tables: schema changes, migrations and permissions + +A data table is a PostgreSQL database managed by Windmill and shared by the whole workspace: scripts, flows and apps reach it by name, \`main\` being the default. It is configured in the workspace settings (Data Tables), never created by SQL. + +## Changing the schema + +A data table with migrations enabled keeps its schema as an ordered list of versioned SQL migrations, each an \`up\` and an optional \`down\`. That list is what git sync and a workspace merge carry, and what rebuilds the schema in another workspace. So first find out whether migrations are enabled on the data table: + +- **Enabled**: make every schema change (CREATE, ALTER, DROP, anything but row data) as a new migration. A change made with plain SQL exists in that one database only, and the history no longer describes it. +- **Not enabled**: schema changes are plain SQL. Enabling migrations is a workspace admin's decision, made in the Data Tables settings, not a step to take on the way to something else. + +Writing a migration: + +- Wrap the statements in \`BEGIN; ... END;\` so it applies atomically. Leave the frame out only for a statement that cannot run in a transaction, such as \`CREATE INDEX CONCURRENTLY\`: such a migration can fail half applied. +- Give it a \`down\` that undoes the \`up\` whenever the change is reversible. Without one it cannot be rolled back. +- Declare the schemas it changes on a leading line of its \`up\`, \`-- schemas sales, billing\`, and qualify every name with its schema (\`sales.orders\`). A migration waits only on earlier migrations whose schemas overlap its own. One that declares none applies to the whole database and every later migration waits for it, so leave the line out only for a change that really spans the database, such as an extension. +- Migrations apply oldest first. One that is applied is not edited: correct it with a new migration. +- Row data is not schema. Insert, update and delete rows with plain SQL, migrations or not. + +\`wmill datatable migrate new <name>\` scaffolds \`migrations/datatable/<datatable>/<timestamp>_<name>.up.sql\` and \`.down.sql\`, \`wmill datatable migrate up\` pushes the local files and applies what is pending, \`wmill datatable migrate down\` rolls back the most recent one and \`wmill datatable migrate status\` lists them. All take \`-d <datatable>\` and default to \`main\`. \`migrate new --schemas sales,billing\` writes the \`-- schemas\` line, and \`migrate up --schema sales\` applies only the pending migrations declaring that schema. + +## A migration is not a draft + +A migration is saved to the workspace and changes the database as soon as it is applied, for everything that reads those tables. To try a schema out without touching tables already in use: + +- put the new tables in a schema of their own, created by the same migration (\`CREATE SCHEMA IF NOT EXISTS\`), and point what you are building at it. A raw app names its schema in its \`data\` config, which is why a new app gets a new schema by default; +- or work in a workspace fork whose data table was cloned when the fork was created ("Clone schema only" or "Clone schema and data"): migrations applied there change that copy alone, and reach the parent workspace when the fork is merged. A fork that kept the original data table points at the parent's database, so a migration applied in it changes the parent's tables at once. + +Altering or dropping a table other scripts or apps use is neither of those: say what depends on it before doing it. + +## Roles and permissions + +Data table roles are a self-hosted Enterprise Edition feature, for data tables on managed Postgres (the instance database or the external managed instance). Without them, and always on a data table backed by a Postgres resource, everyone who can use the data table reaches all of it: there is no per-user, per-schema or per-row access to promise. + +A data table under roles is reached as a Postgres role, and Postgres enforces what that role was granted: + +- roles are assigned, per data table, to users, groups or folders. \`admin\` is the connection the data table had before roles: it owns the existing objects and ignores grants; +- a connection either names a role (\`wmill.datatable('main', { role: 'analyst' })\`, \`role='analyst'\` in Python, \`datatable://main?role=analyst\`) and holds that role alone, or names none and is resolved from the data table's default role; +- \`permission denied\` means the role in use lacks a grant. Say which role and which object: the grant is a data table admin's to give, in the roles drawer of the Database Manager. Do not switch to \`admin\` to get past it; +- a migration runs as the role its SQL declares on its first line, \`-- role <name>\`, the same one in its \`down\`. One that declares none runs as \`admin\`, which only those who may use \`admin\` can do. + +Read the Permissions section of https://www.windmill.dev/docs/core_concepts/persistent_storage/data_tables before designing who reaches what: it covers tenants, grants, the default role and the roles a connection that names none ends up holding, rows that differ per viewer through row-level security, and how forks and raw apps behave under roles. +`, + "workspace-settings": `--- +name: workspace-settings +description: MUST use when reading or changing workspace settings, or the settings.yaml file \`wmill sync\` keeps. +--- + +# Workspace settings + +Everything an admin sets on the Workspace settings page is one document: a mapping of top-level +keys, the same layout as the \`settings.yaml\` file \`wmill sync\` keeps. Only a workspace admin can +read or change it. + +## Applying a document + +- A partial document changes only the keys it states; every key it omits is left as it is. +- Each key is replaced whole, so read its current value and send it back edited: a nested object + given with one field replaces the stored object with that one field. +- A key set to \`null\` clears that setting; an on/off switch cleared this way reads as \`false\`. +- Each setting is written through the same path the settings page uses, with the same validation + and audit log. The writes are not one transaction: when one fails the apply stops, and the + error says what was already written. +- A dry run reports the changes, as \`before\` / \`after\` per key, without writing anything. +- \`name\` is never applied: rename a workspace on the settings page. \`color\` is applied only when + set to a value, so \`null\` does not clear it. +- A key the server does not know is ignored and named in the warnings: check them, since a typo + otherwise reads as "nothing to change". +- A setting this edition does not offer (Enterprise only) is refused, by the dry run too. + +## Secrets + +\`slack_oauth_client_secret\` is the one secret. A read shows \`__SENSITIVE_AND_UNCHANGED__\` in place +of a set secret; sending that placeholder back keeps the stored value. A value starting with +\`$encrypted:\` is decrypted with the workspace key, and one encrypted with another workspace's key +is left unchanged with a warning; any other value is taken as plaintext. Never +write a secret you were not given: keep the placeholder. + +## Keys + +| Key | Value | +|---|---| +| \`auto_invite\` | \`{ enabled, mode: invite \\| add, operator, instance_groups?, instance_groups_roles? }\`. The instance groups are managed only when \`instance_groups\` is stated; clearing a group removes the members it added. | +| \`error_handler\` / \`success_handler\` | \`{ path, extra_args?, muted_on_cancel?, muted_on_user_path? }\`, \`path\` being \`script/<path>\` or \`flow/<path>\`. | +| \`error_handler_fallback_to_instance_alerts\` | Report failures to the instance critical alert channels when no error handler is set. | +| \`webhook\` | URL POSTed a JSON event on every change to the workspace's items. | +| \`ai_config\` | Providers, default and completion models, custom prompts, \`copilot_disabled\`. | +| \`large_file_storage\` | Workspace object storage: \`{ type, s3_resource_path \\| azure_blob_resource_path \\| gcs_resource_path, public_resource?, secondary_storage?, advanced_permissions? }\`. | +| \`git_sync\` | \`{ repositories: [...] }\`, each with \`git_repo_resource_path\`, \`script_path\` and \`settings\` (include/exclude paths and types). Server-owned fields (webhook secrets, sync state, credentials) are never read nor written. | +| \`datatable\` | \`{ datatables: { <name>: { database: { resource_type, resource_path? } } } }\`. Role permissions are \`datatable_permissions\`. | +| \`datatable_permissions\` | \`{ <data table>: { default_role, roles: { <role>: [tenants] } } }\`: who may connect to each data table as which role. Tenants are \`u/<user>\`, \`g/<group>\`, \`f/<folder>\` or \`*\`; \`admin\` is always a role, and \`default_role: null\` means no default. A data table the value omits is no longer under roles. Only a data table on a cluster Windmill manages can be. | +| \`protection_rules\` | \`{ <rule name>: { rules: [...], bypass_groups: [...], bypass_users: [...] } }\`, rules among \`DisableDirectDeployment\`, \`DisableWorkspaceForking\`, \`RestrictDeployToDeployers\`, \`RestrictAnonymousAppDeployment\`, \`RestrictPublicRunSharing\`, \`RestrictGuestAppDeployment\`, \`RequireIsolatedForks\`. A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. | +| \`ducklake\` | \`{ ducklakes: { <name>: { catalog, storage, ... } } }\`. | +| \`dbt_warehouses\` | dbt warehouse connections. | +| \`default_app\` | Path of the app shown as the workspace home. | +| \`default_scripts\` | \`{ order?, hidden?, default_script_content? }\` for the script language picker. | +| \`deploy_ui\` | \`{ include_path?, include_type? }\`: what the deploy-to-workspace UI offers. | +| \`operator_settings\` | What operators see and do: page visibility flags (\`runs\`, \`schedules\`, \`resources\`, \`variables\`, \`assets\`, \`audit_logs\`, \`groups\`, \`folders\`, \`workers\`, \`triggers\`) and write rights (\`manage_schedules\`, \`manage_triggers\`, \`builder_flows\`, \`builder_apps\`). A write right the value omits keeps its stored value. | +| \`mute_critical_alerts\` | Mute the workspace's critical alerts. | +| \`slack_team_id\`, \`slack_name\` | Read only: set by connecting Slack on the settings page. | +| \`slack_command_script\` / \`teams_command_script\` | Script or flow handling the Slack / Teams command. | +| \`slack_oauth_client_id\` / \`slack_oauth_client_secret\` | The workspace's own Slack OAuth app. Clearing either removes both. | +| \`public_app_execution_limit_per_minute\` | Rate limit for public apps, \`null\` for none. | +| \`guest_access_enabled\`, \`guest_jwt_public_key\`, \`guest_jwt_jwks_url\` | Guest access to public apps and the key that signs guest JWTs. | +| \`add_admins_and_developers_to_forks\` | Add the workspace's admins and developers to each fork. | +| \`color\` | Workspace color, \`#rrggbb\`. | + +## From the command line + +\`wmill workspace get-settings\` prints the document (\`--encrypted\` for secrets encrypted with the +workspace key, \`--json\` for JSON). \`wmill workspace apply-settings <file>\` applies a partial +document from a YAML or JSON file: it shows the changes and asks before writing (\`--dry-run\` to +only show them, \`-y\` to skip the question, \`--replace\` to clear what the file omits). + +## In a synced repository + +With \`includeSettings: true\` in \`wmill.yaml\`, \`wmill sync pull\` writes the document to +\`settings.yaml\`, secrets encrypted with the workspace key (plaintext only with \`plainSecrets\`), and +\`wmill sync push\` applies it. Unlike a partial apply, a push treats the file as the whole +document: a setting the file omits is cleared, except \`operator_settings\`, \`color\`, the auto-invite +instance groups, and the keys \`ducklake\`, \`dbt_warehouses\`, \`deploy_ui\`, \`teams_command_script\`, +\`public_app_execution_limit_per_minute\`, \`guest_access_enabled\`, \`guest_jwt_public_key\`, +\`guest_jwt_jwks_url\`, \`error_handler_fallback_to_instance_alerts\` and +\`add_admins_and_developers_to_forks\`, which are managed only when the file states them. +\`datatable_permissions\` is pushed only with \`includeDatatablePermissions: true\` (or +\`--include-datatable-permissions\`). A push ignores \`protection_rules\`: \`protection-rules.yaml\` and +\`wmill protection-rules push\` sync them. `, "cli-commands": `--- name: cli-commands @@ -8028,7 +8417,7 @@ app related commands - \`app dev [app_folder:string]\` - Start a development server for building apps with live reload and hot module replacement - \`--port <port:number>\` - Port to run the dev server on (will find next available port if occupied) - \`--host <host:string>\` - Host to bind the dev server to - - \`--entry <entry:string>\` - Entry point file (default: index.ts for Svelte/Vue, index.tsx otherwise) + - \`--entry <entry:string>\` - Entry point file (default: index.ts for Svelte, index.tsx otherwise) - \`--no-open\` - Don't automatically open the browser - \`--recording\` - Frame the app in a shell with a Record button, to capture a replayable session recording of the app under development - \`app lint [app_folder:string]\` - Lint a raw app folder to validate structure and buildability @@ -8039,7 +8428,7 @@ app related commands - \`app new\` - create a new raw app from a template - \`--summary <summary:string>\` - App summary (short description). Skips the prompt when provided. Triggers non-interactive mode. - \`--path <path:string>\` - App path (e.g., f/folder/my_app or u/username/my_app). Skips the prompt when provided. Triggers non-interactive mode. - - \`--framework <framework:string>\` - Framework template: react19 | react18 | svelte5 | vue. Skips the prompt when provided. Triggers non-interactive mode. + - \`--framework <framework:string>\` - Framework template: react19 | react18 | svelte5. Skips the prompt when provided. Triggers non-interactive mode. - \`--datatable <datatable:string>\` - Datatable to wire up. Without this flag in non-interactive mode, no datatable is configured. - \`--schema <schema:string>\` - Schema to use with --datatable. If it doesn't exist yet, a sql_to_apply/ migration (CREATE SCHEMA IF NOT EXISTS) is written for it. - \`--overwrite\` - Overwrite the target directory if it already exists, without prompting. @@ -8082,8 +8471,10 @@ datatable related commands - \`datatable migrate\` - manage datatable migrations - \`datatable migrate new <name:string>\` - scaffold a new migration (.up.sql / .down.sql files) - \`-d --datatable <datatable:string>\` - Target datatable (default: main) + - \`-s --schemas <schemas:string>\` - Comma-separated schemas the migration changes, written as its \`-- schemas\` line. Without it the migration applies to the whole database and every later migration waits for it - \`datatable migrate up\` - apply all pending migrations to the main datatable (or one via --datatable) - \`-d --datatable <datatable:string>\` - Target datatable (default: main) + - \`--schema <schema:string>\` - Apply only the pending migrations that declare this schema; refused while an earlier overlapping migration is pending - \`datatable migrate down\` - roll back the most recent migration on the main datatable (or one via --datatable) - \`-d --datatable <datatable:string>\` - Target datatable (default: main) - \`datatable migrate status\` - show applied and pending migrations on the main datatable (or one via --datatable) @@ -8179,6 +8570,7 @@ flow related commands - \`--remote\` - Use deployed workspace scripts for PathScript steps instead of local files. - \`--step <step_id:string>\` - Run only the named step instead of the whole flow. Honors --data as the step's args and --remote / local-PathScript resolution the same way the full-flow preview does. - \`--tag <tag:string>\` - Override the worker tag the preview is dispatched to (e.g. to route it to dev workers instead of the flow's default tag). + - \`--on-behalf-of <identity:string>\` - Run the preview as this user or group (an email, u/<username> or g/<group>) instead of yourself, e.g. to reproduce a run_on_behalf_of identity. Requires being an admin or a member of wm_deployers. - \`flow new <flow_path:string>\` - create a new empty flow - \`--summary <summary:string>\` - flow summary - \`--description <description:string>\` - flow description @@ -8577,6 +8969,7 @@ script related commands - \`-d --data <data:file>\` - Inputs specified as a JSON string or a file using @<filename> or stdin using @-. A resource argument is the bare string $res:<path> as its whole value, and a variable argument is the bare string $var:<path> — not an object wrapper keyed on $res/$var, and not a plain path. - \`-s --silent\` - Do not output anything other than the final output. Useful for scripting. - \`--tag <tag:string>\` - Override the worker tag the preview is dispatched to (e.g. to route it to dev workers instead of the script's default tag). + - \`--on-behalf-of <identity:string>\` - Run the preview as this user or group (an email, u/<username> or g/<group>) instead of yourself, e.g. to reproduce a run_on_behalf_of identity. Requires being an admin or a member of wm_deployers. - \`script new <path:file> <language:string>\` - create a new script - \`--summary <summary:string>\` - script summary - \`--description <description:string>\` - script description @@ -8614,6 +9007,7 @@ sync local with a remote workspaces or the opposite (push or pull) - \`--include-users\` - Include syncing users - \`--include-groups\` - Include syncing groups - \`--include-settings\` - Include syncing workspace settings + - \`--include-datatable-permissions\` - With --include-settings, also sync who may connect to each data table as which role - \`--include-key\` - Include workspace encryption key - \`--keep-deleted\` - Do not delete local files for items that no longer exist on the remote workspace. Only adds and updates. - \`--skip-branch-validation\` - Skip git branch validation and prompts @@ -8645,6 +9039,7 @@ sync local with a remote workspaces or the opposite (push or pull) - \`--include-users\` - Include syncing users - \`--include-groups\` - Include syncing groups - \`--include-settings\` - Include syncing workspace settings + - \`--include-datatable-permissions\` - With --include-settings, also sync who may connect to each data table as which role - \`--include-key\` - Include workspace encryption key - \`--skip-reencrypt-on-key-change\` - When the pushed encryption key differs from the remote, do NOT re-encrypt existing remote secrets. Only safe if they are already encrypted with the new key (e.g. workspace/instance migration). Default is to re-encrypt. - \`--keep-deleted\` - Do not delete remote items that no longer exist locally. Only adds and updates. @@ -8838,6 +9233,13 @@ Arguments (omit both to be prompted interactively): - \`--team-id <team_id:string>\` - Slack team id - \`--team-name <team_name:string>\` - Slack team name - \`workspace disconnect-slack\` - Clear slack_team_id / slack_name on the active workspace (marks the workspace as disconnected). Does NOT remove the bot token variable/resource/folder/group — delete those from the local sync folder and run 'wmill sync push' to tear them down. Does NOT remove the workspace-level OAuth override — set slack_oauth_client_id/_secret to '' in settings.yaml and push. +- \`workspace get-settings\` - Print the active workspace's settings in the layout of the settings.yaml that 'wmill sync' writes. Secrets show as __SENSITIVE_AND_UNCHANGED__ unless --encrypted. Admin only. + - \`--encrypted\` - Write secrets encrypted with the workspace key, as 'wmill sync pull' does + - \`--json\` - Output as JSON +- \`workspace apply-settings <file:string>\` - Apply a settings document (YAML or JSON, in the layout of settings.yaml) to the active workspace. Only the settings the file states are changed, unless --replace; a setting set to null is cleared. A secret left as __SENSITIVE_AND_UNCHANGED__ keeps its value. Shows the changes and asks before applying. Admin only. + - \`--dry-run\` - Only show the changes + - \`--replace\` - Also clear the settings the file omits, as 'wmill sync push' does + - \`-y --yes\` - Apply without asking diff --git a/cli/src/types.ts b/cli/src/types.ts index 866b2be21e..3ae2b8d6a4 100644 --- a/cli/src/types.ts +++ b/cli/src/types.ts @@ -6,7 +6,7 @@ import { sep as SEP } from "node:path"; import { stringify as yamlStringify } from "yaml"; import { yamlParseContent } from "./utils/yaml.ts"; import { isDbtDescriptorPath } from "./utils/resource_folders.ts"; -import { pushApp } from "./commands/app/app.ts"; +import { pushApp, pushAppCustomPath } from "./commands/app/app.ts"; import { pushFolder } from "./commands/folder/folder.ts"; import { pushFlow } from "./commands/flow/flow.ts"; import { pushResource } from "./commands/resource/resource.ts"; @@ -187,6 +187,8 @@ export interface PushObjOptions { wsSpecific?: boolean; /** encryption_key push: non-interactive flag and explicit re-encryption choice */ keyPushOpts?: PushWorkspaceKeyOptions; + /** settings push: whether settings.yaml manages the data tables' roles */ + includeDatatablePermissions?: boolean; /** TypeScript runtime a bare `.ts` denotes, for raw-app runnables */ defaultTs?: "bun" | "deno"; /** schedule push into a fork: the file's `enabled` is the parent's */ @@ -218,6 +220,7 @@ export async function pushObj( permissionedAsContext, wsSpecific, keyPushOpts, + includeDatatablePermissions, defaultTs, enabledOwnedByParent, } = opts; @@ -228,13 +231,16 @@ export async function pushObj( if (!appName) { throw new Error(`Could not extract app name from path: ${p}`); } - await pushApp(workspace, appName, buildFolderPath(appName, "app"), message, permissionedAsContext); + // A sync carries the custom path in its own workspace-specific file. + await pushApp(workspace, appName, buildFolderPath(appName, "app"), message, permissionedAsContext, false); } else if (typeEnding === "raw_app") { const rawAppName = extractResourceName(p, "raw_app"); if (!rawAppName) { throw new Error(`Could not extract raw app name from path: ${p}`); } - await pushRawApp(workspace, rawAppName, buildFolderPath(rawAppName, "raw_app"), message, defaultTs, permissionedAsContext); + await pushRawApp(workspace, rawAppName, buildFolderPath(rawAppName, "raw_app"), message, defaultTs, permissionedAsContext, false); + } else if (typeEnding === "custom_path") { + await pushAppCustomPath(workspace, removeType(p, "custom_path"), newObj); } else if (typeEnding === "folder") { await pushFolder(workspace, p, befObj, newObj); } else if (typeEnding === "variable") { @@ -248,7 +254,7 @@ export async function pushObj( } else if (typeEnding === "resource") { if (!alreadySynced.includes(p)) { alreadySynced.push(p); - await pushResource(workspace, p, befObj, newObj, originalLocalPath || p, wsSpecific, true); + await pushResource(workspace, p, befObj, newObj, originalLocalPath || p, wsSpecific, true, permissionedAsContext); } } else if (typeEnding === "resource-type") { await pushResourceType(workspace, p, befObj, newObj); @@ -285,7 +291,9 @@ export async function pushObj( } else if (typeEnding === "workspace_dependencies") { await pushWorkspaceDependencies(workspace, p, befObj, newObj); } else if (typeEnding === "settings") { - await pushWorkspaceSettings(workspace, p, befObj, newObj); + await pushWorkspaceSettings(workspace, p, befObj, newObj, { + includeDatatablePermissions, + }); } else if (typeEnding === "encryption_key") { await pushWorkspaceKey(workspace, p, befObj, newObj, keyPushOpts); } else { @@ -353,6 +361,7 @@ export function getTypeStrFromPath( | "folder" | "app" | "raw_app" + | "custom_path" | "schedule" | "http_trigger" | "websocket_trigger" @@ -447,6 +456,7 @@ export function getTypeStrFromPath( typeEnding === "resource" || typeEnding === "resource-type" || typeEnding === "app" || + typeEnding === "custom_path" || typeEnding === "schedule" || typeEnding === "http_trigger" || typeEnding === "websocket_trigger" || diff --git a/cli/src/utils/git.ts b/cli/src/utils/git.ts index 354e15c36e..29796c2f7c 100644 --- a/cli/src/utils/git.ts +++ b/cli/src/utils/git.ts @@ -388,10 +388,12 @@ export function gitSyncIncludePattern( switch (pathType) { case "flow": return `${path}.flow/*,${path}__flow/*`; + // An app's custom path is a sibling workspace-specific file: the export's + // `<path>.custom_path.*` and the checkout's `<path>.<workspace>.custom_path.*`. case "app": - return `${path}.app/*,${path}__app/*`; + return `${path}.app/*,${path}__app/*,${path}.custom_path.*,${path}.*.custom_path.*`; case "raw_app": - return `${path}.raw_app/**,${path}__raw_app/**`; + return `${path}.raw_app/**,${path}__raw_app/**,${path}.custom_path.*,${path}.*.custom_path.*`; case "folder": return `${path}/folder.meta.*`; case "resourcetype": diff --git a/cli/src/utils/job_polling.ts b/cli/src/utils/job_polling.ts index bf72c2bfe5..6cc1631747 100644 --- a/cli/src/utils/job_polling.ts +++ b/cli/src/utils/job_polling.ts @@ -135,8 +135,10 @@ export async function pollJobWithQueueLogging( ); } + // Errors back off to the slow interval: at the fast one, the consecutive + // error budget would be spent on a ~1s blip. const delayMs = - Date.now() - startedAt < fastPollDurationMs + consecutiveErrors === 0 && Date.now() - startedAt < fastPollDurationMs ? fastPollIntervalMs : slowPollIntervalMs; await new Promise((resolve) => setTimeout(resolve, delayMs)); diff --git a/cli/src/utils/script_common.ts b/cli/src/utils/script_common.ts index 611268c27c..e3deabb6a7 100644 --- a/cli/src/utils/script_common.ts +++ b/cli/src/utils/script_common.ts @@ -189,6 +189,8 @@ const LANG_ANNOTATIONS: Partial<Record<ScriptLanguage, string[]>> = { "py311", "py312", "py313", + "py314", + "py315", "sandbox", ], bun: ["npm", "nodejs", "native", "nobundling", "sandbox"], @@ -208,7 +210,7 @@ const LANG_ANNOTATIONS: Partial<Record<ScriptLanguage, string[]>> = { * * `# py: <specifier>` is the exception the macro does not cover: the python * import parser reads it directly (`windmill-parser-py-imports`, alongside the - * `py310`..`py313` flags) to pick the interpreter, which changes what resolves. + * `py310`..`py315` flags) to pick the interpreter, which changes what resolves. */ export function hasLockAffectingAnnotation( scriptContent: string, diff --git a/cli/test/app_isolation_unit.test.ts b/cli/test/app_isolation_unit.test.ts new file mode 100644 index 0000000000..201c4a52a4 --- /dev/null +++ b/cli/test/app_isolation_unit.test.ts @@ -0,0 +1,60 @@ +import { expect, test } from "bun:test"; +import { + finalizeDerivedPolicy, + isolationUpToDate, + markIsolationFromPolicy, + statedIsolation, +} from "../src/commands/app/app.ts"; + +function pushed(file: any, deployed: any, rawApp = true) { + const policy = { ...deployed }; + finalizeDerivedPolicy(policy, "publisher", statedIsolation(file, rawApp), rawApp); + return policy; +} + +test("a pull writes isolation only when it is on, and a push deploys what was pulled", () => { + const off: any = { policy: { sandbox: false, frontend_sdk_scopes: ["jobs:run"] } }; + markIsolationFromPolicy(off, true); + expect("sandbox" in off).toBe(false); + expect("frontend_api" in off).toBe(false); + + const on: any = { policy: { sandbox: true, frontend_sdk_scopes: ["jobs:run"] } }; + markIsolationFromPolicy(on, true); + expect(on.sandbox).toBe(true); + expect(on.frontend_api).toEqual(["jobs:run"]); + // Into a workspace where the app does not exist yet. + const fresh = pushed(on, undefined); + expect(fresh.sandbox).toBe(true); + expect(fresh.frontend_sdk_scopes).toEqual(["jobs:run"]); +}); + +test("the file wins when it states sandbox, the deployed policy carries over when it does not", () => { + const deployed = { sandbox: true, frontend_sdk_scopes: ["jobs:run"] }; + + const silent = pushed({}, deployed); + expect(silent.sandbox).toBe(true); + expect(silent.frontend_sdk_scopes).toEqual(["jobs:run"]); + expect(isolationUpToDate(statedIsolation({}, true), deployed, true)).toBe(true); + + // A file with the key states the scopes too: none here. + const narrowed = pushed({ sandbox: true }, deployed); + expect(narrowed.sandbox).toBe(true); + expect(narrowed.frontend_sdk_scopes).toBeUndefined(); + expect(isolationUpToDate(statedIsolation({ sandbox: true }, true), deployed, true)).toBe(false); + + const opened = pushed({ sandbox: false }, deployed); + expect(opened.sandbox).toBe(false); + expect(opened.frontend_sdk_scopes).toBeUndefined(); +}); + +test("scopes are refused without sandbox, outside the allowlist, or repeated", () => { + expect(() => statedIsolation({ frontend_api: ["jobs:run"] }, true)).toThrow("requires 'sandbox: true'"); + expect(() => statedIsolation({ sandbox: false, frontend_api: ["jobs:run"] }, true)).toThrow( + "requires 'sandbox: true'", + ); + expect(() => statedIsolation({ sandbox: true, frontend_api: ["apps:write"] }, true)).toThrow("Invalid"); + expect(() => statedIsolation({ sandbox: true, frontend_api: ["jobs:run", "jobs:run"] }, true)).toThrow( + "Duplicate", + ); + expect(() => statedIsolation({ sandbox: true, frontend_api: ["jobs:run"] }, false)).toThrow("full-code"); +}); diff --git a/cli/test/app_lint_viewer_identity_unit.test.ts b/cli/test/app_lint_viewer_identity_unit.test.ts new file mode 100644 index 0000000000..f328ffe4e2 --- /dev/null +++ b/cli/test/app_lint_viewer_identity_unit.test.ts @@ -0,0 +1,24 @@ +import { expect, test } from "bun:test"; +// app.ts first: it is the entry the CLI loads lint.ts through, and loading +// lint.ts ahead of it trips their import cycle. +import "../src/commands/app/app.ts"; +import { viewerIdentityInputWarnings } from "../src/commands/app/lint.ts"; + +const sql = (content: string, fields?: Record<string, any>) => ({ + type: "inline", + inlineScript: { language: "duckdb", content }, + ...(fields ? { fields } : {}), +}); + +test("app lint warns on a SQL viewer-identity argument the server does not fill", async () => { + const content = + "-- $username (text)\n-- $limit (int)\nSELECT * FROM orders WHERE owner = $username LIMIT $limit"; + + const warnings = await viewerIdentityInputWarnings({ + open: sql(content), + filled: sql(content, { username: { ctx: "username" } }), + }); + + expect(warnings).toHaveLength(1); + expect(warnings[0]).toContain("Runnable 'open': argument 'username'"); +}); diff --git a/cli/test/deploy_on_behalf_of_unit.test.ts b/cli/test/deploy_on_behalf_of_unit.test.ts index 7e21b24832..a0db663589 100644 --- a/cli/test/deploy_on_behalf_of_unit.test.ts +++ b/cli/test/deploy_on_behalf_of_unit.test.ts @@ -105,3 +105,28 @@ test("deployItem: never sends the source workspace's on_behalf_of", async () => expect("on_behalf_of" in JSON.parse(JSON.stringify(identity))).toBe(false); } }); + +// An agent carries its principal inside its resource value, and is handed the chosen one as a +// principal. The source's must never be sent: without a choice the key is dropped, leaving the +// backend to make the agent the deployer's. +test("deployItem: an agent takes the chosen principal, never the source's", async () => { + const captured: any[] = []; + const provider = { + existsResource: async () => true, + getResource: async () => ({ + path: "f/x/agent", + resource_type: "ai_agent", + description: "", + value: { system_prompt: "hi", on_behalf_of: "u/alice" }, + }), + updateResource: async (p: any) => void captured.push(p.requestBody), + } as any; + + await deployItem(provider, "resource" as any, "f/x/agent", "src", "dst", "u/bob"); + await deployItem(provider, "resource" as any, "f/x/agent", "src", "dst", undefined); + + expect(captured[0].value).toEqual({ system_prompt: "hi", on_behalf_of: "u/bob" }); + expect(captured[0].preserve_on_behalf_of).toBe(true); + expect(captured[1].value).toEqual({ system_prompt: "hi" }); + expect(captured[1].preserve_on_behalf_of).toBe(false); +}); diff --git a/cli/test/dev_server.test.ts b/cli/test/dev_server.test.ts index 558fea0241..b4f630b3fa 100644 --- a/cli/test/dev_server.test.ts +++ b/cli/test/dev_server.test.ts @@ -82,6 +82,9 @@ test( `summary: "test"\ndescription: ""\nlock: ""\nschema:\n $schema: "https://json-schema.org/draft/2020-12/schema"\n type: object\n properties: {}\n required: []\n`, "utf-8", ); + const moduleDir = join(scriptDir, "hello__mod"); + await mkdir(moduleDir); + await writeFile(join(moduleDir, "query.gql"), "query { __typename }\n"); // Push the script so the workspace has content const pushResult = await backend.runCLICommand( @@ -94,6 +97,13 @@ test( } expect(pushResult.code).toEqual(0); + // Folder layout: the script's content is its own module folder's `script.*` + const folderModuleDir = join(scriptDir, "folder__mod"); + await mkdir(folderModuleDir); + await writeFile(join(folderModuleDir, "script.ts"), 'export function main() { return "folder"; }\n'); + await writeFile(join(folderModuleDir, "script.yaml"), "summary: \"\"\ndescription: \"\"\nlock: \"\"\n"); + await writeFile(join(folderModuleDir, "query.gql"), "query { __typename }\n"); + // Build the CLI command for `wmill dev` const cliMainPath = getCLIMainPath(); const args = [ @@ -178,14 +188,13 @@ test( expect(ws.readyState).toEqual(WebSocket.OPEN); - // Set up a promise to receive the next WebSocket message const isWindows = process.platform === "win32"; - const messagePromise = new Promise<any>((resolve, reject) => { + const nextMessage = () => new Promise<any>((resolve, reject) => { const timeout = setTimeout( () => reject(new Error("WebSocket message timeout")), isWindows ? 30000 : 10000, ); - ws!.on("message", (data) => { + ws!.once("message", (data) => { clearTimeout(timeout); try { resolve(JSON.parse(data.toString())); @@ -195,6 +204,21 @@ test( }); }); + const initialMessage = nextMessage(); + ws.send(JSON.stringify({ type: "loadWmPath", path: "f/test/hello" })); + expect((await initialMessage).modules["query.gql"]).toEqual({ + content: "query { __typename }\n", + language: "graphql", + }); + + const folderMessage = nextMessage(); + ws.send(JSON.stringify({ type: "loadWmPath", path: "f/test/folder" })); + const folder = await folderMessage; + expect(folder.content).toContain("folder"); + expect(Object.keys(folder.modules)).toEqual(["query.gql"]); + + const messagePromise = nextMessage(); + // Modify the script file on disk // Windows fs.watch() needs more time to initialize with recursive: true await new Promise((r) => setTimeout(r, isWindows ? 2000 : 300)); @@ -212,6 +236,14 @@ test( expect(message.content).toContain("modified"); expect(message.path).toContain("f/test/hello"); expect(message.language).toBeTruthy(); + expect(message.modules["query.gql"].content).toEqual("query { __typename }\n"); + + const moduleMessage = nextMessage(); + await writeFile(join(moduleDir, "query.gql"), "query Updated { __typename }\n"); + const updated = await moduleMessage; + expect(updated.path).toEqual("f/test/hello"); + expect(updated.content).toContain("modified"); + expect(updated.modules["query.gql"].content).toEqual("query Updated { __typename }\n"); } finally { if (ws) { ws.close(); diff --git a/cli/test/git_unit.test.ts b/cli/test/git_unit.test.ts index 92d44e09d9..2cce1617e2 100644 --- a/cli/test/git_unit.test.ts +++ b/cli/test/git_unit.test.ts @@ -364,9 +364,11 @@ describe("gitSyncIncludePattern", () => { }); test("flow/app expand to dotted + __ folder patterns", () => { expect(gitSyncIncludePattern("flow", "f/x")).toBe("f/x.flow/*,f/x__flow/*"); - expect(gitSyncIncludePattern("app", "f/x")).toBe("f/x.app/*,f/x__app/*"); + expect(gitSyncIncludePattern("app", "f/x")).toBe( + "f/x.app/*,f/x__app/*,f/x.custom_path.*,f/x.*.custom_path.*" + ); expect(gitSyncIncludePattern("raw_app", "f/x")).toBe( - "f/x.raw_app/**,f/x__raw_app/**" + "f/x.raw_app/**,f/x__raw_app/**,f/x.custom_path.*,f/x.*.custom_path.*" ); }); test("folder and triggers", () => { diff --git a/cli/test/init_no_git_sync.test.ts b/cli/test/init_no_git_sync.test.ts index d16c9e771f..189e82562f 100644 --- a/cli/test/init_no_git_sync.test.ts +++ b/cli/test/init_no_git_sync.test.ts @@ -56,8 +56,6 @@ test("Init: createWorkspaceProfile includes defaults when no repositories exist" expect(Array.isArray(workspaceProfile.excludes)).toBeTruthy(); expect(workspaceProfile.excludes.length).toEqual(0); - expect(workspaceProfile.defaultTs).toEqual('bun'); - console.log('Workspace profile correctly includes default sync settings when no repositories exist'); }); @@ -74,8 +72,6 @@ test("Init: verify DEFAULT_SYNC_OPTIONS has expected values", () => { expect(Array.isArray(DEFAULT_SYNC_OPTIONS.excludes)).toBeTruthy(); expect(DEFAULT_SYNC_OPTIONS.excludes.length).toEqual(0); - expect(DEFAULT_SYNC_OPTIONS.defaultTs).toEqual('bun'); - console.log('DEFAULT_SYNC_OPTIONS has expected values'); }); @@ -178,7 +174,7 @@ test.skipIf(shouldSkipOnCI())("Init: --use-default bypasses backend settings che // Should have default settings, not backend settings expect(wmillYaml).toContain("includes:\n - f/**"); - expect(wmillYaml).toContain("defaultTs: bun"); + expect(wmillYaml).not.toContain("defaultTs"); // Should NOT have backend-specific settings expect(wmillYaml.includes("f/should-be-ignored/**")).toEqual(false); diff --git a/cli/test/init_template_unit.test.ts b/cli/test/init_template_unit.test.ts index 227fc271a2..7070de63c8 100644 --- a/cli/test/init_template_unit.test.ts +++ b/cli/test/init_template_unit.test.ts @@ -90,7 +90,6 @@ describe("generateCommentedTemplate", () => { test("default values match expected defaults", () => { const config = parse(generateCommentedTemplate("main")); - expect(config.defaultTs).toBe("bun"); expect(config.skipSecrets).toBe(true); expect(config.nonDottedPaths).toBe(true); expect(config.codebases).toEqual([]); diff --git a/cli/test/permissioned_as_context_unit.test.ts b/cli/test/permissioned_as_context_unit.test.ts new file mode 100644 index 0000000000..33a24bf3a1 --- /dev/null +++ b/cli/test/permissioned_as_context_unit.test.ts @@ -0,0 +1,27 @@ +/** + * Regression guard: a superadmin whose `usr` row in the workspace is not an + * admin still preserves ownership on the backend, so the CLI must not refuse + * their push as if it would reassign every item to them. + */ + +import { expect, test } from "bun:test"; +import { mockServices } from "./mock_services.ts"; + +mockServices({ + whoami: async () => ({ + email: "super@windmill.dev", + username: "super", + is_admin: false, + is_super_admin: true, + groups: [], + }), +}); + +const { buildPermissionedAsContext } = await import( + "../src/core/permissioned_as.ts" +); + +test("a superadmin with a non-admin membership counts as able to preserve", async () => { + const ctx = await buildPermissionedAsContext("w", "v1"); + expect(ctx?.userIsAdminOrDeployer).toBe(true); +}); diff --git a/cli/test/precheck_permissioned_as_apps_unit.test.ts b/cli/test/precheck_permissioned_as_apps_unit.test.ts index 4a224a43c0..9651b59cc1 100644 --- a/cli/test/precheck_permissioned_as_apps_unit.test.ts +++ b/cli/test/precheck_permissioned_as_apps_unit.test.ts @@ -145,3 +145,16 @@ test("an app is listed once however many of its files changed", async () => { expect(message).toContain("2 item(s)"); }); + +// An agent has an identity only while `run_on_behalf_of` is on, so only then +// can a push take it over. +test("an agent warns only while it runs on behalf of someone", async () => { + const agent = (run: boolean) => ({ + name: "edited" as const, + path: "f/test/bot.resource.yaml", + before: `resource_type: ai_agent\nvalue:\n system_prompt: hi\n run_on_behalf_of: ${run}\n`, + }); + + expect(await precheck([agent(true)])).toContain("f/test/bot.resource.yaml"); + expect(await precheck([agent(false)])).toBeUndefined(); +}); diff --git a/cli/test/push_diff_convergence_unit.test.ts b/cli/test/push_diff_convergence_unit.test.ts index a6f2c132c0..fd20f0d263 100644 --- a/cli/test/push_diff_convergence_unit.test.ts +++ b/cli/test/push_diff_convergence_unit.test.ts @@ -8,6 +8,8 @@ import { compareDynFSElement, ZipFSElement, } from "../src/commands/sync/sync.ts"; +import { changedCustomPath } from "../src/commands/app/app.ts"; +import { isCustomPathFile } from "../src/core/specific_items.ts"; // The differ also reads the working tree (shared lockfiles, dependency files); // an empty one keeps that out of the picture. @@ -346,3 +348,150 @@ test("push: settings.yaml without instance_groups is not a change", async () => }); expect(await diff(otherGroups, remote, skips)).toEqual(["edited settings.yaml"]); }); + +function remoteRawApp(customPath?: string, files: Record<string, string> = {}) { + const zip = new JSZip(); + zip.file( + "f/test/myapp.raw_app.json", + JSON.stringify({ + summary: "My app", + policy: { execution_mode: "publisher" }, + ...(customPath ? { custom_path: customPath } : {}), + value: { files, runnables: {} }, + }), + { createFolders: false }, + ); + return ZipFSElement(zip, true, "bun", {}, {}, false, true) as any; +} + +async function rendered(el: Mock): Promise<Record<string, string>> { + const files: Record<string, string> = {}; + const walk = async (el: Mock) => { + for await (const child of el.getChildren()) { + if (child.isDirectory) await walk(child); + else files[slashPath(child.path)] = await child.getContentText(); + } + }; + await walk(el); + return files; +} + +// Workspace-named as push and pull name it, without any specificItems. +async function diffIn(ws: string, localEl: Mock, remoteEl: Mock, pull: boolean) { + const { changes } = await compareDynFSElement( + (pull ? remoteEl : localEl) as any, + (pull ? localEl : remoteEl) as any, + noIgnore, + false, + {} as any, + !pull, + [], + pull, + undefined, + ws, + pull, + false, + ); + return changes.map((c) => `${c.name} ${slashPath(c.path)}`); +} + +test("a custom path is its own workspace-specific file", async () => { + const files = await rendered(remoteRawApp("my-dashboard")); + expect(files["f/test/myapp.custom_path.yaml"]).toBe( + "custom_path: my-dashboard\n", + ); + const rawAppYaml = files["f/test/myapp.raw_app/raw_app.yaml"]; + expect(rawAppYaml).toBeDefined(); + expect(rawAppYaml).not.toContain("custom_path"); + + const { "f/test/myapp.custom_path.yaml": _, ...appFiles } = files; + const checkout = (extra: Record<string, string>) => + local({ ...appFiles, ...extra }); + + // The workspace's own file is the one compared; another's is ignored. + const own = checkout({ + "f/test/myapp.prod.custom_path.yaml": "custom_path: my-dashboard\n", + "f/test/myapp.staging.custom_path.yaml": "custom_path: staging-dash\n", + }); + for (const pull of [true, false]) { + expect(await diffIn("prod", own, remoteRawApp("my-dashboard"), pull)).toEqual([]); + } + expect( + await diffIn("staging", own, remoteRawApp("my-dashboard"), false), + ).toEqual(["edited f/test/myapp.custom_path.yaml"]); + + // Promotion: a checkout without the target's file leaves its path alone on + // push, and a pull brings it in as the target's file. + const promoted = checkout({ + "f/test/myapp.staging.custom_path.yaml": "custom_path: staging-dash\n", + }); + expect(await diffIn("prod", promoted, remoteRawApp("my-dashboard"), false)).toEqual([]); + expect(await diffIn("prod", promoted, remoteRawApp("my-dashboard"), true)).toEqual([ + "added f/test/myapp.custom_path.yaml", + ]); + // A pull mirrors a cleared custom path by deleting the workspace's file. + expect(await diffIn("prod", own, remoteRawApp(), true)).toEqual([ + "deleted f/test/myapp.custom_path.yaml", + ]); + // `custom_path: ''` clears it on push, and is in sync once it is cleared. + const cleared = checkout({ + "f/test/myapp.prod.custom_path.yaml": "custom_path: ''\n", + }); + expect(await diffIn("prod", cleared, remoteRawApp("my-dashboard"), false)).toEqual([ + "edited f/test/myapp.custom_path.yaml", + ]); + expect(await diffIn("prod", cleared, remoteRawApp(), false)).toEqual([]); +}); + +test("an app file named like a custom-path file is app content", async () => { + const remote = () => + remoteRawApp(undefined, { "/settings.prod.custom_path.json": "{}" }); + const files = await rendered(remote()); + expect(files["f/test/myapp.raw_app/settings.prod.custom_path.json"]).toBe("{}"); + expect(await diffIn("prod", local({}), remote(), true)).toContain( + "added f/test/myapp.raw_app/settings.prod.custom_path.json", + ); + expect(await diffIn("prod", local(files), remote(), false)).toEqual([]); +}); + +test("a fileset child named like a custom-path file is resource content", async () => { + const child = "f/res/data.fileset/settings.prod.custom_path.json"; + expect(isCustomPathFile(child)).toBe(false); + expect(isCustomPathFile("f/test/myapp.prod.custom_path.yaml")).toBe(true); + expect( + await diffIn("prod", local({ [child]: "{\"v\":2}" }), local({ [child]: "{\"v\":1}" }), false), + ).toEqual([`edited ${child}`]); +}); + +// A checkout from before custom paths had their own file keeps the value in +// raw_app.yaml: a push must converge on it, and a pull moves it out. +test("an in-file custom path converges on push", async () => { + const files = await rendered(remoteRawApp("my-dashboard")); + const { "f/test/myapp.custom_path.yaml": _, ...appFiles } = files; + const inFile = (value: string) => + local({ + ...appFiles, + "f/test/myapp.raw_app/raw_app.yaml": + files["f/test/myapp.raw_app/raw_app.yaml"] + `custom_path: ${value}\n`, + }); + + expect(await diffIn("prod", inFile("my-dashboard"), remoteRawApp("my-dashboard"), false)).toEqual([]); + expect(await diffIn("prod", inFile("other"), remoteRawApp("my-dashboard"), false)).toEqual([ + "edited f/test/myapp.custom_path.yaml", + ]); + expect(await diffIn("prod", inFile("my-dashboard"), remoteRawApp("my-dashboard"), true)).toEqual([ + "edited f/test/myapp.raw_app/raw_app.yaml", + "added f/test/myapp.custom_path.yaml", + ]); +}); + +test("push: an unchanged custom_path is not sent", () => { + expect( + changedCustomPath("my-dashboard", { custom_path: "my-dashboard" }), + ).toBeUndefined(); + expect(changedCustomPath(undefined, { custom_path: "my-dashboard" })).toBeUndefined(); + expect(changedCustomPath("", undefined)).toBeUndefined(); + expect(changedCustomPath("new", { custom_path: "my-dashboard" })).toBe("new"); + expect(changedCustomPath("", { custom_path: "my-dashboard" })).toBe(""); + expect(changedCustomPath("new", undefined)).toBe("new"); +}); diff --git a/cli/test/push_workspace_settings_auto_invite_unit.test.ts b/cli/test/push_workspace_settings_auto_invite_unit.test.ts index f4564c25b2..d04b7f4337 100644 --- a/cli/test/push_workspace_settings_auto_invite_unit.test.ts +++ b/cli/test/push_workspace_settings_auto_invite_unit.test.ts @@ -21,6 +21,10 @@ const remoteAutoInvite = { // Every wmill.* call reachable from pushWorkspaceSettings is stubbed so the // function runs without a backend. mockServices({ + // A server without the settings document, so the per-setting endpoints run. + applyWorkspaceSettingsDocument: async () => { + throw { status: 404 }; + }, getSettings: async () => ({ auto_invite: remoteAutoInvite }), getWorkspaceName: async () => "phoenix", changeWorkspaceName: async () => {}, diff --git a/cli/test/push_workspace_settings_identity_unit.test.ts b/cli/test/push_workspace_settings_identity_unit.test.ts index d11b5efac4..16b3bd34b4 100644 --- a/cli/test/push_workspace_settings_identity_unit.test.ts +++ b/cli/test/push_workspace_settings_identity_unit.test.ts @@ -17,6 +17,10 @@ let remoteWebhook: string | undefined = undefined; // Every wmill.* call reachable from pushWorkspaceSettings is stubbed so the // function runs without a backend; only the three we assert on record calls. mockServices({ + // A server without the settings document, so the per-setting endpoints run. + applyWorkspaceSettingsDocument: async () => { + throw { status: 404 }; + }, getSettings: async (_a: { workspace: string }) => ({ webhook: remoteWebhook, color: remoteColor, diff --git a/cli/test/resource_push_agent_obo_unit.test.ts b/cli/test/resource_push_agent_obo_unit.test.ts new file mode 100644 index 0000000000..d9b8361c8a --- /dev/null +++ b/cli/test/resource_push_agent_obo_unit.test.ts @@ -0,0 +1,57 @@ +/** + * An agent's run-as identity lives in its value, which the pull leaves out. A + * push must neither see that gap as a change nor let the file pick who the + * agent runs as: only the deployed identity is claimed back, and only by a + * pusher the backend lets keep it. + */ + +import { expect, test } from "bun:test"; +import { isSuperset } from "../src/types.ts"; +import { agentOnBehalfOf } from "../src/commands/resource/resource.ts"; + +const ctx = (userIsAdminOrDeployer: boolean) => ({ + userCache: new Map(), + userIsAdminOrDeployer, + userEmail: "me@x.dev", +}); + +function agents(localObo?: string) { + const deployed = { + resource_type: "ai_agent", + value: { system_prompt: "hi", on_behalf_of: "u/bob" }, + } as any; + const local = { + resource_type: "ai_agent", + value: { system_prompt: "hi", ...(localObo ? { on_behalf_of: localObo } : {}) }, + } as any; + return { deployed, local }; +} + +test("an unchanged agent still compares equal to the deployed one", () => { + const { deployed, local } = agents(); + agentOnBehalfOf(deployed, local, ctx(true)); + expect(isSuperset(local, deployed)).toBe(true); +}); + +test("an admin or deployer claims the deployed identity, never the file's", () => { + const { deployed, local } = agents("u/admin"); + expect(agentOnBehalfOf(deployed, local, ctx(true))).toBe("u/bob"); + expect(local.value.on_behalf_of).toBeUndefined(); +}); + +test("anyone else claims nothing", () => { + const { deployed, local } = agents("u/bob"); + expect(agentOnBehalfOf(deployed, local, ctx(false))).toBeUndefined(); + expect(agentOnBehalfOf(agents().deployed, agents().local, undefined)).toBeUndefined(); + expect(local.value.on_behalf_of).toBeUndefined(); +}); + +test("other resources are left alone, an agent retyped into one included", () => { + for (const deployedType of ["json", "ai_agent"]) { + const deployed = { resource_type: deployedType, value: { on_behalf_of: "u/bob" } } as any; + const local = { resource_type: "json", value: { on_behalf_of: "u/x" } } as any; + expect(agentOnBehalfOf(deployed, local, ctx(true))).toBeUndefined(); + expect(local.value.on_behalf_of).toBe("u/x"); + expect(deployed.value.on_behalf_of).toBe("u/bob"); + } +}); diff --git a/cli/test/standalone_commands.test.ts b/cli/test/standalone_commands.test.ts index 271b13867b..561ccf9d42 100644 --- a/cli/test/standalone_commands.test.ts +++ b/cli/test/standalone_commands.test.ts @@ -139,10 +139,7 @@ describe("resource-type commands", () => { ); expect(result.code).toEqual(0); - // When empty, shows helpful message; when populated, shows table with Name header - const hasTable = result.stdout.includes("Name"); - const hasEmptyMessage = result.stdout.includes("No custom resource types"); - expect(hasTable || hasEmptyMessage).toBe(true); + expect(result.stdout).toContain("Name"); }); }); diff --git a/cli/windmill-utils-internal/src/deploy.ts b/cli/windmill-utils-internal/src/deploy.ts index 71447c6b1f..d73cb3562c 100644 --- a/cli/windmill-utils-internal/src/deploy.ts +++ b/cli/windmill-utils-internal/src/deploy.ts @@ -637,15 +637,26 @@ export async function deployItem( workspace: workspaceFrom, path, }); + let value = resource.value ?? ""; + // An agent's value carries the principal it runs as, as a trigger's row does: the source's + // names nobody in the target, so it is replaced by the chosen one or dropped, leaving the + // backend to make it the deployer's. + const agent = resource.resource_type === "ai_agent" && typeof value === "object"; + if (agent) { + const { on_behalf_of: _, ...rest } = value; + value = onBehalfOf ? { ...rest, on_behalf_of: onBehalfOf } : rest; + } + const agentPreserve = agent ? { preserve_on_behalf_of: preserveOnBehalfOf } : {}; if (alreadyExists) { await provider.updateResource({ workspace: workspaceTo, path, requestBody: { path, - value: resource.value ?? "", + value, description: resource.description ?? "", labels: resource.labels, + ...agentPreserve, }, }); } else { @@ -653,10 +664,11 @@ export async function deployItem( workspace: workspaceTo, requestBody: { path, - value: resource.value ?? "", + value, resource_type: resource.resource_type, description: resource.description ?? "", labels: resource.labels, + ...agentPreserve, }, }); } @@ -917,6 +929,11 @@ export async function getItemValue( return variable.value; } else if (kind === "resource") { const resource = await provider.getResource({ workspace, path }); + // Each workspace resolves its own agent identity, which a deploy never copies. + if (resource.resource_type === "ai_agent" && resource.value) { + const { on_behalf_of: _, ...value } = resource.value; + return value; + } return resource.value; } else if (kind === "resource_type") { const rt = await provider.getResourceType({ workspace, path }); @@ -1002,7 +1019,8 @@ function stripTriggerOrScheduleRuntimeFields(row: unknown): unknown { /** * Fetch the on_behalf_of value for a deployable item. - * Returns an email for flows/scripts/apps, or undefined if not applicable. + * Returns an email for flows/scripts/apps, a principal (u/username, g/group) for + * triggers/schedules and agents, or undefined if not applicable. */ export async function getOnBehalfOf( provider: DeployProvider, @@ -1020,6 +1038,12 @@ export async function getOnBehalfOf( } else if (kind === "app" || kind === "raw_app") { const app = await provider.getAppByPath({ workspace, path }); return app.policy?.on_behalf_of_email; + } else if (kind === "resource") { + // Only an agent runs as anyone, and like a trigger it records the principal. + const resource = await provider.getResource({ workspace, path }); + return resource.resource_type === "ai_agent" + ? resource.value?.on_behalf_of + : undefined; } else if (kind === "schedule") { const schedule = await provider.getSchedule({ workspace, path }); return schedule.permissioned_as; diff --git a/cli/wmill.schema.json b/cli/wmill.schema.json index 022156e5c9..145a75fd26 100644 --- a/cli/wmill.schema.json +++ b/cli/wmill.schema.json @@ -10,7 +10,7 @@ "bun", "deno" ], - "description": "Default TypeScript runtime for new scripts" + "description": "TypeScript runtime of a plain .ts script (bun when absent)" }, "includes": { "type": "array", diff --git a/debugger/README.md b/debugger/README.md index 1dba49d977..040fb4ef67 100644 --- a/debugger/README.md +++ b/debugger/README.md @@ -139,7 +139,7 @@ the debug service. Where two names are listed the first wins; a worker reads the | `PY_TRUSTED_HOST` / `PIP_TRUSTED_HOST` | Hosts to trust, whitespace-separated (`--trusted-host`) | - | | `PY_INDEX_CERT` / `PIP_INDEX_CERT` | CA bundle for the index, passed to uv as `SSL_CERT_FILE`. Falls back to `SSL_CERT_FILE`, then `REQUESTS_CA_BUNDLE`, then `CURL_CA_BUNDLE`, so a host that configures its CA under any of those names is picked up. Whichever is used **replaces** uv's own roots rather than adding to them, so it has to be a complete bundle: one holding only a private CA leaves every public index untrusted. `bun install` gets the same bundle as `NODE_EXTRA_CA_CERTS`, the only spelling Bun reads | - | | `SSL_CERT_DIR` | Directory of certificates, forwarded to uv as-is. Replaces uv's roots the same way the bundle does, so a directory holding only a private CA leaves public indexes untrusted | - | -| `PY_NATIVE_CERT` / `UV_NATIVE_TLS` | `true` to also trust the platform certificate store (`--native-tls`) | false | +| `PY_NATIVE_CERT` / `UV_SYSTEM_CERTS` | `true` to also trust the platform certificate store (`--system-certs`) | false | | `UV_HTTP_TIMEOUT` | uv HTTP request timeout, in seconds | uv's own default | | `DAP_REGISTRY_CONFIG_TIMEOUT_MS` | How long to wait on the settings fetch before installing without it | 10000 | @@ -172,7 +172,7 @@ and the container still boots. `INIT_SCRIPT` remains the hook for anything more the CA update it aborts startup when it fails. Note what the system store does *not* cover, which is most of what a debug session installs with: -uv trusts its own bundled roots unless `PY_NATIVE_CERT`/`UV_NATIVE_TLS` is `true`, Bun and Node read +uv trusts its own bundled roots unless `PY_NATIVE_CERT`/`UV_SYSTEM_CERTS` is `true`, Bun and Node read only `NODE_EXTRA_CA_CERTS`, and `requests` carries certifi. Registering the CA fixes Python's stdlib `ssl`, `curl` and `git`; the rest still needs the variables above. diff --git a/docker/DockerfileExtra b/docker/DockerfileExtra index ace382528b..1d8d0003da 100644 --- a/docker/DockerfileExtra +++ b/docker/DockerfileExtra @@ -71,7 +71,7 @@ ENV XDG_CACHE_HOME=/pyls/.cache RUN uv pip install --system --break-system-packages pipenv tornado python-lsp-jsonrpc ruff==0.16.0 Cython # Install Node-based language servers -RUN npm install -g diagnostic-languageserver pyright +RUN npm install -g pyright # Setup LSP working directory WORKDIR /pyls diff --git a/docker/DockerfileFull b/docker/DockerfileFull index 8ef6be78bb..c3a82c8312 100644 --- a/docker/DockerfileFull +++ b/docker/DockerfileFull @@ -1,6 +1,9 @@ ARG BASE_IMAGE=ghcr.io/windmill-labs/windmill:dev FROM ${BASE_IMAGE} +# Deno +COPY --from=denoland/deno:2.2.1 --chmod=755 /usr/bin/deno /usr/bin/deno + # Rust COPY --from=rust:1.97.0 /usr/local/cargo /usr/local/cargo COPY --from=rust:1.97.0 /usr/local/rustup /usr/local/rustup @@ -12,7 +15,9 @@ RUN RUSTUP_HOME=/usr/local/rustup CARGO_HOME=/usr/local/cargo /usr/local/cargo/b # ansible there leaves its venv interpreter as a dangling symlink at runtime, so every # ansible-* executable fails with ENOENT ("ansible-galaxy not found"). Pin the tool's # interpreter to a persistent image path so the install stays self-contained. -RUN UV_PYTHON_INSTALL_DIR=/usr/local/uv/py uv tool install ansible && [ -d "$(uv tool dir)/ansible/bin/" ] && find "$(uv tool dir)/ansible/bin/" -mindepth 1 -maxdepth 1 -type f -executable -regextype posix-extended -regex '^((.+/)?)[^.]+' -print0 | xargs -0 ln -sf -t "$UV_TOOL_BIN_DIR/" || true +# The version is explicit because uv otherwise downloads its newest stable Python, which +# ansible-core may not support yet: the install succeeds and every executable fails on import. +RUN UV_PYTHON_INSTALL_DIR=/usr/local/uv/py uv tool install --python 3.14 ansible && [ -d "$(uv tool dir)/ansible/bin/" ] && find "$(uv tool dir)/ansible/bin/" -mindepth 1 -maxdepth 1 -type f -executable -regextype posix-extended -regex '^((.+/)?)[^.]+' -print0 | xargs -0 ln -sf -t "$UV_TOOL_BIN_DIR/" || true # C# RUN wget https://dot.net/v1/dotnet-install.sh -O dotnet-install.sh \ diff --git a/docker/DockerfileFullEe b/docker/DockerfileFullEe index 88ed619c19..bb83195f62 100644 --- a/docker/DockerfileFullEe +++ b/docker/DockerfileFullEe @@ -21,6 +21,9 @@ RUN if [ "$TARGETPLATFORM" = "linux/arm64" ]; then \ FROM ${BASE_IMAGE} +# Deno +COPY --from=denoland/deno:2.2.1 --chmod=755 /usr/bin/deno /usr/bin/deno + # Rust COPY --from=rust:1.97.0 /usr/local/cargo /usr/local/cargo COPY --from=rust:1.97.0 /usr/local/rustup /usr/local/rustup @@ -32,7 +35,9 @@ RUN RUSTUP_HOME=/usr/local/rustup CARGO_HOME=/usr/local/cargo /usr/local/cargo/b # ansible there leaves its venv interpreter as a dangling symlink at runtime, so every # ansible-* executable fails with ENOENT ("ansible-galaxy not found"). Pin the tool's # interpreter to a persistent image path so the install stays self-contained. -RUN UV_PYTHON_INSTALL_DIR=/usr/local/uv/py uv tool install ansible && [ -d "$(uv tool dir)/ansible/bin/" ] && find "$(uv tool dir)/ansible/bin/" -mindepth 1 -maxdepth 1 -type f -executable -regextype posix-extended -regex '^((.+/)?)[^.]+' -print0 | xargs -0 ln -sf -t "$UV_TOOL_BIN_DIR/" || true +# The version is explicit because uv otherwise downloads its newest stable Python, which +# ansible-core may not support yet: the install succeeds and every executable fails on import. +RUN UV_PYTHON_INSTALL_DIR=/usr/local/uv/py uv tool install --python 3.14 ansible && [ -d "$(uv tool dir)/ansible/bin/" ] && find "$(uv tool dir)/ansible/bin/" -mindepth 1 -maxdepth 1 -type f -executable -regextype posix-extended -regex '^((.+/)?)[^.]+' -print0 | xargs -0 ln -sf -t "$UV_TOOL_BIN_DIR/" || true # dotnet SDK RUN wget https://dot.net/v1/dotnet-install.sh -O dotnet-install.sh \ && chmod +x dotnet-install.sh \ diff --git a/docker/DockerfileSlim b/docker/DockerfileSlim index 45986bbd5f..630f454f01 100644 --- a/docker/DockerfileSlim +++ b/docker/DockerfileSlim @@ -23,13 +23,16 @@ RUN apt-get -y update \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* -RUN git clone -b master --single-branch https://github.com/google/nsjail.git . && git checkout dccf911fd2659e7b08ce9507c25b2b38ec2c5800 +COPY docker/nsjail-patches/ /nsjail-patches/ +RUN git clone -b master --single-branch https://github.com/google/nsjail.git . && git checkout dccf911fd2659e7b08ce9507c25b2b38ec2c5800 \ + && git apply /nsjail-patches/*.patch RUN make FROM ${DEBIAN_IMAGE} ARG APP=/usr/src/app ARG LATEST_STABLE_PY=3.12.13 +ARG NEW_INSTANCE_PY=3.13.16 # UV configuration ENV UV_CACHE_DIR=/tmp/windmill/cache/uv @@ -58,13 +61,14 @@ RUN curl -fsSL https://www.postgresql.org/media/keys/ACCC4CF8.asc | gpg --dearmo ENV TZ=Etc/UTC # Install UV -RUN curl --proto '=https' --tlsv1.2 -LsSf https://github.com/astral-sh/uv/releases/download/0.11.24/uv-installer.sh | sh && mv /root/.local/bin/uv /usr/local/bin/uv +RUN curl --proto '=https' --tlsv1.2 -LsSf https://github.com/astral-sh/uv/releases/download/0.13.0/uv-installer.sh | sh && mv /root/.local/bin/uv /usr/local/bin/uv # Preinstall python runtime to temp location (will copy with world-writable perms later) # --compile-bytecode precompiles the stdlib to .pyc so jobs don't recompile it on every run # under the read-only nsjail runtime mount (uv >= 0.9.25). The copy below MUST preserve # timestamps or Python's mtime-based .pyc invalidation discards these compiled files. RUN UV_PYTHON_INSTALL_DIR=/tmp/build_cache/py_runtime uv python install $LATEST_STABLE_PY --compile-bytecode +RUN UV_PYTHON_INSTALL_DIR=/tmp/build_cache/py_runtime uv python install $NEW_INSTANCE_PY --compile-bytecode # Copy to final location with world-writable permissions for arbitrary UID support RUN mkdir -p /tmp/windmill/cache && \ diff --git a/docker/DockerfileSlimEe b/docker/DockerfileSlimEe index 5ac24f5c1d..8189e74bf9 100644 --- a/docker/DockerfileSlimEe +++ b/docker/DockerfileSlimEe @@ -23,13 +23,16 @@ RUN apt-get -y update \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* -RUN git clone -b master --single-branch https://github.com/google/nsjail.git . && git checkout dccf911fd2659e7b08ce9507c25b2b38ec2c5800 +COPY docker/nsjail-patches/ /nsjail-patches/ +RUN git clone -b master --single-branch https://github.com/google/nsjail.git . && git checkout dccf911fd2659e7b08ce9507c25b2b38ec2c5800 \ + && git apply /nsjail-patches/*.patch RUN make FROM ${DEBIAN_IMAGE} ARG APP=/usr/src/app ARG LATEST_STABLE_PY=3.12.13 +ARG NEW_INSTANCE_PY=3.13.16 # UV configuration ENV UV_CACHE_DIR=/tmp/windmill/cache/uv @@ -58,13 +61,14 @@ RUN curl -fsSL https://www.postgresql.org/media/keys/ACCC4CF8.asc | gpg --dearmo ENV TZ=Etc/UTC # Install UV -RUN curl --proto '=https' --tlsv1.2 -LsSf https://github.com/astral-sh/uv/releases/download/0.11.24/uv-installer.sh | sh && mv /root/.local/bin/uv /usr/local/bin/uv +RUN curl --proto '=https' --tlsv1.2 -LsSf https://github.com/astral-sh/uv/releases/download/0.13.0/uv-installer.sh | sh && mv /root/.local/bin/uv /usr/local/bin/uv # Preinstall python runtime to temp location (will copy with world-writable perms later) # --compile-bytecode precompiles the stdlib to .pyc so jobs don't recompile it on every run # under the read-only nsjail runtime mount (uv >= 0.9.25). The copy below MUST preserve # timestamps or Python's mtime-based .pyc invalidation discards these compiled files. RUN UV_PYTHON_INSTALL_DIR=/tmp/build_cache/py_runtime uv python install $LATEST_STABLE_PY --compile-bytecode +RUN UV_PYTHON_INSTALL_DIR=/tmp/build_cache/py_runtime uv python install $NEW_INSTANCE_PY --compile-bytecode # Copy to final location with world-writable permissions for arbitrary UID support RUN mkdir -p /tmp/windmill/cache && \ diff --git a/docker/RHEL8/Dockerfile b/docker/RHEL8/Dockerfile index ea53feabf1..a7eca5fbd8 100644 --- a/docker/RHEL8/Dockerfile +++ b/docker/RHEL8/Dockerfile @@ -93,7 +93,7 @@ RUN --mount=type=cache,target=/usr/local/cargo/registry \ CARGO_NET_GIT_FETCH_WITH_CLI=true cargo build --release RUN mkdir -p /usr/src/app && \ - cp windmill-duckdb-ffi-internal/target/release/libwindmill_duckdb_ffi_internal.so /usr/src/app/ + cp windmill-duckdb-ffi-internal/target/release/windmill_duckdb_runner /usr/src/app/ # Runtime Kerberos packages (installed separately from build deps) RUN yum install -y krb5-workstation cyrus-sasl-gssapi diff --git a/docker/RHEL9/Dockerfile b/docker/RHEL9/Dockerfile index ab94df5fc4..cc972884d8 100644 --- a/docker/RHEL9/Dockerfile +++ b/docker/RHEL9/Dockerfile @@ -93,7 +93,7 @@ RUN --mount=type=cache,target=/usr/local/cargo/registry \ CARGO_NET_GIT_FETCH_WITH_CLI=true cargo build --release RUN mkdir -p /usr/src/app && \ - cp windmill-duckdb-ffi-internal/target/release/libwindmill_duckdb_ffi_internal.so /usr/src/app/ + cp windmill-duckdb-ffi-internal/target/release/windmill_duckdb_runner /usr/src/app/ # Runtime Kerberos packages (installed separately from build deps) RUN yum install -y krb5-workstation cyrus-sasl-gssapi diff --git a/docker/nsjail-patches/gvisor-compat.patch b/docker/nsjail-patches/gvisor-compat.patch new file mode 100644 index 0000000000..70176b7272 --- /dev/null +++ b/docker/nsjail-patches/gvisor-compat.patch @@ -0,0 +1,153 @@ +gvisor_compat: an opt-in nsjail option (config field and --gvisor_compat) for running inside +gVisor (runsc). With it false, nsjail behaves as upstream. With it true: +- no rtnetlink link cache when no interface is moved into the jail: gVisor acks NLM_F_DUMP + requests before NLMSG_DONE and libnl rejects that (google/gvisor#15945); +- an EPERM from setrlimit(RLIMIT_MSGQUEUE) is a warning: gVisor refuses that limit for any + value (google/gvisor#15944); +- an EPERM from PR_SET_SECUREBITS is tolerated when the UID does not change, where the bits + have no effect (SECBIT_NO_SETUID_FIXUP lands in gVisor with google/gvisor#15130). +Applied to google/nsjail dccf911fd2659e7b08ce9507c25b2b38ec2c5800 by the Dockerfiles. + +diff --git a/cmdline.cc b/cmdline.cc +index 1b52b33..b49ce16 100644 +--- a/cmdline.cc ++++ b/cmdline.cc +@@ -115,6 +115,7 @@ struct custom_option custom_opts[] = { + { { "rlimit_rtprio", required_argument, NULL, 0x0210 }, "RLIMIT_RTPRIO, 'max' or 'hard' for the current hard limit, 'def' or 'soft' for the current soft limit, 'inf' for RLIM64_INFINITY (default: 'soft')" }, + { { "rlimit_msgqueue", required_argument, NULL, 0x0211 }, "RLIMIT_MSGQUEUE in bytes, 'max' or 'hard' for the current hard limit, 'def' or 'soft' for the current soft limit, 'inf' for RLIM64_INFINITY (default: 'soft')" }, + { { "disable_rlimits", no_argument, NULL, 0x0208 }, "Disable all rlimits, default to limits set by parent" }, ++ { { "gvisor_compat", no_argument, NULL, 0x0510 }, "Tolerate what gVisor (runsc) does not implement (see config.proto)" }, + { { "persona_addr_compat_layout", no_argument, NULL, 0x0301 }, "personality(ADDR_COMPAT_LAYOUT)" }, + { { "persona_mmap_page_zero", no_argument, NULL, 0x0302 }, "personality(MMAP_PAGE_ZERO)" }, + { { "persona_read_implies_exec", no_argument, NULL, 0x0303 }, "personality(READ_IMPLIES_EXEC)" }, +@@ -437,6 +438,7 @@ std::unique_ptr<nsjconf_t> parseArgs(int argc, char* argv[]) { + nsjconf->rl_rtpr = parseRLimit(RLIMIT_RTPRIO, "soft", 1); + nsjconf->rl_msgq = parseRLimit(RLIMIT_MSGQUEUE, "soft", 1); + nsjconf->disable_rl = false; ++ nsjconf->gvisor_compat = false; + nsjconf->personality = 0; + nsjconf->clone_newnet = true; + nsjconf->clone_newuser = true; +@@ -603,6 +605,9 @@ std::unique_ptr<nsjconf_t> parseArgs(int argc, char* argv[]) { + case 0x0208: + nsjconf->disable_rl = true; + break; ++ case 0x0510: ++ nsjconf->gvisor_compat = true; ++ break; + case 0x0301: + nsjconf->personality |= ADDR_COMPAT_LAYOUT; + break; +diff --git a/config.cc b/config.cc +index 620d08e..9427069 100644 +--- a/config.cc ++++ b/config.cc +@@ -166,6 +166,7 @@ static bool configParseInternal(nsjconf_t* nsjconf, const nsjail::NsJailConfig& + configRLimit(RLIMIT_MSGQUEUE, njc.rlimit_msgqueue_type(), njc.rlimit_msgqueue()); + + nsjconf->disable_rl = njc.disable_rl(); ++ nsjconf->gvisor_compat = njc.gvisor_compat(); + + if (njc.persona_addr_compat_layout()) { + nsjconf->personality |= ADDR_COMPAT_LAYOUT; +diff --git a/config.proto b/config.proto +index cd297ae..96b477c 100644 +--- a/config.proto ++++ b/config.proto +@@ -266,4 +266,10 @@ message NsJailConfig { + /* Binary path (with arguments) to be executed. If not specified here, it + can be specified with cmd-line as "-- /path/to/command arg1 arg2" */ + optional Exe exec_bin = 90; ++ ++ /* Tolerate what gVisor (runsc) does not implement: an EPERM from ++ setrlimit(RLIMIT_MSGQUEUE) or from PR_SET_SECUREBITS when the UID does ++ not change, and no rtnetlink link cache when no interface is moved ++ into the jail */ ++ optional bool gvisor_compat = 93 [default = false]; + } +diff --git a/contain.cc b/contain.cc +index b5120cc..41e69f8 100644 +--- a/contain.cc ++++ b/contain.cc +@@ -172,8 +172,12 @@ static bool containSetLimits(nsjconf_t* nsjconf) { + } + rl.rlim_cur = rl.rlim_max = nsjconf->rl_msgq; + if (setrlimit64(RLIMIT_MSGQUEUE, &rl) == -1) { +- PLOG_E("setrlimit64(0, RLIMIT_MSGQUEUE , %" PRIu64 ")", nsjconf->rl_msgq); +- return false; ++ if (!nsjconf->gvisor_compat || errno != EPERM) { ++ PLOG_E("setrlimit64(0, RLIMIT_MSGQUEUE , %" PRIu64 ")", nsjconf->rl_msgq); ++ return false; ++ } ++ PLOG_W("setrlimit64(0, RLIMIT_MSGQUEUE , %" PRIu64 "), ignored (gvisor_compat)", ++ nsjconf->rl_msgq); + } + return true; + } +diff --git a/net.cc b/net.cc +index 87c3df9..b4c64f4 100644 +--- a/net.cc ++++ b/net.cc +@@ -138,6 +138,10 @@ bool initNsFromParent(nsjconf_t* nsjconf, int pid) { + if (!nsjconf->clone_newnet) { + return true; + } ++ /* gVisor's rtnetlink replies are rejected by libnl's link cache, which is unused here */ ++ if (nsjconf->gvisor_compat && nsjconf->ifaces.empty() && nsjconf->iface_vs.empty()) { ++ return true; ++ } + struct nl_sock* sk = nl_socket_alloc(); + if (!sk) { + LOG_E("Could not allocate socket with nl_socket_alloc()"); +diff --git a/nsjail.h b/nsjail.h +index 5687ca7..fa2b9fa 100644 +--- a/nsjail.h ++++ b/nsjail.h +@@ -119,6 +119,7 @@ struct nsjconf_t { + uint64_t rl_rtpr; + uint64_t rl_msgq; + bool disable_rl; ++ bool gvisor_compat; + unsigned long personality; + bool clone_newnet; + bool clone_newuser; +diff --git a/user.cc b/user.cc +index a335e2d..f3e578b 100644 +--- a/user.cc ++++ b/user.cc +@@ -260,10 +260,24 @@ bool initNsFromChild(nsjconf_t* nsjconf) { + * Make sure all capabilities are retained after the subsequent setuid/setgid, as they will + * be needed for privileged operations: mounts, uts change etc. + */ ++ bool securebits_set = true; + if (prctl(PR_SET_SECUREBITS, SECBIT_KEEP_CAPS | SECBIT_NO_SETUID_FIXUP, 0UL, 0UL, 0UL) == + -1) { +- PLOG_E("prctl(PR_SET_SECUREBITS, SECBIT_KEEP_CAPS | SECBIT_NO_SETUID_FIXUP)"); +- return false; ++ /* ++ * The bits only matter when setresuid() below changes the UID: without them, ++ * leaving UID 0 clears the capabilities still needed by the jail setup. ++ */ ++ uid_t ruid, euid, suid; ++ const uid_t uid = nsjconf->uids[0].inside_id; ++ if (!nsjconf->gvisor_compat || errno != EPERM || ++ getresuid(&ruid, &euid, &suid) == -1 || ruid != uid || euid != uid || ++ suid != uid) { ++ PLOG_E("prctl(PR_SET_SECUREBITS, SECBIT_KEEP_CAPS | SECBIT_NO_SETUID_FIXUP)"); ++ return false; ++ } ++ PLOG_W("prctl(PR_SET_SECUREBITS, SECBIT_KEEP_CAPS | SECBIT_NO_SETUID_FIXUP), " ++ "ignored (gvisor_compat, UID unchanged)"); ++ securebits_set = false; + } + + /* +@@ -306,7 +320,7 @@ bool initNsFromChild(nsjconf_t* nsjconf) { + * unexpectedly retaining capabilities after a UID/GID + * change. + */ +- if (prctl(PR_SET_SECUREBITS, 0UL, 0UL, 0UL, 0UL) == -1) { ++ if (securebits_set && prctl(PR_SET_SECUREBITS, 0UL, 0UL, 0UL, 0UL) == -1) { + PLOG_E("prctl(PR_SET_SECUREBITS, 0)"); + return false; + } diff --git a/docker/test_windmill_extra.ts b/docker/test_windmill_extra.ts index 5fd1a74108..c5884c2dd4 100644 --- a/docker/test_windmill_extra.ts +++ b/docker/test_windmill_extra.ts @@ -121,6 +121,60 @@ async function testLspWebSocket(): Promise<void> { }) } +async function testLspShellDiagnostics(): Promise<void> { + return new Promise((resolve, reject) => { + const timeout = setTimeout(() => { + ws.close() + reject(new Error('no shellcheck diagnostics within 10s')) + }, 10000) + + const ws = new WebSocket(`ws://${HOST}:${LSP_PORT}/ws/diagnostic`) + const send = (msg: object) => ws.send(JSON.stringify({ jsonrpc: '2.0', ...msg })) + + ws.onopen = () => { + // Editors still send a linter definition; the server's own configuration + // applies, so the diagnostics below have to come from shellcheck. + send({ + id: 1, + method: 'initialize', + params: { + capabilities: {}, + initializationOptions: { + linters: { shellcheck: { command: 'true', sourceName: 'shellcheck' } }, + filetypes: { shell: 'shellcheck' } + } + } + }) + send({ + method: 'textDocument/didOpen', + params: { + textDocument: { + uri: 'file:///tmp/monaco/test.sh', + languageId: 'shell', + version: 1, + text: '#!/bin/bash\necho "$unassigned"\n' + } + } + }) + } + + ws.onmessage = (event) => { + const msg = JSON.parse(event.data.toString()) + if (msg.method !== 'textDocument/publishDiagnostics') return + clearTimeout(timeout) + ws.close() + const codes = msg.params.diagnostics.map((d: { code: string }) => d.code) + if (codes.includes('SC2154')) resolve() + else reject(new Error(`expected SC2154, got ${JSON.stringify(msg.params.diagnostics)}`)) + } + + ws.onerror = () => { + clearTimeout(timeout) + reject(new Error('LSP WebSocket connection failed')) + } + }) +} + async function runLspTests(): Promise<boolean> { log('\n=== LSP Service Tests (Port ' + LSP_PORT + ') ===') @@ -132,6 +186,7 @@ async function runLspTests(): Promise<boolean> { let passed = true passed = (await runTest('LSP health check', testLspHealth)) && passed passed = (await runTest('LSP WebSocket connection (pyright)', testLspWebSocket)) && passed + passed = (await runTest('LSP shell diagnostics', testLspShellDiagnostics)) && passed return passed } diff --git a/docs/datatable-viewer-roles.md b/docs/datatable-viewer-roles.md new file mode 100644 index 0000000000..89ae3d9d50 --- /dev/null +++ b/docs/datatable-viewer-roles.md @@ -0,0 +1,104 @@ +# Data table connections and whose roles they hold + +A data table under roles (Enterprise Edition) resolves a connection that names a role to that +role alone. A connection that names none is resolved from the data table's default role and the +roles of one **identity**: + +| Default role | A connection naming no role holds | +|---|---| +| `admin` (until changed) | `admin`, as before identity roles existed | +| another role | that role when the identity may use it, plus **every role the identity is a tenant of** | +| none (`NO_DEFAULT_DATATABLE_ROLE`) | the identity's roles only | + +The identity is the job's own, `permissioned_as`, like everything else a job reaches: the +publisher for a publisher-mode app, the owner of a schedule or trigger, whoever ran a script. It +is the job's **viewer** only for an inline runnable of a full-code app whose policy entry sets +`viewer_data_access` (`DatatableConnectAs::Viewer`). Postgres row-level security then answers per +viewer from a runnable that runs as the publisher, with nothing written in the code. + +A connection left with no role at all is refused. Policies test membership, which is true for a +role's own login too, so one policy serves a named connection and an unnamed one: + +```sql +CREATE POLICY emea ON orders FOR SELECT + USING (region = 'emea' AND pg_has_role(current_user, 'sales_emea', 'member')); +``` + +A policy names its role as text, so renaming the role breaks it. + +## Code + +| Where | What | +|---|---| +| `windmill-common/src/workspaces.rs` | `DatatableAccess`, `DatatableConnectAs`, `get_datatable_resource_from_db` | +| `windmill-common/src/datatable_roles_ee.rs` | `resolve_datatable_role_connection`, `resolve_unnamed_login`, `governing_identity`, `ensure_role_set_login`, `retire_role_set_logins_of`, `sweep_unused_role_set_logins` | +| `windmill-api/src/apps.rs` | `execute_component`, which sets `job_perms.viewer_data_access` for a flagged inline runnable | +| `windmill-api-jobs/src/execution.rs` | `run_end_user_email`, where a run's viewer is recorded, and `run_inline_preview_end_user` | +| `frontend/.../raw_apps/ViewerDataAccessPopup.svelte` | the runnable setting, shown when the code reads a data table or object storage | +| `frontend/.../workspaceSettings/DataTablePermissionsButton.svelte` | the roles drawer, which warns while the default is `admin` | + +## What holds it together + +- **A default of `admin` is not a floor.** `admin` owns the tables and bypasses row-level + security, so nothing could be added to it, and it is the default until someone changes it. + Such a data table resolves exactly as it did before identity roles existed. Nothing ever sets a + default back to `admin`: removing or deleting the default role leaves none. +- **One identity decides both the default and the added roles.** The default is held when that + identity may use it, and the roles added are those whose tenants name that same identity. A + job never mixes its own identity's default with its viewer's roles. +- **Connecting as the viewer is the publisher's choice, made per runnable and stored in the + policy.** It is honored on inline runnables only, whose code is deployed with the app: a path + runnable is someone else's script, which would read with the viewer's roles without its author + choosing to. The server stamps `job_perms.viewer_data_access` in the transaction that pushes + the job. Nested jobs do not inherit it; an inline preview run with the job's token + (`run_inline/preview`, what `wmill.datatable()` uses) does, since that code is the job's own. +- **A job that connects as its viewer and has none is refused**, never resolved as the job: that + would undo what the runnable asked for. An anonymous app viewer is the usual case. +- **No role at all is a refusal, never an empty answer.** There is no login that would read + nothing: what a role sees is up to each table's grants and policies. +- **A set login owns what it creates.** Postgres gives a new object to `current_user`, and + default privileges go by the creating role, so a table created over a connection that holds + several roles belongs to that set's login: no other role or identity reaches it, and it passes + to `custom_instance_user` when the login is swept. Unnamed connections are for rows. To create + an object, name a role or run `SET ROLE <role>` first, which a set login may do for any role it + holds. Migrations are not affected: one that declares no role runs as `admin`. +- **The viewer is `job_perms.end_user_email`, and nothing else.** The server records it when the + run starts: the session behind an app request, the caller of a direct run or preview, and for a + job started with another job's token, that job's viewer. No argument reaches it. +- **A cached result belongs to one identity, one viewer and one mode.** `cached_result_path` + hashes the job's `permissioned_as`, its recorded viewer and `viewer_data_access` into the key, + since a cache hit returns before any connection is resolved. Turning the setting on changes no + code, so without the mode a result read with the app's roles would be served to the viewer. +- **Only a tenant list naming the identity counts.** A workspace admin may *use* every role, + `admin` included. The roles added are those whose tenants name the identity (user, group, + folder, `*`), and never `admin`. +- **One role is that role's login. Several are a login per distinct set.** `wm_set_<hash>` is a + member of exactly those roles, with `INHERIT`; the hash is over their catalog ids, so a rename + moves nothing and a change in someone's groups resolves them to another login instead of + editing one. Its privileges are its memberships, so `SET ROLE` only narrows and `RESET ROLE` + comes back to it. The prefix is reserved in `validate_role_name`. +- **A `datatable_role_set` row with a password names a login that can authenticate with it.** The + row is written after the login exists and removed, in its own commit, before the login is + dropped or made `NOLOGIN`. A login without a row is taken back with a new password on next use, + and so is one whose row has an empty password: that is what a sweep leaves when it could + neither drop a login nor let it back in, so the next sweep still finds it. +- **Set logins are bounded by use, not by the number of role combinations.** One exists only for + a set some identity actually connected with, so there are at most as many as (identity, data + table) pairs. `last_used_at` is recorded at most once a day, and `sweep_unused_role_set_logins`, + run from the monitor loop, drops those unused for 30 days; a dropped one is made again on + demand. The sweep goes by this instance's rows, never by the cluster's `wm_set_*` roles: a + cluster can serve several Windmill instances. +- **Disabling or dropping a role retires every set login holding it.** `NOLOGIN` on a role does + not reach a login that is a member of it. +- **Mixed fleets.** A worker or server older than v1.831 connects as the default role alone, and + refuses a data table with no default role, whose marker it reads as a role the data table + lacks. One from v1.831 or v1.832 adds the recorded viewer's roles to every job that has one, + flagged or not, and the job's own roles to none. + +## Trust + +A job that names no role reads with its own identity's roles, the same trust as the resources and +variables it reaches: every viewer of a publisher-mode app sees what the publisher's roles see. +An inline runnable that connects as its viewer runs its publisher's code with the viewer's reach +into the data table, the same trust as an app in viewer execution mode. Naming a role in the code +pins the connection to that one role either way. diff --git a/docs/duckdb-execution.md b/docs/duckdb-execution.md new file mode 100644 index 0000000000..70f9218ee4 --- /dev/null +++ b/docs/duckdb-execution.md @@ -0,0 +1,118 @@ +# How DuckDB jobs run + +A DuckDB job runs in `windmill_duckdb_runner`, a binary built from +`backend/windmill-duckdb-ffi-internal` (`src/bin`) and shipped next to the `windmill` binary. +The worker spawns one runner per DuckDB connection a job opens: the job itself, and the +`on_schema_change=sync` pre-pass. It never loads the engine into its own process. + +The runner gets the same job isolation as every other language. `duckdb_runner::runner_mode` +decides it per job: + +| worker isolates with | runner runs | what it can see | +|---|---|---| +| nsjail | inside `run.duckdb.config.proto` | read-only `/usr`, `/lib`, `/etc`; its own `/tmp`; its job dir read-only, except `duckdb/` (spill + result); a read-only extension cache | +| unshare | under `build_command_with_isolation` | the worker user's file system, its own PID namespace, a cleared environment | +| nothing | as a plain child process | the worker user's file system, a cleared environment | + +There is no SQL-level policy on top. A script can read and write what the jail lets it and load +any extension DuckDB will sign, as a Python job can read the same files and load native code. +Under nsjail its disk use is capped from the worker (below). Network egress is open in every +mode, as it is for the other languages: the S3 proxy, metadata endpoints and internal hosts are +all reachable. + +## What crosses to the runner + +`spawn_runner` writes one JSON request to the runner's stdin, so nothing secret is put on argv or +into the environment: + +- the blocks, already rewritten by the worker: resource `ATTACH`es, DuckLake and datatable + attaches with their credentials inlined, workspace macros; +- the job args, the job token, `base_internal_url` and the workspace id. The runner derives the + S3/GCS secrets for the workspace's S3 proxy from the token, which it reaches over the network; +- `memory_limit` (`DUCKDB_MEMORY_LIMIT`, or 80% of the worker's cgroup), the temp directory (the + job dir), and the result-size cap (`MAX_SQL_RESULT_SIZE`). + +The environment is cleared except `PATH`, `HOME` (outside nsjail), `DUCKDB_MAX_TEMP_DIRECTORY_SIZE`, +`GOOGLE_APPLICATION_CREDENTIALS` (BigQuery `ATTACH`, whose credentials file nsjail mounts) and the +proxy variables. In particular a script cannot use the worker's own `AWS_*` credential chain. + +Under nsjail the job dir is mounted read-only at its host path, so every path the worker wrote +into the blocks (Postgres root certificates) resolves unchanged. The one writable place on the +host is `{job dir}/duckdb/`: the spill directory and the result file, which the worker opens +without following symlinks, since the script can write there. + +The runner writes its answer to a file in that directory: a first line with the last statement's +column order, then either the collected results or `ERROR <json-encoded message>`. +`finish_run` / `finish_prepare` in `duckdb_executor.rs` turn that into the job result. + +## Failure, cancellation and memory + +- **A crash fails the job, never the worker.** A runner that exits without writing its result + becomes `The DuckDB engine process … The worker is unaffected.` with the tail of its stderr. + An engine `std::terminate` (for example a remote `temp_directory` that has to spill) and a + panic in result rendering both land here. +- **Cancellation and timeouts kill the engine.** The executor drops the job future, and + `KillGroupOnDrop` kills the runner's whole process group. Killing the spawned process alone is + not enough: `unshare --fork` leaves its child running. +- **The kernel OOM-kills the runner, not the worker.** `JOB_OOM_SCORE_ADJ` is written in + `pre_exec`, before nsjail or `unshare` is exec'd, so the runner inherits it. Written after spawn + it would race their fork, and the jail's `/proc` is read-only. Within the job, DuckDB bounds + itself through `memory_limit` and spills past it. +- **Runner output is bounded.** stdout/stderr are drained keeping only the last 4 KB: a script + controls how much the engine prints (`CALL enable_logging(storage='stdout')`). + +## Extensions + +Outside nsjail the runner uses the worker user's `~/.duckdb/extensions` and installs whatever a +script names. + +Under nsjail it gets its own cache, `~/.duckdb/windmill_jail_extensions`, mounted read-only. +Only the worker writes to it: before a jailed run it starts the runner unjailed in `install` +mode, with only `INSTALL` statements it built itself, for `httpfs`, `azure`, `parquet`, `json` +and every extension a block installs by name. That runs no script SQL and loads nothing, so no +extension code runs outside the jail. It happens once per extension per worker process, except +for `FORCE INSTALL`, which is honored every time and becomes a plain `INSTALL` inside the jail. +A job can therefore neither add to nor replace what the next job loads from that cache. An +extension used without being named and outside those four (`icu` behind `SET TimeZone`, say) +fails on the read-only mount: name it with `INSTALL`. + +A script can still point `extension_directory` somewhere writable and install into it. That only +affects its own connection, and is no more than a Python job could do. + +## The engine + +The runner links duckdb-rs from crates.io, pinned with `=` so `cargo update` cannot move the +engine. The engine loads the **prebuilt** extensions from `extensions.duckdb.org`, compiled for the +exact release it reports, so an engine bump is a version change in `Cargo.toml` and nothing else. + +Confinement belongs to the job isolation, not to engine settings. DuckDB spills through the same +file system a query reads with, so `disabled_filesystems='LocalFileSystem'` also stops every query +that outgrows `memory_limit`, and no combination of stock settings gives "spill, but no other local +file access". Fencing the engine at the SQL level again would need a patched engine to keep +spilling. + +## Bounding disk use + +The cap is `DUCKDB_MAX_TEMP_DIRECTORY_SIZE`, or `6GiB` on a `CLOUD_HOSTED` worker that does not +set it. The cloud runs one worker per pod on nodes with no per-pod ephemeral-storage limit, and a +worker pod already holds several GiB of runtime caches, so the cap is sized against a mostly full +node; re-measure before raising it. Unset elsewhere, DuckDB's own default applies: 90% of the +temp volume's free space. + +It is applied twice: + +- **DuckDB's `max_temp_directory_size`**, set on every connection, so an ordinary query that + outgrows it fails with the engine's `failed to offload data block … max_temp_directory_size` + error and cleans up its temp files. +- **A worker-side watchdog**, under nsjail. A script can raise the engine setting, so on its own + it is only a default. The worker sums the allocated size of `{job dir}/duckdb/` once a second + and kills the runner when it passes the cap, whatever wrote the bytes: spill, `COPY … TO`, or + the result file. With a disk-backed jail `/tmp` (`NSJAIL_TMP_BACKING=disk`) that `/tmp` lives +inside the same directory, so it counts too; a RAM-backed one is bounded by its tmpfs size. +Enforcement lags by up to a second of writing. Outside nsjail the script can + write anywhere the worker user can, as other languages can, so there the cap stays a default. + +The value is DuckDB's spelling, not Kubernetes': `KiB`/`MiB`/`GiB`/`TiB` for 1024-based units, +`KB`/`MB`/`GB`/`TB` for 1000-based. An unparseable value fails every DuckDB job on the worker +rather than being ignored. `DUCKDB_MEMORY_LIMIT` is spelled the same way, and the two are set in +separate statements so a parse error names the right variable. diff --git a/docs/duckdb-isolation.md b/docs/duckdb-isolation.md deleted file mode 100644 index fb85085b2c..0000000000 --- a/docs/duckdb-isolation.md +++ /dev/null @@ -1,223 +0,0 @@ -# DuckDB isolation and the patched engine - -DuckDB runs **in-process** in the worker, through the FFI cdylib in -`backend/windmill-duckdb-ffi-internal`. It is therefore the one language that the -nsjail/unshare isolation cannot confine: there is no child process to jail. On a worker -that isolates jobs, `windmill-worker/src/duckdb_isolation_ee.rs` mirrors that policy at -the connection level instead, rewriting the block list handed to the engine so it starts -with three irreversible settings: - -```sql -SET lock_temp_directory=true; -SET disabled_filesystems='LocalFileSystem'; -SET allow_community_extensions=false; -``` - -`disabled_filesystems` is the fence. `lock_temp_directory` is what keeps out-of-core -execution working behind it, and it is **not a stock DuckDB setting** — see below. - -## Why the engine had to change - -DuckDB spills through the same file system a query would use to read `/etc/hostname`, so -`disabled_filesystems='LocalFileSystem'` also stops the buffer manager. Every query whose -working set outgrows `memory_limit` then fails instead of going out-of-core. No -combination of stock settings gives "spill, but no other local file access": - -- `allowed_directories` / `allowed_paths` enforce nothing while `enable_external_access` - is true — `DBConfig::CanAccessFile` returns early. -- Turning `enable_external_access` off does preserve spilling (startup adds the temp - directory to `allowed_directories`), but the postgres and mysql extensions refuse to - `ATTACH` on that flag alone, with no allowlist entry able to re-permit it. That would - take DuckLake catalogs and datatables down with it. -- A remote `temp_directory` is impossible: DuckDB cannot open an HTTP file for both - reading and writing, and the attempt aborts the process. - -The engine is also not arranged the way the layering suggests. `FileSystem::GetLocal(db)` -looks like an escape hatch — it is what secret storage and extension installation use — -but `LocalDatabaseFileSystem::GetFileSystem()` re-applies the `disabled_filesystems` -check by hand, so it is not one. (That is also why extension autoload broke behind the -fence in DuckDB 1.5.3, which `EXTENSION_ALLOWLIST` and `PRELOAD_EXTENSIONS` exist to work -around.) The buffer manager, meanwhile, reaches its temp files through -`FileSystem::GetFileSystem(db)`, an opener-wrapped virtual file system, so both the path -allowlist and the disable apply to it. - -## What the patches add - -`lock_temp_directory` (BOOLEAN, default false, global, irreversible). Setting it: - -1. fixes `temp_directory` in place — it can no longer be modified, and the setting itself - cannot be unset or reset; -2. fixes `max_temp_directory_size` the same way, so the ceiling on what may be written - there cannot be raised either; -3. routes the buffer manager's temporary files through a local file system that - `disabled_filesystems` does not apply to. - -The halves are what make it safe as a set. The exemption is only sound because the -directory can no longer be redirected: without (1), a script could point `temp_directory` -at an arbitrary path and get a blind write primitive through the exemption. And it is only -bounded because of (2): DuckDB accepts `SET max_temp_directory_size='100GB'` from any -statement, so a cap a script can lift is not a cap. -`allowed_directories` still applies either way. - -The isolation transform therefore emits `SET lock_temp_directory=true` **before** -`disabled_filesystems`, while the local file system is still reachable, and after the FFI -has already pointed `temp_directory` at the job dir -(`configure_duckdb_resource_limits`). Everything a script authored runs after all three -settings, so a script can neither move the temp directory nor raise the cap on it. - -## Bounding the spill - -`configure_duckdb_resource_limits` sets `max_temp_directory_size` from -`DUCKDB_MAX_TEMP_DIRECTORY_SIZE`, immediately before it takes the lock. Unset — the -self-hosted default — leaves DuckDB's own default of 90% of the temp volume's free space, -so nothing changes for an install that does not opt in. The cloud sets `6GiB` per worker -pod (`cloudee/cloud/cloud.yml` in `infra-aws`); those pods run a single worker each, so it -is effectively a per-pod cap and is not divided by `NUM_WORKERS`. - -Those pods carry no `ephemeral-storage` limit, so what the cap has to stay clear of is the -node's eviction threshold rather than a per-pod one, and the budget is tighter than the -node's size suggests: a worker pod already holds 4.7-6.9 GiB of language-runtime caches and -job dirs before any spill, so a ~100 GB node running 5-6 of them sits at 45-60 GB used at -rest. Every pod on the fullest node spilling to its cap at the same instant would land near -the kubelet's default `nodefs.available<10%`. That is the tail, not the common case, and it -is still bounded where the previous behaviour was not — one query could take all the free -space by itself — but the cap is sized against a mostly-full node, not an empty one. Re-measure -before raising it, and re-measure if the runtime-cache baseline grows. - -It is read from the environment rather than passed across the FFI: the cdylib is versioned -separately from the worker and agent workers ship it out of band, so a signature change -would mean an ABI bump and a coordinated redeploy for what is a config value. - -The value is DuckDB's spelling, not Kubernetes': `KiB`/`MiB`/`GiB`/`TiB` for 1024-based -units, `KB`/`MB`/`GB`/`TB` for 1000-based. Kubernetes' `6Gi` is not a unit DuckDB knows, -and an unparseable value fails every DuckDB job on the worker rather than being ignored — -a cap that quietly disappeared would be worse. `DUCKDB_MEMORY_LIMIT` is spelled the same -way and DuckDB's parse error says only "memory", so the cap's `SET` is issued on its own -statement: batched together, a bad value in either would produce the same message and name -neither. - -Enforcement is graceful. A query that needs more spill than the cap fails with -`Out of Memory Error: failed to offload data block of size … This limit was set by the -'max_temp_directory_size' setting.`, its temp files are removed, and the worker carries on. -Size it from measurement, not from the data: DuckDB compresses temp files, so the logical -spill a given cap permits is well above the number set. - -That engine message goes on to suggest `PRAGMA max_temp_directory_size='10GiB'`, which the -lock refuses — advice that was actionable before the cap was frozen and is now a dead end -ending in a second, unrelated-looking permission error. `decode_ffi_error` -(`duckdb_executor.rs`) appends a correction whenever the message appears, on every worker -rather than only isolating ones, since the lock is taken on every connection. It matches -DuckDB's wording verbatim, which -`spilling_past_the_configured_cap_fails_the_query_and_cleans_up` asserts against real engine -output so an engine bump that rewords it fails the test instead of silently dropping the -correction. - -The engine emits that same message for **its own default cap**, so which limit was hit -cannot be read off the message: with `DUCKDB_MAX_TEMP_DIRECTORY_SIZE` unset it means the -worker is low on disk, not that anyone configured a ceiling. `spill_cap_hint` takes the -answer from the worker's config instead and says whichever is true — naming the env var on a -worker that never set it would point the reader at a knob that does not exist. - -## Where the patched engine comes from - -`backend/windmill-duckdb-ffi-internal` depends on -[`windmill-labs/duckdb-rs`](https://github.com/windmill-labs/duckdb-rs), branch -`windmill/duckdb-1.5.5`, pinned by rev. That fork is duckdb-rs 1.10505.0 (DuckDB 1.5.5) -plus the windmill commits; `duckdb.tar.gz` is left byte-identical to upstream's and -`crates/libduckdb-sys/windmill/0*.patch` are applied to the extracted sources at build -time, in order, so `git diff` against `duckdb/duckdb-rs` shows the whole delta as text. -`0001` adds the setting and the exemption, `0002` extends the lock to -`max_temp_directory_size`. `crates/libduckdb-sys/windmill/README.md` in the fork carries -the rebase recipe. - -### The patches may not move a struct member - -The engine loads the **prebuilt** extensions from `extensions.duckdb.org` — httpfs, azure, -postgres, ducklake, parquet, and the rest of `EXTENSION_ALLOWLIST` — which are compiled -against the struct layouts of the release the engine claims to be. A patch that shifts a -member those extensions reach breaks them, and not loudly: the extension reads the -neighbouring field and `LOAD httpfs` **blocks forever** rather than failing, so every -DuckDB job hangs until its timeout. - -The first revision of `0001` declared its new `DatabaseInstance` member next to -`local_db_file_system`, which pushed `create_api_v1` — the extension C-API entry point — -8 bytes along, and every extension load hung. It is declared last for that reason, and -`lock_temp_directory` is declared at the end of `DBConfigOptions`' run of bools so it takes -a byte of padding the struct already had. - -The invariant is **no pre-existing member changes offset**, which is strictly stronger than -`sizeof` holding — the first attempt at that field went in next to `temporary_directory`, -kept `sizeof(DBConfigOptions)` at 920 by consuming interior padding, and still slid four -bools along by a byte each. A rebase must diff the full record layouts -(`clang++ -Xclang -fdump-record-layouts`, recipe in the fork's README), not the sizes. -`prebuilt_extensions_still_load` in the FFI crate is the end-to-end guard — a timeout, not -an assertion, because the failure mode is a hang — but it covers extension *entry*, not -every field an extension reads, so it does not substitute for the layout diff. - -Alternatives considered and rejected: vendoring a patched `libduckdb-sys` in this repo -would put a 6 MB binary tarball into windmill's history on every engine bump and would -need the FFI builder stage in `Dockerfile` to copy more than -`backend/windmill-duckdb-ffi-internal`; linking a prebuilt engine through -`DUCKDB_LIB_DIR` would drop the `bundled` build, so every developer and every CI job -would need a patched `libduckdb` on the box before `build_dev.sh` could work. - -## What stops the patches disappearing silently - -An unpatched engine compiles, links and passes every existing test. Three things catch it: - -- **The fork's build script** asserts each patch's marker string is present in the patched - sources after applying it, and panics if one no longer applies. -- **`patched_engine_tests` in the FFI crate** runs a query that must spill, first - without the lock (asserting the fence stops it, which is what proves the query really - spills) and then with it (asserting it succeeds); it also pins that the lock leaves - neither `temp_directory` nor `max_temp_directory_size` settable, and that a configured - connection stops at its cap. It fails outright on a stock engine, where the `SET` is an - unrecognized parameter. CI runs it via the FFI crate's own `cargo test` step in - `backend-test.yml`. -- **The transform itself fails closed**: on a stock engine `SET lock_temp_directory=true` - errors, so every DuckDB job on an isolating worker fails immediately rather than - quietly losing the ability to spill. - -## Upstream - -Both patches are written against `duckdb/duckdb` `v1.5.5` in the shape upstream takes -changes. Besides the engine sources they carry `src/common/settings.json` (the settings -generator's input, regenerated with `scripts/generate_settings.py` and formatted with -clang-format 11.0.1), two sqllogictests under `test/sql/settings/`, and one line in -`test/api/test_reset.cpp` — that test requires every setting to survive a `RESET`, so an -irreversible one has to join the exclusion list `disabled_filesystems` and -`lock_configuration` are already on. They are `git format-patch` files, so they apply with -`git am`: - -```bash -git clone https://github.com/duckdb/duckdb.git && cd duckdb && git checkout v1.5.5 -git am .../crates/libduckdb-sys/windmill/0*.patch -GEN=ninja make && ./build/release/test/unittest "test/sql/settings/lock_temp_directory*" -``` - -`0001` is filed as -**[duckdb/duckdb#24694](https://github.com/duckdb/duckdb/pull/24694)**, against `main` -rather than `v1.5.5`. Filing was a human decision on purpose: their `CONTRIBUTING.md` asks -contributors not to submit LLM-generated pull requests, to discuss the change on GitHub -first, and to run CI on a fork before opening one. - -**`0002` is windmill-only and is not on #24694.** It is kept as a separate commit rather -than folded into `0001` for exactly that reason: `0001` stays byte-identical to what the -open PR carries, and `0002` applies to it verbatim as a second commit whenever a human -chooses to push it. That is the one sanctioned divergence; when it is pushed, say so here -and in the fork's `windmill/README.md`, and the "same change" rule below covers it too. - -**[duckdb/duckdb#24695](https://github.com/duckdb/duckdb/issues/24695)** states the -underlying problem without prescribing a fix, and is where a different design would land: -`lock_temp_directory` is one shape, and an enforceable `allowed_directories` would solve it -equally well. Watch the issue rather than the PR for whether this fork can be retired. - -`0001` and #24694 are the same change and must stay that way. They differ only -where the base version forces it: the `DUCKDB_SETTING_ALIAS` indices, `vfs` versus -`db.config.file_system` in `FileSystem::GetLocal`, and the sqllogictest directory -placeholder. Nothing else should diverge. Note that the build applies neither the `test/` -hunks nor `settings.json` (`NOT_IN_TARBALL` in `build_windmill_patch.rs`), so drift in -those is invisible here and only surfaces when #24694 is rebased. - -Until it lands in a released DuckDB the fork is the delivery mechanism, and the exit path -is to delete `crates/libduckdb-sys/windmill/` and go back to the crates.io crate. diff --git a/docs/external-instance-datatables.md b/docs/external-instance-datatables.md index acfb93b90a..38e810b03d 100644 --- a/docs/external-instance-datatables.md +++ b/docs/external-instance-datatables.md @@ -83,6 +83,6 @@ Worth knowing while testing: - A worker needs the `postgresql` and `duckdb` tags for those jobs (`update config set config = jsonb_set(config, '{worker_tags}', …) where name = 'worker__default'`). -- DuckDB jobs load `libwindmill_duckdb_ffi_internal.so` by name, so a binary built into its own - `CARGO_TARGET_DIR` needs that library on `LD_LIBRARY_PATH`. +- DuckDB jobs run `windmill_duckdb_runner` from next to the worker binary, so a binary built + into its own `CARGO_TARGET_DIR` needs `DUCKDB_RUNNER_PATH` pointed at the runner. - Setup holds the lifecycle lock for its whole run, so a settings save during it waits. diff --git a/docs/fork-object-storage.md b/docs/fork-object-storage.md new file mode 100644 index 0000000000..7428119f97 --- /dev/null +++ b/docs/fork-object-storage.md @@ -0,0 +1,68 @@ +# Fork-isolated workspace object storage + +A fork clones its parent's `large_file_storage` settings, so without isolation it reads and +writes the parent's objects: a script iterating in a fork overwrites production's files. Each +storage the fork isolates (a `fork_storage_namespace` row, chosen at fork creation, default +isolated) instead maps logical keys: + +- **Writes** (put, multipart, delete, copy destination) go to `__wm_forks/<fork segment>/<key>`, + the same one-component segment DuckLake's fork namespaces use (`fork_data_dir_segment`). +- **Reads** try the fork's own key, then each ancestor's mapping, nearest first, then the root's + raw key. They stop at the first ancestor whose storage is a different one + (`lfs_entry_storage_ref`): its keys are not in this bucket. A shared fork maps like its parent. +- **Listings** show the workspace's own objects only, as logical keys. +- **Deletes** remove the fork's copy; an ancestor's object stays readable through it. + +The mapping (`windmill_common::fork_storage::ForkStorageKeys`) is applied wherever Windmill +turns a workspace-storage key into a storage operation: the `ForkStore` object-store wrapper +(`windmill_object_store::fork_store::workspace_object_store`) for every server-side helper, and +key rewriting in the S3 proxy's raw S3 forwarding (URI key, list `prefix`/`start-after`/`marker` +and response keys, `x-amz-copy-source`). A named resource (`s3_resource_path`) is not workspace +storage and is never mapped. A workspace whose keys are mapped is refused its workspace +storage's own credentials (`s3_resource_info`, the duckdb/polars settings endpoints): a client +holding them would write past the mapping. + +Not mapped, on purpose: AI sessions and volumes (their keys already carry the workspace id), +SMTP attachments (job-id keys), the storage usage count (it counts the whole bucket). Known +gaps: the worker's result-cache hash HEADs the logical key unmapped, and a read of an object +the fork does not own costs one HEAD per chain level before the GET. + +## Invariants + +- **`__wm_forks/` is reachable only through the workspace's own chain.** A key under it maps to + itself when it is in the workspace's own area (writes) or an area of the chain (reads), and is + refused otherwise; listings hide it. This is also what keeps DuckLake working: its fork data + paths arrive already prefixed, and its defer attaches read ancestors' raw keys through the + read chain. Every workspace gets the rule, isolating or not, so pre-existing forks' lakes keep + working. +- **No `.` or `..` key segments**, in any workspace: the proxy forwards mapped keys in a URL, + where they collapse and would climb out of the fork's prefix. +- **The prefix derives from the workspace id**, so an isolating fork's id cannot be changed + (`change_workspace_id` refuses): under a new id it would see none of its objects. Nor can an + isolated storage be repointed, since the purge targets the storage recorded at creation. +- **A shared lake needs its storage shared**: its files must land at the parent's keys, where the + parent's catalog looks for them. Fork creation refuses the other combination. +- **Children before parents**: deleting a fork that has forks of its own is refused when anything + in its chain isolates a storage, shared forks included. A child reads through, or writes into, + the isolating prefix via that link, and without it the child's chain would map like the root's. +- **Deletion and same-id creation are serialized** on the `fork:<id>` advisory lock, and a purge + skips an id that exists again: the rows are then the new fork's. The proxy caches only the raw + client, never a mapping, so fork creation and deletion invalidate the one mapping cache. +- **Deletion always purges** the fork's area of each isolated storage, post-commit, from the + storage identity recorded at creation: nothing can reach it once the fork is gone. Rows have + no FK and outlive the workspace when the purge fails; creating a fork with the same id retries + them and refuses while they cannot be purged, since a same-id fork would read them. +- Isolation is a per-fork-creation choice (`shared_storages` on create-fork), never inherited. + Forks created before the registry existed have no rows and keep sharing. + +## Requiring isolation + +The `RequireIsolatedForks` protection rule on a workspace makes its forks leave nothing shared +with it, for every user the ruleset does not exempt (admins always are): no `shared_storages`, +no `shared_ducklakes`, and every data table whose database it owns cloned rather than kept as a +pointer. A data table whose database another workspace owns is left alone: that is not its data. +A clone governed from another workspace still has its own database, so it is not exempt. It is +checked against the workspace being forked, in +`create_workspace_fork` and in the git-branch pre-check (so a refused fork leaves no branch +behind), and the data table part again under the parent's `lock_fork_datatables`, which data table +edits also take: a table added between the two would otherwise reach the fork as a pointer. diff --git a/docs/operator-builder-rights.md b/docs/operator-builder-rights.md index 4db2a69511..8ace42a1e5 100644 --- a/docs/operator-builder-rights.md +++ b/docs/operator-builder-rights.md @@ -1,13 +1,25 @@ # Operator builder rights -`operator_settings.builder_flows` lets every operator of a workspace compose flows out of runnables -that already exist. It does not make them authors: the boundary the operator role draws is -**authoring code and running arbitrary code**, and this does not move it. +Two workspace settings, `operator_settings.builder_flows` and `operator_settings.builder_apps`, +that let every operator of that workspace compose flows and full-code apps out of runnables that +already exist. Neither lets them author backend code or run arbitrary code on a worker, the +boundary the operator role draws. The app right does let them write the app's frontend code, +which runs in the viewer's browser and is why that right rests on sandbox isolation. -It is a write right, unlike the visibility flags beside it, and unlike the withdrawable rights in -`docs/operator-write-rights.md` it is granted on request and costs a seat. Read it with -`windmill_common::workspaces::operator_can_build_flows` (60s cache, shared with the withdrawable -rights) and gate a write with `check_operator_can_build_flows`. +They are granted **independently**, because the two are not equally verifiable. A composed flow is +checked in full server-side (`check_flow_is_composition_only` refuses everything carrying code). +A full-code app is a browser-built bundle no server-side check can read, and rests instead on +forced `sandbox` isolation plus the viewer consent prompt. An admin may reasonably want the first +without the second, so **never gate on "either"**: a gate that does authorizes the kind its +workspace never granted, which is the whole point of the split. `BuilderKind` exists to make each +call site say which one it means. + +These are write rights, unlike the visibility flags beside them, and unlike the withdrawable +rights in `docs/operator-write-rights.md` they are granted on request and cost a seat. Read them +with `windmill_common::workspaces::operator_builder_rights` (60s cache, shared with the +withdrawable rights), which returns an `OperatorBuilderRights { flows, apps }`, and gate a write +with `check_operator_can_build`, naming the `BuilderKind`. `.any()` is only for surfaces that are +genuinely not per-kind: the seat a membership costs, and listing drafts. ## What the check has to cover @@ -49,25 +61,131 @@ Call it on every write **and** every preview: `run_preview_flow_job` and it the way to run what the write path refuses. A flow draft goes through `validate_operator_flow` too: a developer who loads a builder's draft in the editor runs its code as themselves. +The same reasoning applies to a builder-authored app, with one extra step. `execute_component` +resolves the runnable it runs on the root handle, so `validate_operator_composed_app` checks every +referenced path under the caller's RLS and refuses hub ones. For a script it checks the version a +run would pick: grants are per version, and a path reused after its versions were archived starts +with none while the archived ones keep theirs. But it has to check **two** surfaces, +because they are not the same list: the policy's `script/<path>` and `flow/<path>` triggerables, +and the by-path entries of the app value's `runnables` map, which is what the editor resolves a +`runnable_id` against and sends. Read only that map, and refuse an entry whose `type`, `path` or +`runType` is not text. + +Reading a triggerable key is not a `split_once(':')`: `execute_component` looks up +`format!("{component}:{path}")` with an unrestricted component string, so `a:b:script/x` resolves +at run time for `component = "a:b"`. Every colon is a possible split, so the check validates every +suffix that parses as a runnable rather than guessing which one a request will use. + +What makes those checks bind is that **`ExecutionMode::Viewer` is refused for a builder app**. In +Viewer mode `execute_component` falls back to a default triggerable for any `script/`/`flow/` +path, so the policy stops being the list of what the app may invoke, and the job runs as the +*viewer*: an admin who merely opened the app would run anything in the workspace as themselves. +`Publisher`, `Guest` and `Anonymous` have no such fallback; all three run as the publisher. If you ever relax the Viewer refusal, the +deploy-time path checks above stop being an authorization boundary. + +## The two raw-app deploy paths are not equivalent + +`create_app_raw` / `update_app_raw` are multipart: the browser already built the bundle, and +nothing server-side compiles anything. Builders use these. + +`create_app_raw_source` / `update_app_raw_source` push a bundler CLI over caller-supplied `files` +as a job **on a worker**, which is arbitrary code execution and is why they already require +`jobs:run` on top of `apps:write`. They stay closed to operators, builder rights or not. Do not +"tidy" the exception away: it costs builders nothing, because the browser and the CLI both bundle +locally and deploy through the multipart endpoints. + +A builder-authored app is forced to `policy.sandbox = true`. That is what makes it safe to let an +operator publish a bundle nobody reviewed: without it the bundle runs same-origin with each +viewer's Windmill session. The same check refuses a `rawscript/<sha>` key in either triggerables +map, since that key is the deployed app's authorization to run caller-supplied `raw_code` hashing +to it. It reads the value as stored, NUL escapes stripped: a stripped NUL can turn a key it +ignored into `inlineScript`. + +`update_app` takes a builder too, but settings only: the deploy panel saves a deployed full-code +app's access and frontend scopes through it with no value. It reaches the same check, so a builder +can no more switch the sandbox off there than on deploy. + +A builder's **draft** goes through the same `check_operator_composed_app` as its deploy, with +`BuilderAppWrite::Draft`: an admin may open it in the editor or deploy it as it stands, so any +rule added for deploys must hold for drafts too. Where the two differ, `write` decides: a deploy +fills in an omitted sandbox or mode, since it stores the policy it checked, while a draft skips +`triggerables_v2` and must not name another user's run identity. Every frontend writer of a +builder draft must conform the policy first with `conformBuilderAppPolicy`, since a policy loaded +from someone else's app breaks these rules: the raw-app editor component does, which covers both +the standalone editor and the AI Sessions one, and so does the AI chat. + +The raw-app editor previews an app isolated only when its policy has `sandbox`, and otherwise runs +the bundle same-origin with the session of whoever opens it. A builder's draft is therefore +held to the same rule as its deploy: `update_draft` refuses one whose `policy.sandbox` is not +`true`, so whatever an admin opens of an operator's, deployed or drafted, previews isolated. +Turning the sandbox off in their own editor stays that admin's explicit choice. It also refuses +a draft naming a runnable the builder cannot read, or a hub one, like the deploy: the editor +preview runs them as whoever opens it, and admits any path for an admin. That covers the +policy's legacy `triggerables` too, `rawscript/` keys included: every deploy of a draft +carries it through untouched, so an admin deploying the draft would publish it. Its +`triggerables_v2` is not checked: every deploy of a draft rebuilds it from the runnables, the +preview never reads it, and a copy gone stale since the last deploy would otherwise block +autosave. `Viewer` mode is refused in a draft as on deploy: the deploy panel shows it as +members-only, so an admin deploying the draft would publish it unawares. The builder's editor +switches it to `Publisher` on load, since that panel offers no way out of it. A draft naming a +run identity other than its builder is refused for the same reason: a builder's own deploy resets +it, but an admin's one-click draft deploy preserves it without showing it. The builder's editor +drops another user's identity on load, which an app that user deployed carries. A builder in +`wm_deployers` is the exception: like any member, their deploy may keep another identity, which +was judged acceptable for operators in that group (WIN-2536) and is the same for composed flows. + +Reading a triggerable key at every colon copies it once per colon, so the check refuses a key +over 512 bytes before splitting: a quadratic walk otherwise lets a sub-megabyte key allocate +gigabytes. A 255-character path plus a component name stays well under it. + ## Billing -An operator of a builder workspace consumes a full author seat: composing deployable artifacts -makes them an author, and there is no half-author. `consumes_operator_seat` is the seat-role -helper; the EE counting queries share `OPERATOR_SEAT_SQL` so the displayed, enforced and reported -numbers agree. The one exception is `get_user_usage` in `stats_ee.rs`: it is a compile-checked -`query!`, which cannot interpolate the constant, so it spells the predicate out. Change both -together. +An operator of a builder workspace consumes a full author seat. This is the one place that reads +"either right", and deliberately so: either one makes an operator an author of deployable +artifacts, and there is no half-author, so granting both costs no more than granting one. Do not +introduce per-right pricing — it turns one boolean into a capability matrix that billing, the cap +check and the displayed count would each have to agree on. -On cloud, `billable_seats` applies the same rule; see its doc for the out-of-repo invoice it must -match. +`consumes_operator_seat` is the seat-role helper; the EE counting queries share +`OPERATOR_SEAT_SQL` so the displayed, enforced and reported numbers agree. The one exception is +`get_user_usage` in `stats_ee.rs`: it is a compile-checked `query!`, which cannot interpolate the +constant, so it spells the predicate out. Change both together. On cloud, `billable_seats` applies +the same rule; see its doc for the out-of-repo invoice it must match. -Granting the right runs `check_seat_cap_for_operator_builder`, which prices the change by counting -seats twice rather than by counting the workspace's operators: an operator who already authors -elsewhere must not be charged again, so re-saving settings that already have the right on is a -zero delta and never blocks. +Granting the first right runs `check_seat_cap_for_operator_builder`, which prices the change by +counting seats twice rather than by counting the workspace's operators: an operator who already +authors elsewhere must not be charged again. Adding the second right later, or re-saving settings +that already have one on, is a zero delta and never blocks. ## Accepted risks +- A builder raw app may declare `frontend_sdk_scopes`, and `mint_raw_app_sdk_token` mints as the + *viewer*. A consenting admin therefore hands the bundle a 12h admin-identity token within the + curated scope list. The viewer consent prompt is the gate, shown by the editor preview as well + as the deployed app, before any token is minted. The lever, if this is ever revisited, + is dropping `variables:read` / `resources:read` / `jobs:run` from `FRONTEND_SDK_ALLOWED_SCOPES` + for builder apps. +- The raw-app editor preview runs an app's runnables as whoever has the editor open, where the + deployed app runs them as its publisher. An admin opening a builder's app in the editor lets its + frontend code run, with the admin's rights, any runnable the builder can read. Running as the + draft's author instead would need a preview that ignores unsaved edits to the runnable list. +- A builder may make an app public (`ExecutionMode::Anonymous`): anyone with the URL runs the + runnables its policy names, as the builder. Refusing it is the workspace's call, through the + `RestrictAnonymousAppDeployment` protection rule. A `Guest` app is the same with a login in + front: anyone the instance's identity provider admits, member or not, once guest access is + enabled. `RestrictGuestAppDeployment` refuses it. +- A builder raw app may set `allow_user_resources` on a runnable's inputs, and the bundle picks the + `$res:` path it sends. `build_args` resolves that path as the *viewer*, with no prompt, into a + job that runs as the builder. Getting a value out takes a guessable path and a readable script + that returns, logs or sends its input. Developers can do the same; the lever is refusing a + non-empty `allow_user_resources` (and `s3_inputs[].allow_user_resources`) for builders. +- A builder's delete or settings-only update reads the app's kind before the write, not under a + lock held through it. An admin converting that app to low-code in between lets the builder's + request land on the low-code app; the builder already has write access to its path. +- A builder's draft carries no run identity other than the builder's own, and deploying one that + carries none makes the deployer its run identity, as any deploy does. An admin deploying such a + draft, from the editor or Compare & Deploy, therefore publishes the builder's code running as + that admin; the deploy is the admin's explicit act, as it is for a developer's draft. - All-or-nothing per workspace: there is no per-user builder role. - `operator_settings` is git-synced, so a pull can flip every operator's class in a workspace and the billed seat count with it. diff --git a/docs/operator-write-rights.md b/docs/operator-write-rights.md index 2c18ecd290..a1421400f0 100644 --- a/docs/operator-write-rights.md +++ b/docs/operator-write-rights.md @@ -54,6 +54,32 @@ It refuses with `PermissionDenied` (403), never `NotAuthorized` (401): the front uncaught 401 as an expired session and logs the user out, so 401 here ejects an operator from the app rather than telling them why. Both integration tests assert the status for that reason. +## Drafts + +An operator may save a draft of a kind they could deploy, and no other: a resource or variable +draft always, since no operator setting gates those routes; a schedule draft while they hold +`manage_schedules`, a trigger draft (every trigger kind, native ones included) while they hold +`manage_triggers`, a flow or full-code app draft under `builder_flows` / `builder_apps`. +drafts.rs `require_can_write_path` asks `operator_can_draft`, which reads the same cached rights +as the router gate, and `UserDraftItemKind::manage_kind` maps each draft kind to its right. The AI +session chat writes resources, variables, schedules and triggers only as drafts and then deploys +them, so without this rule an operator who may create a schedule on its page could not ask the +chat for one. + +A secret variable draft is stored as an `$encrypted:` marker and decrypted by the variable create +and update routes on deploy. Those routes accept the marker from any caller, so a draft gives an +operator nothing the direct route does not. + +The schedule, trigger, resource and variable list routes append an operator's draft-only rows +under the same `operator_can_draft` check, so a saved draft shows on its list page exactly while +the operator may still save it. + +Deploying a draft goes through the ordinary create and update routes, so the router gate is still +what decides the write. The draft rule only has to agree with it: a draft the gate would refuse to +deploy should not be saved in the first place. The frontend mirrors the rule in `roleCanDraft` +(`editRights.ts`), which the chat's `write_schedule_draft` / `write_trigger_draft` capabilities +come from. + ## In the UI The shared lists (`TriggerList`, `SchedulesList`, `NativeTriggerTable`) derive a per-row `canEdit` diff --git a/flake.nix b/flake.nix index f005644e3d..2a1d2699c8 100644 --- a/flake.nix +++ b/flake.nix @@ -78,15 +78,16 @@ ]; # --------------------------------------------------------------- - # Prebuilt V8 binary (must match version in Cargo.toml) + # Prebuilt V8 binary (must match the `v8` pin in backend/Cargo.toml). + # The simdutf variant: deno_core enables that feature of the v8 crate. # --------------------------------------------------------------- rustyV8Archive = let - version = "137.1.0"; + version = "150.4.0"; target = stdenv.hostPlatform.rust.rustcTarget; sha256 = { x86_64-linux = - "sha256-Tiscfy2bzYGR3s0T+SC1IB3xWvTVpVcSEdjq3MCRoRw="; + "sha256-9IdiyhDR8fxgWkQcWuQw7Izh6egPFNePvELLh4wwtHY="; aarch64-linux = lib.fakeHash; x86_64-darwin = lib.fakeHash; aarch64-darwin = lib.fakeHash; @@ -94,7 +95,7 @@ in pkgs.fetchurl { name = "librusty_v8-${version}"; url = - "https://github.com/denoland/rusty_v8/releases/download/v${version}/librusty_v8_release_${target}.a.gz"; + "https://github.com/denoland/rusty_v8/releases/download/v${version}/librusty_v8_simdutf_release_${target}.a.gz"; inherit sha256; }; diff --git a/frontend/e2e/global-setup.ts b/frontend/e2e/global-setup.ts index db27741a5a..6d10c53d92 100644 --- a/frontend/e2e/global-setup.ts +++ b/frontend/e2e/global-setup.ts @@ -47,18 +47,10 @@ async function globalSetup(config: FullConfig) { await page.waitForURL('**/') if (!process.env.SKIP_HUB_SYNC) { - await page.locator('#home-search-input').waitFor({ state: 'visible' }) - await page.locator('#home-search-input').fill('u/admin/hub_sync') - - const hubSyncBtn = page.locator('text=u/admin/hub_sync').first() - await hubSyncBtn.waitFor({ state: 'visible' }) - await hubSyncBtn.click() - - const runBtn = page.locator('#run-form-run-button') - await runBtn.waitFor({ state: 'visible' }) - await runBtn.click() - await page.waitForURL(/\/run\/.+/) - await page.locator('text=Success').waitFor({ timeout: 30000, state: 'visible' }) + const res = await page.request.post(`${baseURL}/api/settings/sync_cached_resource_types`) + if (!res.ok()) { + throw new Error(`Resource type sync failed: ${await res.text()}`) + } } // Save the authenticated state await context.storageState({ path: './e2e/auth.json' }) diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 2f5ea5b721..30ac859fce 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -1,12 +1,12 @@ { "name": "@windmill-labs/components", - "version": "1.827.0", + "version": "1.841.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@windmill-labs/components", - "version": "1.827.0", + "version": "1.841.0", "hasInstallScript": true, "license": "AGPL-3.0", "dependencies": { @@ -95,19 +95,19 @@ "vscode-languageclient": "~9.0.1", "vscode-uri": "~3.1.0", "vscode-ws-jsonrpc": "~3.5.0", - "windmill-parser-wasm-asset": "1.753.0", + "windmill-parser-wasm-asset": "1.830.0", "windmill-parser-wasm-csharp": "1.510.1", "windmill-parser-wasm-go": "1.761.0", "windmill-parser-wasm-java": "1.510.1", "windmill-parser-wasm-nu": "1.510.1", "windmill-parser-wasm-php": "1.647.1", - "windmill-parser-wasm-py": "1.782.0", + "windmill-parser-wasm-py": "1.830.0", "windmill-parser-wasm-r": "1.668.1", "windmill-parser-wasm-regex": "1.764.0", "windmill-parser-wasm-ruby": "1.526.1", "windmill-parser-wasm-rust": "1.647.1", "windmill-parser-wasm-ts": "1.695.0", - "windmill-parser-wasm-wac": "1.668.6", + "windmill-parser-wasm-wac": "1.830.0", "windmill-parser-wasm-yaml": "1.770.0", "windmill-sql-datatype-parser-wasm": "1.512.0", "windmill-utils-internal": "1.8.2", @@ -14644,9 +14644,9 @@ } }, "node_modules/windmill-parser-wasm-asset": { - "version": "1.753.0", - "resolved": "https://registry.npmjs.org/windmill-parser-wasm-asset/-/windmill-parser-wasm-asset-1.753.0.tgz", - "integrity": "sha512-zpJhjvcU8EWRoOJzas/nRGKjGdQnvzeB9GOxP+Mdmnk8BFk3uehsmHS2Krxyjo36fUrCHqobbnffEqf0g3LIGg==" + "version": "1.830.0", + "resolved": "https://registry.npmjs.org/windmill-parser-wasm-asset/-/windmill-parser-wasm-asset-1.830.0.tgz", + "integrity": "sha512-q4HSaMOd5cF8pmfPcEGiGeQbO8vhtv89us7zbO12IlgpxpWT8ojvw66J75y4yUt1PaEuaoztSaX8Gkxxn/6MXw==" }, "node_modules/windmill-parser-wasm-csharp": { "version": "1.510.1", @@ -14674,9 +14674,9 @@ "integrity": "sha512-u2qaMkupSdhJibxvkLh3r/y36IARvnYNTLXWvOKxcQ0G/BPUB4+yF5o/yf47vv9zUV5WZv4mrdsKDt/pZDYeDg==" }, "node_modules/windmill-parser-wasm-py": { - "version": "1.782.0", - "resolved": "https://registry.npmjs.org/windmill-parser-wasm-py/-/windmill-parser-wasm-py-1.782.0.tgz", - "integrity": "sha512-ZnpEvhbffaJI+Uq7HH1mVO6kUgR4uiAIIxaLa30Pqb1/oz0h4abT6W7bFOApIE5X9SDOuycoaDBEr9Ogm6ZLzQ==" + "version": "1.830.0", + "resolved": "https://registry.npmjs.org/windmill-parser-wasm-py/-/windmill-parser-wasm-py-1.830.0.tgz", + "integrity": "sha512-+P4mIyp3lXkgjsr3/20Oc31ank8orQDd4K/v8TnjTQnCyxyy+VB9rynLESnkH6OlcEVSk2qf9pDM9c367E8DoQ==" }, "node_modules/windmill-parser-wasm-r": { "version": "1.668.1", @@ -14704,9 +14704,9 @@ "integrity": "sha512-9EFxeRZWmfb7EyhSlcG7dzTTKETPRYAvpRlxxLkhhtI5I219wFgI7kwrMpz4stXHJj/aqBknVv66NQHRstSJmw==" }, "node_modules/windmill-parser-wasm-wac": { - "version": "1.668.6", - "resolved": "https://registry.npmjs.org/windmill-parser-wasm-wac/-/windmill-parser-wasm-wac-1.668.6.tgz", - "integrity": "sha512-/ovcLWlIO+TQMrnWwcWoXquJI6hTZ+Zpo4POhV8z6e+pb4cVModGysASI9mERn2e9uj8/xSRmYqk54TLG8oUbQ==" + "version": "1.830.0", + "resolved": "https://registry.npmjs.org/windmill-parser-wasm-wac/-/windmill-parser-wasm-wac-1.830.0.tgz", + "integrity": "sha512-M67qPkzDnuMNWGrZTj9V4ajDoCQrTsQJ89UMHq308t5CtCdtiX8Z3freL+8SoRAG/dVlqQ8roK6dzncHIEM0hQ==" }, "node_modules/windmill-parser-wasm-yaml": { "version": "1.770.0", diff --git a/frontend/package.json b/frontend/package.json index 4515459ba3..7320d9c5f6 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@windmill-labs/components", - "version": "1.827.0", + "version": "1.841.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", @@ -161,19 +161,19 @@ "vscode-languageclient": "~9.0.1", "vscode-uri": "~3.1.0", "vscode-ws-jsonrpc": "~3.5.0", - "windmill-parser-wasm-asset": "1.753.0", + "windmill-parser-wasm-asset": "1.830.0", "windmill-parser-wasm-csharp": "1.510.1", "windmill-parser-wasm-go": "1.761.0", "windmill-parser-wasm-java": "1.510.1", "windmill-parser-wasm-nu": "1.510.1", "windmill-parser-wasm-php": "1.647.1", - "windmill-parser-wasm-py": "1.782.0", + "windmill-parser-wasm-py": "1.830.0", "windmill-parser-wasm-r": "1.668.1", "windmill-parser-wasm-regex": "1.764.0", "windmill-parser-wasm-ruby": "1.526.1", "windmill-parser-wasm-rust": "1.647.1", "windmill-parser-wasm-ts": "1.695.0", - "windmill-parser-wasm-wac": "1.668.6", + "windmill-parser-wasm-wac": "1.830.0", "windmill-parser-wasm-yaml": "1.770.0", "windmill-sql-datatype-parser-wasm": "1.512.0", "windmill-utils-internal": "1.8.2", diff --git a/frontend/scripts/fix-svelte-module-imports.js b/frontend/scripts/fix-svelte-module-imports.js index 9cec6265a0..fe4fde4959 100644 --- a/frontend/scripts/fix-svelte-module-imports.js +++ b/frontend/scripts/fix-svelte-module-imports.js @@ -16,9 +16,22 @@ // tarball. Copy the registry into the package and rewrite those imports // to point at it (mirrors how package-system-prompts.js bundles // `$system_prompts`). +// +// 3. Chat SDK: the `windmill-chat` alias (svelte.config.js) points at +// `chat-sdk/src/index.ts`, which escapes the package root the same way. +// Compile that entry point into the package and rewrite those imports. +// +// 4. `$lib/utils` from inside `utils/`: svelte-package turns it into `./`, +// which is the `utils/` directory (no index) rather than `utils.js`. +// Point a directory specifier with no index at its sibling module. +// +// A relative import that still escapes the package root, or an +// `import.meta.glob` left on an alias, fails the build: either one +// publishes fine and only breaks in the consumer's bundler. +import { execFileSync } from 'child_process' import { copyFileSync, existsSync, readdirSync, readFileSync, statSync, writeFileSync } from 'fs' import { fileURLToPath } from 'url' -import { dirname, join, relative, resolve } from 'path' +import { dirname, join, relative, resolve, sep } from 'path' const __filename = fileURLToPath(import.meta.url) const __dirname = dirname(__filename) @@ -29,8 +42,37 @@ const oauthConnectDest = join(packageDir, 'oauth_connect.json') copyFileSync(oauthConnectSrc, oauthConnectDest) -const IMPORT_SPECIFIER_RE = /(\bfrom\s*|\bimport\s*\(?\s*)(['"])(\.\.?\/[^'"]*\.(?:svelte|json))\2/g +const chatSdkSrc = resolve(__dirname, '..', '..', 'chat-sdk', 'src', 'index.ts') +const chatSdkDest = join(packageDir, 'chat-sdk') + +// File arguments make tsc ignore every tsconfig and emit only what the entry +// point reaches, which leaves out the React and AI SDK adapters. +execFileSync( + 'npx', + [ + 'tsc', + chatSdkSrc, + '--outDir', + chatSdkDest, + '--rootDir', + dirname(chatSdkSrc), + '--declaration', + '--target', + 'ES2021', + '--module', + 'ESNext', + '--moduleResolution', + 'bundler', + '--skipLibCheck' + ], + { stdio: 'inherit', cwd: resolve(__dirname, '..') } +) + +const IMPORT_SPECIFIER_RE = /(\bfrom\s*|\bimport\s*\(?\s*)(['"])(\.\.?(?:\/[^'"]*)?)\2/g const OAUTH_CONNECT_RE = /^(\.\.\/)+backend\/oauth_connect\.json$/ +const CHAT_SDK_RE = /^(\.\.\/)+chat-sdk\/src\/index\.ts$/ +const DIRECTORY_RE = /(^|\/)\.\.?$|\/$/ +const ALIASED_GLOB_RE = /import\.meta\.glob(?:<[^>]*>)?\(\s*\[?\s*['"]\$/ function* walk(dir) { for (const entry of readdirSync(dir)) { @@ -50,9 +92,13 @@ function relativeSpecifier(fromFile, toFile) { let rewrittenFiles = 0 let rewrittenImports = 0 +const unresolvable = [] for (const file of walk(packageDir)) { const content = readFileSync(file, 'utf-8') + if (ALIASED_GLOB_RE.test(content)) { + unresolvable.push(`${relative(packageDir, file)}: import.meta.glob on an alias`) + } let changed = false const updated = content.replace(IMPORT_SPECIFIER_RE, (match, prefix, quote, specifier) => { if (OAUTH_CONNECT_RE.test(specifier)) { @@ -60,10 +106,27 @@ for (const file of walk(packageDir)) { rewrittenImports++ return `${prefix}${quote}${relativeSpecifier(file, oauthConnectDest)}${quote}` } + if (CHAT_SDK_RE.test(specifier)) { + changed = true + rewrittenImports++ + return `${prefix}${quote}${relativeSpecifier(file, join(chatSdkDest, 'index.js'))}${quote}` + } + const target = resolve(dirname(file), specifier) + if (target !== packageDir && !target.startsWith(packageDir + sep)) { + unresolvable.push(`${relative(packageDir, file)}: ${specifier}`) + return match + } + if (DIRECTORY_RE.test(specifier)) { + if (!existsSync(join(target, 'index.js')) && existsSync(target + '.js')) { + changed = true + rewrittenImports++ + return `${prefix}${quote}${relativeSpecifier(file, target + '.js')}${quote}` + } + return match + } if (!specifier.endsWith('.svelte')) { return match } - const target = resolve(dirname(file), specifier) // A real `.svelte` component file: leave the import alone. if (existsSync(target)) { return match @@ -82,6 +145,14 @@ for (const file of walk(packageDir)) { } } +if (unresolvable.length > 0) { + console.error( + `fix-svelte-module-imports: ${unresolvable.length} import(s) a consumer cannot resolve:\n` + + unresolvable.join('\n') + ) + process.exit(1) +} + console.log( `fix-svelte-module-imports: rewrote ${rewrittenImports} import(s) in ${rewrittenFiles} file(s)` ) diff --git a/frontend/scripts/ui_builder_artifact.json b/frontend/scripts/ui_builder_artifact.json index c82e327126..82e53ad1a5 100644 --- a/frontend/scripts/ui_builder_artifact.json +++ b/frontend/scripts/ui_builder_artifact.json @@ -1,5 +1,5 @@ { "baseUrl": "https://pub-06154ed168a24e73a86ab84db6bf15d8.r2.dev", - "version": "d3fdb70", - "sha256": "8c894b3f02d5d1872a966c37d43314f05ce42900f7330bdcf45a18a772deb2b9" + "version": "6880a7f", + "sha256": "05d49a6ed4790b444058574ccb650c8d3882161bbf004c0f8c0370964e853367" } diff --git a/frontend/src/app.html b/frontend/src/app.html index 3c9e232e0f..d637491e74 100644 --- a/frontend/src/app.html +++ b/frontend/src/app.html @@ -3,6 +3,10 @@ <head> <meta charset="utf-8" /> <link rel="icon" href="/logo.svg" /> + <link rel="apple-touch-icon" href="/apple-touch-icon.png" /> + <meta name="theme-color" media="(prefers-color-scheme: light)" content="#fbfbfd" /> + <meta name="theme-color" media="(prefers-color-scheme: dark)" content="#3b4252" /> + <meta name="mobile-web-app-capable" content="yes" /> <style type="text/css"> .st2 { fill: #bcd4fc; diff --git a/frontend/src/lib/apiBaseUrl.svelte.ts b/frontend/src/lib/apiBaseUrl.svelte.ts new file mode 100644 index 0000000000..242a6aa9e0 --- /dev/null +++ b/frontend/src/lib/apiBaseUrl.svelte.ts @@ -0,0 +1,21 @@ +import { fromStore } from 'svelte/store' +import { instanceUi } from '$lib/instanceUi' + +const ui = fromStore(instanceUi) + +/** + * Base of every URL shown for an external client to call (webhooks, HTTP routes, push + * trigger endpoints, the CLI remote): the `api_base_url` instance setting, else the + * origin being browsed. Append `/api/...` to it. + * + * Not for URLs the editor itself calls or opens (captures, previews, OAuth popups, links + * to pages): those must stay on the browsing origin, where the session cookie lives. + * + * Reactive: the setting lands after page load, so read it inside a `$derived` or the + * template rather than caching the result. + */ +export function apiBaseUrl(): string { + const setting = ui.current?.api_base_url + const configured = typeof setting === 'string' ? setting.trim() : '' + return configured || window.location.origin +} diff --git a/frontend/src/lib/base.ts b/frontend/src/lib/base.ts deleted file mode 100644 index 0e8f2d71f6..0000000000 --- a/frontend/src/lib/base.ts +++ /dev/null @@ -1 +0,0 @@ -export let base: string = import.meta.env.VITE_BASE_URL ?? '' diff --git a/frontend/src/lib/components/AgentTrace.svelte b/frontend/src/lib/components/AgentTrace.svelte index 7f2a90e621..3d671f46c8 100644 --- a/frontend/src/lib/components/AgentTrace.svelte +++ b/frontend/src/lib/components/AgentTrace.svelte @@ -1,7 +1,6 @@ <script lang="ts"> import { ExternalLink, Globe } from 'lucide-svelte' import { JobService, type Job } from '$lib/gen' - import { base } from '$lib/base' import { msToReadableTimeShort } from '$lib/utils' import ChatCollapsibleCard from './copilot/chat/ChatCollapsibleCard.svelte' import ToolContentDisplay from './copilot/chat/ToolContentDisplay.svelte' @@ -141,7 +140,7 @@ {:else if entry.jobId} <a class="text-2xs text-accent inline-flex items-center gap-1 w-fit hover:underline" - href="{base}/run/{entry.jobId}?workspace={workspaceId ?? $operatingWorkspace}" + href="/run/{entry.jobId}?workspace={workspaceId ?? $operatingWorkspace}" target="_blank" rel="noreferrer" > diff --git a/frontend/src/lib/components/AppConnectInner.svelte b/frontend/src/lib/components/AppConnectInner.svelte index bea6023073..4dc05972ca 100644 --- a/frontend/src/lib/components/AppConnectInner.svelte +++ b/frontend/src/lib/components/AppConnectInner.svelte @@ -25,7 +25,7 @@ import { registryEntryFor, registryCcCapableFor, stripSandboxSuffix } from './oauthRegistry' import { createEventDispatcher, onDestroy, tick } from 'svelte' import Path from './Path.svelte' - import { ListRow, RadioCard, Skeleton } from './common' + import { Badge, ListRow, RadioCard, Skeleton } from './common' import { useListHighlight } from './common/listRow/listHighlight.svelte' import ApiConnectForm from './ApiConnectForm.svelte' import SearchItems from './SearchItems.svelte' @@ -33,7 +33,6 @@ import { sendUserToast } from '$lib/toast' import OauthScopes from './OauthScopes.svelte' import autosize from '$lib/autosize' - import { base } from '$lib/base' import Required from './Required.svelte' import Toggle from './Toggle.svelte' import { Pen, Search } from 'lucide-svelte' @@ -323,6 +322,15 @@ (registryCcCapable() && connectClient != '' && !(connects?.includes(connectClient) ?? false)) ) + /** The provider also has a browser sign-in, unavailable here only because the + * instance holds no OAuth client for it */ + let signInNeedsInstanceClient = $derived.by( + () => + (registryEntry()?.grant_types?.includes('authorization_code') ?? false) && + connectClient != '' && + !(connects?.includes(connectClient) ?? false) + ) + /** Clear CC inputs and scopes so a previous selection never leaks into a new one */ function resetClientCredentialsState() { supportsClientCredentials = false @@ -1400,11 +1408,7 @@ </div> {#if apiTokenApps[resourceType].img} <div class="mt-4 w-full overflow-hidden"> - <img - class="m-auto max-h-60" - alt="connect" - src={base + apiTokenApps[resourceType].img} - /> + <img class="m-auto max-h-60" alt="connect" src={apiTokenApps[resourceType].img} /> </div> {/if} {/if} @@ -1515,14 +1519,14 @@ {#if supportsClientCredentials} <div class="flex flex-col gap-1"> <h3 class="text-sm font-semibold text-emphasis mb-1">Authentication</h3> - {#if ccOnly || ccBringYourOwn} + {#if (ccOnly || ccBringYourOwn) && !signInNeedsInstanceClient} <div class="text-xs text-secondary font-normal mb-2"> {#if useSharedInstanceCreds} {resourceType} connects server-to-server using the credentials configured for this - instance. The token is acquired and refreshed automatically. + instance. {:else} - {resourceType} connects server-to-server. Enter a client ID and secret; the token is - acquired and refreshed automatically. + {resourceType} connects server-to-server with the client credentials grant. Enter a + client ID and secret. {/if} </div> {:else} @@ -1535,17 +1539,24 @@ > <RadioCard label={`Sign in through ${resourceType}`} - description="Opens a browser window to log in and authorize. Connects as you." + description={signInNeedsInstanceClient + ? `Authorization code grant. Needs an OAuth client for ${resourceType} in the instance settings, added by a superadmin.` + : 'Authorization code grant. Opens a browser window to log in and authorize. Connects as you.'} selected={!useClientCredentials} onSelect={selectAuthCodeGrant} + disabled={signInNeedsInstanceClient} + badge={signInNeedsInstanceClient ? setupNeededBadge : undefined} /> + {#snippet setupNeededBadge()} + <Badge verySmall class="px-2">Instance setup needed</Badge> + {/snippet} <RadioCard label={useSharedInstanceCreds ? 'Use the configured instance credentials' : 'Use a client ID and secret'} description={useSharedInstanceCreds - ? "Runs server-to-server with this instance's credentials. No input needed." - : 'Runs server-to-server. Best for automation or service accounts.'} + ? "Client credentials grant. Runs server-to-server with this instance's credentials. No input needed." + : 'Client credentials grant. Runs server-to-server. Best for automation or service accounts.'} selected={useClientCredentials} onSelect={() => enableClientCredentials()} /> diff --git a/frontend/src/lib/components/ArgInput.svelte b/frontend/src/lib/components/ArgInput.svelte index 7511fc3576..ce64d7d231 100644 --- a/frontend/src/lib/components/ArgInput.svelte +++ b/frontend/src/lib/components/ArgInput.svelte @@ -41,7 +41,6 @@ import MultiSelect from './select/MultiSelect.svelte' import { safeSelectItems } from './select/utils.svelte' import S3ArgInput from './common/fileUpload/S3ArgInput.svelte' - import { base } from '$lib/base' import { getJsonSchemaFromResource } from './schema/jsonSchemaResource.svelte' import AIProviderPicker from './AIProviderPicker.svelte' import AiDecisionQuestionsEditor from './AiDecisionQuestionsEditor.svelte' @@ -609,7 +608,7 @@ {#if value && typeof value == 'string' && value?.startsWith('$res:')} Linked to resource <a target="_blank" - href="{base}/resources#/resource/{value.slice(5)}" + href="/resources#/resource/{value.slice(5)}" class="text-blue-500 underline" >{value.slice(5)} <span class="inline-block -mb-0.5"><ExternalLink size={14} /></span></a > diff --git a/frontend/src/lib/components/AuthSettings.svelte b/frontend/src/lib/components/AuthSettings.svelte index f211650df2..cdf847e8fb 100644 --- a/frontend/src/lib/components/AuthSettings.svelte +++ b/frontend/src/lib/components/AuthSettings.svelte @@ -90,14 +90,15 @@ 'visma', 'sage_intacct', 'spotify', - 'teams', 'zoho', 'xero', 'apify', 'docusign', 'salesforce', 'outreach', - 'notion' + 'notion', + 'hubspot', + 'asana' ] // Providers whose registry entry (`backend/oauth_connect.json`) carries a // `sandbox` URL block. Each one gets a sibling `<name>_sandbox` dropdown @@ -119,6 +120,8 @@ const connectConfigTemplates: Record<string, any> = Object.fromEntries( Object.entries(oauthConnectRegistry) .filter(([, cfg]) => cfg && typeof cfg === 'object' && 'connect_config_template' in cfg) + // ms_teams has the pinned Teams tile instead: its tenant field fills the template. + .filter(([name]) => name !== 'ms_teams') .map(([name, cfg]) => [name, (cfg as any).connect_config_template]) ) const windmillBuiltinsTemplated = Object.keys(connectConfigTemplates) @@ -489,12 +492,13 @@ <div class="h-1"></div> <OAuthSetting login={false} name="slack" bind:value={oauths['slack']} /> <div class="h-6"></div> - <OAuthSetting login={false} name="teams" eeOnly={true} bind:value={oauths['teams']} /> + <OAuthSetting login={false} name="ms_teams" bind:value={oauths['ms_teams']} /> <div class="h-6"></div> {#each Object.keys(oauths) as k} {#if oauths[k] && !(oauths[k] && 'login_config' in oauths[k])} - {#if !['slack', 'teams'].includes(k) && oauths[k]} + <!-- 'teams' is the pre-rename key of ms_teams, kept for rolling upgrades --> + {#if !['slack', 'ms_teams', 'teams'].includes(k) && oauths[k]} {@const IconComponent = getOAuthProviderIcon(k) as any} {@const headerLabel = k.endsWith('_sandbox') ? `${k.slice(0, -'_sandbox'.length)} (sandbox)` diff --git a/frontend/src/lib/components/AutosaveIndicator.svelte b/frontend/src/lib/components/AutosaveIndicator.svelte index 76dc030c58..1e318ed9b2 100644 --- a/frontend/src/lib/components/AutosaveIndicator.svelte +++ b/frontend/src/lib/components/AutosaveIndicator.svelte @@ -142,7 +142,13 @@ let hintTimer: ReturnType<typeof setTimeout> | undefined const kindLabel = $derived( - itemKind === 'flow' ? 'flow' : itemKind === 'app' || itemKind === 'raw_app' ? 'app' : 'script' + itemKind === 'flow' + ? 'flow' + : itemKind === 'app' || itemKind === 'raw_app' + ? 'app' + : itemKind === 'data_pipeline' + ? 'pipeline' + : 'script' ) // Each false → true transition fires a hint (others > loaded). Seeded to diff --git a/frontend/src/lib/components/AutoscalingConfigEditor.svelte b/frontend/src/lib/components/AutoscalingConfigEditor.svelte index 3ebbb5d41c..885b6dd55c 100644 --- a/frontend/src/lib/components/AutoscalingConfigEditor.svelte +++ b/frontend/src/lib/components/AutoscalingConfigEditor.svelte @@ -15,15 +15,27 @@ import Select from './select/Select.svelte' import ScriptPicker from './ScriptPicker.svelte' import { sendUserToast } from '$lib/toast' + import { untrack } from 'svelte' interface Props { config: AutoscalingConfig | undefined worker_tags: string[] | undefined + /** Whether the draft config gives the group any tags (worker_tags or dedicated workers). */ + group_has_tags: boolean + /** Tags reported by the group's live workers, which for agent workers come from their token. */ + reported_tags: string[] disabled: boolean eeOnly?: boolean } - let { config = $bindable(), worker_tags, disabled, eeOnly = false }: Props = $props() + let { + config = $bindable(), + worker_tags, + group_has_tags, + reported_tags, + disabled, + eeOnly = false + }: Props = $props() let test_input: number = $state(3) let healthCheckLoading: boolean = $state(false) let healthCheckResult: { success: boolean; error?: string } | null = $state(null) @@ -54,7 +66,9 @@ } } - let collapsed: boolean = $state(true) + let noTagsToCount = $derived(!!config?.enabled && !group_has_tags && !config.custom_tags?.length) + + let collapsed: boolean = $state(untrack(() => !noTagsToCount)) </script> <Section @@ -99,6 +113,29 @@ </div> {/snippet} + {#if noTagsToCount} + <Alert + type="warning" + size="xs" + title="Queued jobs won't trigger autoscaling" + actions={reported_tags.length && !disabled + ? [ + { + label: `Use the tags these workers report: ${reported_tags.join(', ')}`, + onClick: () => { + if (config) config.custom_tags = [...reported_tags] + } + } + ] + : []} + > + Autoscaling counts waiting jobs on this group's worker tags, or on the custom tags under + Advanced, and this group has neither. Agent workers don't need either to run, since their tags + come from their token, but to scale on their queue set worker tags or custom tags to the tags + their token was issued with. + </Alert> + {/if} + <div class="flex flex-row gap-4"> <Label label="Min # of workers" disabled={config === undefined} class="grow min-w-0"> <span class="text-xs text-secondary">The minimum number of workers to scale down to</span> diff --git a/frontend/src/lib/components/BreadcrumbNavPicker.svelte b/frontend/src/lib/components/BreadcrumbNavPicker.svelte new file mode 100644 index 0000000000..1f053c0d92 --- /dev/null +++ b/frontend/src/lib/components/BreadcrumbNavPicker.svelte @@ -0,0 +1,122 @@ +<!-- +@component +The chevron after the breadcrumb's last segment: it opens the same picker a session's preview tab +uses — the workspace pages, then the folders with their flows, scripts and apps — and picking a +row navigates the app there. + +It lands among the current page's siblings: an item opens in its folder with the item +highlighted, a workspace page inside Pages with that page highlighted. +--> +<script lang="ts"> + import { ChevronDown } from 'lucide-svelte' + import { goto } from '$app/navigation' + import { page } from '$app/state' + import Popover from '$lib/components/meltComponents/Popover.svelte' + import PreviewRouterPicker, { type Scope } from './sessions/PreviewRouterPicker.svelte' + import { pageKey, parsePreviewItemRoute, type PreviewTarget } from './sessions/previewRouter' + import { editPathFor, leafKeyFor, viewPathFor, type WorkspaceItem } from './workspacePicker' + import { logFeatureUsage } from '$lib/utils/featureUsage' + import type { PageHeaderItem } from './pageHeaderRegistry.svelte' + + let { + item, + pagePath, + actingWorkspaceId, + iconSize = 14 + }: { + /** The item the page is about, to land in its folder. */ + item?: PageHeaderItem + /** The route of a workspace page, to highlight it among the pages. */ + pagePath?: string + /** Load from, and navigate within, this workspace rather than the one the app points at. */ + actingWorkspaceId?: string + iconSize?: number + } = $props() + + let isOpen = $state(false) + + // Two paths for one item, which differ on a draft: the header names it by the path it will + // deploy to, which is the folder the tree files it under, while its row is keyed by where it + // is stored, which is the path in an editor's URL. A viewer's URL is no help: a script page + // can be addressed by a version hash, so there the header's path is the row's. + const route = $derived(item?.path ? parsePreviewItemRoute(page.url.pathname) : null) + const currentItem = $derived.by<WorkspaceItem | undefined>(() => { + const kind = route?.kind ?? item?.kind + const path = route?.mode === 'edit' ? route.itemPath : item?.path + if (!kind || !path) return undefined + return { path, kind, raw_app: route?.raw_app, summary: item?.summary ?? '' } + }) + + // The item's own folder is its path minus the name. + const initialScope = $derived.by<Scope>(() => { + const parts = item?.path?.split('/') ?? [] + return parts.length >= 3 ? { kind: 'all', dir: parts.slice(0, -1).join('/') } : undefined + }) + const initialHighlight = $derived( + currentItem + ? leafKeyFor(currentItem.kind, currentItem.path) + : pagePath + ? pageKey(pagePath) + : undefined + ) + + // A page acting on another workspace than the app's (a session in a fork) keeps acting on it: + // the route reads `?workspace=` before the store. + function withWorkspace(href: string): string { + if (!actingWorkspaceId) return href + const sep = href.includes('?') ? '&' : '?' + return `${href}${sep}workspace=${encodeURIComponent(actingWorkspaceId)}` + } + + function hrefFor(target: PreviewTarget): string | undefined { + if (target.type === 'page') return target.href + if (target.type === 'item') + return target.mode === 'view' ? viewPathFor(target.item) : editPathFor(target.item) + return undefined + } + + /** The whole vocabulary of the `header_nav` / `pick` counter: what kind of destination was + * picked, never which one. */ + type PickKey = 'page' | 'item_view' | 'item_edit' + + function pickKey(target: PreviewTarget): PickKey | undefined { + if (target.type === 'page') return 'page' + if (target.type === 'item') return target.mode === 'view' ? 'item_view' : 'item_edit' + return undefined + } + + function pick(target: PreviewTarget) { + isOpen = false + const href = hrefFor(target) + if (!href) return + const key = pickKey(target) + if (key) logFeatureUsage('header_nav', 'pick', { key, workspace: actingWorkspaceId }) + goto(withWorkspace(href)) + } +</script> + +<Popover + placement="bottom-start" + usePointerDownOutside + excludeSelectors=".drawer" + disableFocusTrap + closeOnOtherPopoverOpen + bind:isOpen + openFocus="[data-workspace-picker-search]" + contentClasses="flex flex-col overflow-hidden" + class="shrink-0 flex items-center h-9 px-1.5 rounded text-tertiary hover:bg-surface-hover hover:text-primary transition-colors" + triggerAttrs={{ 'aria-label': 'Navigate to', title: 'Navigate to' }} +> + {#snippet trigger()} + <ChevronDown size={iconSize} class="flex-shrink-0" /> + {/snippet} + {#snippet content()} + <PreviewRouterPicker + {initialScope} + {initialHighlight} + {currentItem} + workspaceId={actingWorkspaceId} + onPick={pick} + /> + {/snippet} +</Popover> diff --git a/frontend/src/lib/components/CiTestResults.svelte b/frontend/src/lib/components/CiTestResults.svelte index 82bc81ea19..44888f8a0b 100644 --- a/frontend/src/lib/components/CiTestResults.svelte +++ b/frontend/src/lib/components/CiTestResults.svelte @@ -1,7 +1,6 @@ <script lang="ts"> import { ScriptService, type CiTestResult } from '$lib/gen' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' - import { base } from '$lib/base' import { CircleCheck, CircleX, Loader2, FlaskConical } from 'lucide-svelte' import { resource } from 'runed' @@ -57,14 +56,14 @@ <div class="w-3.5 h-3.5 rounded-full border border-tertiary"></div> {/if} <a - href="{base}/scripts/get/{test.test_script_path}?workspace={$operatingWorkspace}" + href="/scripts/get/{test.test_script_path}?workspace={$operatingWorkspace}" class="text-secondary hover:text-primary truncate" > {test.test_script_path} </a> {#if test.job_id} <a - href="{base}/run/{test.job_id}?workspace={$operatingWorkspace}" + href="/run/{test.job_id}?workspace={$operatingWorkspace}" class="text-tertiary hover:text-secondary text-2xs" > view run diff --git a/frontend/src/lib/components/CliHelpBox.svelte b/frontend/src/lib/components/CliHelpBox.svelte index 0bee33825c..e91b039328 100644 --- a/frontend/src/lib/components/CliHelpBox.svelte +++ b/frontend/src/lib/components/CliHelpBox.svelte @@ -2,10 +2,11 @@ import ClipboardPanel from './details/ClipboardPanel.svelte' import Section from './Section.svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + import { apiBaseUrl } from '$lib/apiBaseUrl.svelte' const operatingWorkspace = useOperatingWorkspace() - let url = $derived(`${window.location.protocol}//${window.location.hostname}/`) + let url = $derived(`${apiBaseUrl()}/`) </script> <Section label="CLI quick setup"> diff --git a/frontend/src/lib/components/CompareWorkspaces.svelte b/frontend/src/lib/components/CompareWorkspaces.svelte index 9696836dfd..5a22ed012d 100644 --- a/frontend/src/lib/components/CompareWorkspaces.svelte +++ b/frontend/src/lib/components/CompareWorkspaces.svelte @@ -65,7 +65,6 @@ import WorkspaceDeployLayout from './WorkspaceDeployLayout.svelte' import DeploymentRequestPanel from './deploymentRequest/DeploymentRequestPanel.svelte' import { userStore } from '$lib/stores' - import { base } from '$lib/base' import CompareModeToggle, { type CompareMode } from './CompareModeToggle.svelte' import CompareTargetPicker from './CompareTargetPicker.svelte' import { displayDate } from '$lib/utils' @@ -613,12 +612,13 @@ } async function fetchOnBehalfOfInfo(diffs: WorkspaceItemDiff[]) { - // Runnables carry an email; triggers/schedules carry `permissioned_as`. - // `getOnBehalfOf` handles the dispatch — we just need to skip kinds that - // have no on_behalf_of concept (resource, variable, folder, resource_type). + // Runnables carry an email; triggers/schedules and agents carry `permissioned_as`. + // `getOnBehalfOf` handles the dispatch (a resource that is not an agent has none) — we + // just need to skip kinds that have no on_behalf_of concept (variable, folder, resource_type). const itemsWithOnBehalfOf = diffs.filter( (d) => - ['flow', 'script', 'app', 'raw_app'].includes(d.kind) || isTriggerOrScheduleKind(d.kind) + ['flow', 'script', 'app', 'raw_app', 'resource'].includes(d.kind) || + isTriggerOrScheduleKind(d.kind) ) const pair = [ { workspace: currentWorkspaceId, side: 'fork' as const }, @@ -680,17 +680,22 @@ }) ) + /** Triggers, schedules and agents record who they run as by principal, the rest by address. */ + function usesPrincipal(kind: Kind): boolean { + return kind === 'trigger' || isTriggerOrScheduleKind(kind) || kind === 'resource' + } + /** * Get the on_behalf_of value for deployment based on user's choice. - * Returns an email for flows/scripts/apps, or permissioned_as (u/username, g/group) for triggers/schedules. + * Returns an email for flows/scripts/apps, or permissioned_as (u/username, g/group) for + * triggers/schedules and agents. */ function getOnBehalfOfForDeploy(itemKey: string, kind: Kind): string | undefined { const choice = onBehalfOfChoice[itemKey] if (choice === 'target') return getTargetOnBehalfOf(itemKey) if (choice === 'custom') { const details = customOnBehalfOf[itemKey] - const wantsPermissionedAs = kind === 'trigger' || isTriggerOrScheduleKind(kind) - return wantsPermissionedAs ? details?.permissionedAs : details?.email + return usesPrincipal(kind) ? details?.permissionedAs : details?.email } // 'me' or undefined = don't pass, backend will use deploying user's identity return undefined @@ -702,7 +707,7 @@ * returning undefined clears the source item's value rather than keeping it. */ function getOnBehalfOfPermissionedAsForDeploy(itemKey: string, kind: Kind): string | undefined { - if (kind === 'trigger' || isTriggerOrScheduleKind(kind)) return undefined + if (usesPrincipal(kind)) return undefined if (onBehalfOfChoice[itemKey] !== 'custom') return undefined return customOnBehalfOf[itemKey]?.permissionedAs } @@ -808,7 +813,19 @@ } let deploymentErrorMessage = $state('') - let allowBehindChangesOverride = $state(false) + // The override acknowledges the outdated items listed next to it, not the + // selection, so it holds while every outdated item is one the user ticked it + // for: a refresh bringing in a new one asks again, one leaving the list does not. + let acknowledgedBehindKeys = $state<Set<string> | undefined>() + let allowBehindChangesOverride = $derived( + acknowledgedBehindKeys != undefined && + itemsWithBehindChanges.every((d) => acknowledgedBehindKeys!.has(getItemKey(d))) + ) + function setBehindChangesOverride(allow: boolean) { + acknowledgedBehindKeys = allow + ? new Set(itemsWithBehindChanges.map((d) => getItemKey(d))) + : undefined + } async function isComparisonUpToDate(): Promise<boolean> { if (!comparison) { @@ -1117,18 +1134,17 @@ const current = new Set(diffs.filter(removesInTarget).map((d) => getItemKey(d))) const flipped = [...current].filter((k) => !removalKeys.has(k)) removalKeys = current - if (flipped.some((k) => selectedItems.includes(k))) { - selectedItems = selectedItems.filter((k) => !flipped.includes(k)) + // A row that left the list (made workspace specific, synced elsewhere) takes its + // tick with it: the deploy button counts the selection, and a key with no row + // would be reported as undeployable. + const listed = new Set(selectableDiffs.map((d) => getItemKey(d))) + const kept = selectedItems.filter((k) => listed.has(k) && !flipped.includes(k)) + if (kept.length !== selectedItems.length) { + selectedItems = kept } }) }) - // Reset override when selection or direction changes - $effect(() => { - ;[selectedItems, mergeIntoParent] - allowBehindChangesOverride = false - }) - // Trigger and schedule rows now flow through `comparison.diffs` like every // other deployable kind — the backend's `compareWorkspaces` populates them // from `workspace_diff`, with runtime fields ignored by `compare_two_*`. @@ -1461,7 +1477,7 @@ <span class="text-secondary">{test.test_script_path}</span> {#if test.job_id} <a - href="{base}/run/{test.job_id}?workspace={currentWorkspaceId}" + href="/run/{test.job_id}?workspace={currentWorkspaceId}" class="text-tertiary hover:text-secondary text-2xs" > view run @@ -1577,7 +1593,8 @@ <span class="font-medium flex flex-row gap-1 text-red-500"> <input type="checkbox" - bind:checked={allowBehindChangesOverride} + checked={allowBehindChangesOverride} + onchange={(e) => setBehindChangesOverride(e.currentTarget.checked)} class="rounded max-w-4" /> Override: Deploy despite {itemsWithBehindChanges.length} outdated item{itemsWithBehindChanges.length !== diff --git a/frontend/src/lib/components/CronBuilder.svelte b/frontend/src/lib/components/CronBuilder.svelte index bcf8508c12..81f1f4490f 100644 --- a/frontend/src/lib/components/CronBuilder.svelte +++ b/frontend/src/lib/components/CronBuilder.svelte @@ -15,7 +15,7 @@ contentClasses="p-4" > {#snippet trigger()} - <Button variant="accent" size="xs" nonCaptureEvent={true} startIcon={{ icon: Clock }}> + <Button variant="default" unifiedSize="md" nonCaptureEvent={true} startIcon={{ icon: Clock }}> Cron builder </Button> {/snippet} diff --git a/frontend/src/lib/components/CronInput.svelte b/frontend/src/lib/components/CronInput.svelte index d2b629d33e..ae06974c66 100644 --- a/frontend/src/lib/components/CronInput.svelte +++ b/frontend/src/lib/components/CronInput.svelte @@ -278,39 +278,46 @@ <div class="w-full flex flex-col gap-1"> <div class="text-emphasis font-semibold text-xs leading-none">Execute schedule every</div> - <div class="w-full flex gap-4"> - <div class="w-full flex flex-col gap-1 mb-2"> - <select {disabled} name="execute_every" id="execute_every" bind:value={executeEvery}> - <option value="second">Second(s)</option> - <option value="minute">Minute(s)</option> - <option value="hour">Hour(s)</option> - <option value="day-month">Day of the month</option> - <option value="month">Month(s)</option> - <option value="day-week">Day of the week</option> - </select> - </div> + <div class="w-full flex gap-4 items-start"> + <Select + class="flex-1 min-w-0" + disablePortal + {disabled} + id="execute_every" + bind:value={executeEvery} + items={[ + { value: 'second', label: 'Second(s)' }, + { value: 'minute', label: 'Minute(s)' }, + { value: 'hour', label: 'Hour(s)' }, + { value: 'day-month', label: 'Day of the month' }, + { value: 'month', label: 'Month(s)' }, + { value: 'day-week', label: 'Day of the week' } + ]} + /> - <div class="w-full flex flex-col gap-1 justify-center"> - {#if executeEvery == 'second'} - <input {disabled} type="number" min="0" max="59" bind:value={seconds} /> - <small class="text-secondary text-2xs">Valid range 0-59</small> - {:else if executeEvery == 'minute'} - <input {disabled} type="number" min="0" max="59" bind:value={minutes} /> - <small class="text-secondary text-2xs">Valid range 0-59</small> - {:else if executeEvery == 'hour'} - <input {disabled} type="number" min="0" max="23" bind:value={hours} /> - <small class="text-secondary text-2xs">Valid range 0-23</small> - {:else if executeEvery == 'day-month'} - <!-- <div class="w-full flex"> - <label for="lastDayOfMonth" class="w-full flex items-center gap-2"> - <div class="flex"> - <input type="checkbox" id="lastDayOfMonth" bind:checked={lastDayOfMonth} /> + {#if executeEvery == 'second' || executeEvery == 'minute' || executeEvery == 'hour'} + <div class="flex-1 min-w-0 flex flex-col gap-1"> + {#if executeEvery == 'second'} + <TextInput + inputProps={{ type: 'number', min: 0, max: 59, disabled }} + bind:value={seconds} + /> + <small class="text-secondary text-2xs">Valid range 0-59</small> + {:else if executeEvery == 'minute'} + <TextInput + inputProps={{ type: 'number', min: 0, max: 59, disabled }} + bind:value={minutes} + /> + <small class="text-secondary text-2xs">Valid range 0-59</small> + {:else} + <TextInput + inputProps={{ type: 'number', min: 0, max: 23, disabled }} + bind:value={hours} + /> + <small class="text-secondary text-2xs">Valid range 0-23</small> + {/if} </div> - <small> Last day of the month </small> - </label> - </div> --> - {/if} - </div> + {/if} </div> </div> @@ -319,6 +326,7 @@ <MultiSelect disablePortal {disabled} + class="w-full" bind:value={monthsOfYear} items={safeSelectItems(monthsOfYearOptions)} placeholder="Every month" @@ -331,6 +339,7 @@ <MultiSelect disablePortal {disabled} + class="w-full" bind:value={daysOfWeek} items={safeSelectItems(daysOfWeekOptions)} placeholder="Every day" @@ -343,28 +352,14 @@ {#if executeEvery == 'month'} <small class="text-secondary text-2xs font-normal">On day of the month</small> {/if} - <div class="w-full flex gap-4"> - <div class="w-full flex"> - <MultiSelect - disablePortal - {disabled} - bind:value={daysOfMonth} - items={safeSelectItems(daysOfMonthOptions)} - placeholder="Every day" - /> - </div> - - <!-- {#if executeEvery == 'month'} - <div class="w-full flex"> - <label for="lastDayOfMonth" class="w-full flex items-center gap-2"> - <div class="flex"> - <input type="checkbox" id="lastDayOfMonth" bind:checked={lastDayOfMonth} /> - </div> - <small> Last day of the month </small> - </label> - </div> - {/if} --> - </div> + <MultiSelect + class="w-full" + disablePortal + {disabled} + bind:value={daysOfMonth} + items={safeSelectItems(daysOfMonthOptions)} + placeholder="Every day" + /> <small class="text-secondary text-2xs font-normal" >Schedule will only execute on valid calendar days</small > @@ -374,7 +369,10 @@ {#if executeEvery == 'day-month' || executeEvery == 'month' || executeEvery == 'day-week'} <div class="w-full flex flex-col gap-1"> <small class="font-semibold text-emphasis text-xs">At time</small> - <input {disabled} type="time" name="atUTCTime" id="atUTCTime" bind:value={UTCTime} /> + <TextInput + inputProps={{ type: 'time', name: 'atUTCTime', id: 'atUTCTime', disabled }} + bind:value={UTCTime} + /> </div> {/if} @@ -390,7 +388,7 @@ <div class="mt-8"> <Button variant="accent" - size="xs" + unifiedSize="md" on:click={() => { schedule = nschedule close() diff --git a/frontend/src/lib/components/DBManager.svelte b/frontend/src/lib/components/DBManager.svelte index 837569c575..5b34c66bc5 100644 --- a/frontend/src/lib/components/DBManager.svelte +++ b/frontend/src/lib/components/DBManager.svelte @@ -45,7 +45,12 @@ import { favoriteManager } from './sidebar/FavoriteMenu.svelte' import DatatableRoleBadge from './DatatableRoleBadge.svelte' import type { AclTarget, Asset, DataTableTables } from '$lib/gen' - import { ADMIN_DATATABLE_ROLE, datatableNameTakesRole, type DatatableRowAction } from './dbTypes' + import { + ADMIN_DATATABLE_ROLE, + datatableNameTakesRole, + namedDefaultRole, + type DatatableRowAction + } from './dbTypes' import TextInput from './text_input/TextInput.svelte' import Checkbox from './common/checkbox/Checkbox.svelte' import DbSchemaDiagram from './dbdiagram/DbSchemaDiagram.svelte' @@ -417,7 +422,10 @@ if (!entry?.permissioned || !datatableNameTakesRole(datatable)) return undefined const roles = entry.usable_roles if (roles.length === 0) return { kind: 'none' } - const role = (datatable === currentDatatable ? currentRole : undefined) ?? entry.default_role + const role = + (datatable === currentDatatable ? currentRole : undefined) ?? + namedDefaultRole(entry.default_role) ?? + roles[0] if (roles.length === 1 && roles[0] === ADMIN_DATATABLE_ROLE && role === ADMIN_DATATABLE_ROLE) { return undefined } diff --git a/frontend/src/lib/components/DatatablePicker.svelte b/frontend/src/lib/components/DatatablePicker.svelte index 53617acf36..17ad6f3361 100644 --- a/frontend/src/lib/components/DatatablePicker.svelte +++ b/frontend/src/lib/components/DatatablePicker.svelte @@ -17,6 +17,9 @@ selectInputClass?: string class?: string onClear?: () => void + /** Size the input to its content, like Path's folder picker. */ + useContentEditable?: boolean + RightIcon?: any } let { @@ -27,7 +30,9 @@ placeholder = undefined, selectInputClass = '', class: className = '', - onClear = undefined + onClear = undefined, + useContentEditable = false, + RightIcon = undefined }: Props = $props() let datatables = usePromise(() => @@ -47,6 +52,8 @@ {placeholder} inputClass={selectInputClass} {onClear} + {useContentEditable} + {RightIcon} /> {#if showSchemaExplorer && value && assetCanBeExplored({ kind: 'datatable', path: value })} <ExploreAssetButton class="mt-1 w-fit" asset={{ kind: 'datatable', path: value }} /> diff --git a/frontend/src/lib/components/DatatableSchemaDiff.svelte b/frontend/src/lib/components/DatatableSchemaDiff.svelte index 1fb6918580..e3ff8633a6 100644 --- a/frontend/src/lib/components/DatatableSchemaDiff.svelte +++ b/frontend/src/lib/components/DatatableSchemaDiff.svelte @@ -202,7 +202,7 @@ // The merge migration gets the highest timestamp, so any still-pending // migration on the target is earlier: running only the merge applies it // out of order. Warn like the row-level Run action does. - const pending = pendingMigrations(status.migrations) + const pending = pendingMigrations(status.migrations, migrationSql) if (pending.length > 0) { const confirmed = await outOfOrderModal.ask({ title: 'Run migration out of order', diff --git a/frontend/src/lib/components/DefaultScriptsInner.svelte b/frontend/src/lib/components/DefaultScriptsInner.svelte index b062fb4c49..29136e42f7 100644 --- a/frontend/src/lib/components/DefaultScriptsInner.svelte +++ b/frontend/src/lib/components/DefaultScriptsInner.svelte @@ -16,11 +16,13 @@ let { small = false }: Props = $props() function computeLangs(defaultScripts: WorkspaceDefaultScripts | undefined): Script['language'][] { - const allLangs = Object.keys(defaultScriptLanguages) as Script['language'][] + const allLangs = (Object.keys(defaultScriptLanguages) as Script['language'][]).filter( + (l) => l != 'deno' + ) if (!defaultScripts || defaultScripts.order == undefined) return allLangs return defaultScripts.order ?.concat(allLangs.filter((l) => !defaultScripts.order?.includes(l))) - .filter((x) => x != 'nativets') as Script['language'][] + .filter((x) => x != 'nativets' && x != 'deno') as Script['language'][] } async function changePosition(i: number, up: boolean) { @@ -31,6 +33,10 @@ ;[norder[i], norder[i + 1]] = [norder[i + 1], norder[i]] } defaultScripts.update((s) => ({ ...s, order: norder })) + await persist() + } + + async function persist() { await WorkspaceService.editDefaultScripts({ workspace: $operatingWorkspace!, requestBody: $defaultScripts @@ -76,7 +82,7 @@ size="xs" color="red" checked={$defaultScripts?.hidden?.includes(lang)} - on:change={(e) => { + on:change={async (e) => { let toggled = e.detail if (toggled) { defaultScripts.update((s) => ({ @@ -89,6 +95,7 @@ hidden: (s?.hidden ?? []).filter((h) => h != lang) })) } + await persist() }} /> </div> diff --git a/frontend/src/lib/components/DefaultTagsInner.svelte b/frontend/src/lib/components/DefaultTagsInner.svelte index 87cfa0f89b..229c0d5e62 100644 --- a/frontend/src/lib/components/DefaultTagsInner.svelte +++ b/frontend/src/lib/components/DefaultTagsInner.svelte @@ -19,6 +19,11 @@ import Section from './Section.svelte' import ToggleButtonGroup from './common/toggleButton-v2/ToggleButtonGroup.svelte' import ToggleButton from './common/toggleButton-v2/ToggleButton.svelte' + import { + devWorkspaceTagSuffix, + loadDevWorkspaceTagSuffix, + withDevSuffix + } from '$lib/devWorkspaceTags' interface Props { defaultTagPerWorkspace?: boolean | undefined defaultTagWorkspaces?: string[] @@ -134,6 +139,7 @@ loadDefaultTags() loadWorkspaces() + loadDevWorkspaceTagSuffix() </script> <Section label="Default tags"> @@ -208,6 +214,22 @@ /> {/snippet} </ToggleButtonGroup> + {#if $devWorkspaceTagSuffix} + <span class="text-2xs text-secondary"> + Dev workspace isolation (Workers page) is on and applies after this: a fork's + <code + >{forkAppendForkSuffix ? 'python3-{parent_id}-fork' : 'python3-{parent_id}'}</code + > + runs as + <code + >{withDevSuffix( + forkAppendForkSuffix ? 'python3-{parent_id}-fork' : 'python3-{parent_id}', + $devWorkspaceTagSuffix + )}</code + >, on the worker groups serving dev workspaces. To split root and dev jobs across + worker pools, isolation alone is enough. + </span> + {/if} </div> <Toggle bind:checked={limitToWorkspaces} diff --git a/frontend/src/lib/components/DeployWorkspace.svelte b/frontend/src/lib/components/DeployWorkspace.svelte index 53ca12cf03..daf944ff37 100644 --- a/frontend/src/lib/components/DeployWorkspace.svelte +++ b/frontend/src/lib/components/DeployWorkspace.svelte @@ -5,7 +5,6 @@ aiAgentModuleDependencies, collectTransformRefs } from './deployDependencies' - import { base } from '$lib/base' import { enterpriseLicense, superadmin } from '$lib/stores' import { AppService, @@ -111,16 +110,22 @@ return needsOnBehalfOfSelection(kind, sourceOnBehalfOfInfo[statusPath]) } + /** Triggers and agents record who they run as by principal, the rest by address. */ + function usesPrincipal(kind: Kind): boolean { + return kind === 'trigger' || kind === 'resource' + } + /** * Get the on_behalf_of value for deployment based on user's choice. - * Returns an email for flows/scripts/apps, or permissioned_as (u/username, g/group) for triggers/schedules. + * Returns an email for flows/scripts/apps, or permissioned_as (u/username, g/group) for + * triggers/schedules and agents. */ function getOnBehalfOfForDeploy(statusPath: string, kind: Kind): string | undefined { const choice = onBehalfOfChoice[statusPath] if (choice === 'target') return targetOnBehalfOfInfo[statusPath] if (choice === 'custom') { const details = customOnBehalfOf[statusPath] - return kind === 'trigger' ? details?.permissionedAs : details?.email + return usesPrincipal(kind) ? details?.permissionedAs : details?.email } // 'me' or undefined = don't pass, backend will use deploying user's identity return undefined @@ -135,7 +140,7 @@ statusPath: string, kind: Kind ): string | undefined { - if (kind === 'trigger' || onBehalfOfChoice[statusPath] !== 'custom') return undefined + if (usesPrincipal(kind) || onBehalfOfChoice[statusPath] !== 'custom') return undefined return customOnBehalfOf[statusPath]?.permissionedAs } @@ -206,7 +211,7 @@ // Fetch on_behalf_of_email for flows, scripts, apps, and triggers from both workspaces for (const dep of sortedSet.filter((d) => - ['flow', 'script', 'app', 'trigger'].includes(d.kind) + ['flow', 'script', 'app', 'trigger', 'resource'].includes(d.kind) )) { const key = computeStatusPath(dep.kind, dep.path) let source: string | undefined @@ -538,7 +543,7 @@ > {:else} <Alert type="info" title="Shareable page" - >Share this <a href="{base}/deploy/{kind}/{initialPath}">link</a> to have another properly permissioned + >Share this <a href="/deploy/{kind}/{initialPath}">link</a> to have another properly permissioned user do the deployment</Alert > @@ -580,7 +585,7 @@ connection={remoteStatus?.connection} returnTo={kind === 'trigger' ? undefined - : `${base}/deploy/${kind}/${initialPath}?workspace=${encodeURIComponent($operatingWorkspace!)}`} + : `/deploy/${kind}/${initialPath}?workspace=${encodeURIComponent($operatingWorkspace!)}`} onChange={loadDestinations} /> </div> diff --git a/frontend/src/lib/components/DevWorkspaceIsolation.svelte b/frontend/src/lib/components/DevWorkspaceIsolation.svelte new file mode 100644 index 0000000000..61bc56fb69 --- /dev/null +++ b/frontend/src/lib/components/DevWorkspaceIsolation.svelte @@ -0,0 +1,613 @@ +<script lang="ts"> + import { Alert, Button, Section } from './common' + import ConfirmationModal from './common/confirmationModal/ConfirmationModal.svelte' + import Toggle from './Toggle.svelte' + import TextInput from './text_input/TextInput.svelte' + import Select from './select/Select.svelte' + import Tooltip from './meltComponents/Tooltip.svelte' + import { ArrowRight, ChevronDown, ChevronRight, Save, Settings } from 'lucide-svelte' + import { + SettingService, + WorkerService, + WorkspaceService, + type GetQueueStatusResponse, + type Workspace + } from '$lib/gen' + import { + DEV_WORKSPACE_ISOLATION_SETTING, + DEV_WORKSPACE_ISOLATION_SKIP_NON_DEV_FORKS_SETTING, + DEV_WORKSPACE_TAG_SUFFIX_SETTING + } from '$lib/consts' + import { + DEFAULT_DEV_WORKSPACE_TAG_SUFFIX, + DEV_WORKSPACE_TAG_SUFFIX_PATTERN, + devWorkspaceIsolation, + devWorkspaceListenSuffix, + devWorkspaceSkipNonDevForks, + devWorkspaceTagSuffix, + isDevOrForkWorkspace, + isIsolatedWorkspace, + loadDevWorkspaceTagSuffix, + withDevSuffix + } from '$lib/devWorkspaceTags' + import { enterpriseLicense } from '$lib/stores' + import { sendUserToast } from '$lib/toast' + import { pluralize } from '$lib/utils' + import { onMount } from 'svelte' + + interface Props { + /** Worker group configs, by group name. */ + workerGroups: Record<string, any> | undefined + /** Workers of each group that pinged in the last 15 seconds. */ + liveWorkers: Record<string, number> + canEdit: boolean + onConfigureGroup: (name: string) => void + } + + let { workerGroups, liveWorkers, canEdit, onConfigureGroup }: Props = $props() + + let suffix = $derived($devWorkspaceTagSuffix) + let enabled = $derived(suffix != null) + let effectiveSuffix = $derived($devWorkspaceListenSuffix) + + // Overridden while a confirmation is pending, reset to the saved state otherwise. + let toggleChecked = $derived(enabled) + let suffixDraft = $derived(effectiveSuffix) + let suffixError = $derived( + DEV_WORKSPACE_TAG_SUFFIX_PATTERN.test(suffixDraft.trim()) + ? undefined + : "Use 1 to 32 letters, digits, '-', '_' or '.'" + ) + + let skipNonDevForks = $derived($devWorkspaceSkipNonDevForks) + // Overridden while saving, reset to the saved state otherwise. + let skipChecked = $derived(skipNonDevForks) + let workspaces = $state<Workspace[] | undefined>(undefined) + let devWorkspaces = $derived( + (workspaces ?? []).filter( + (w) => !w.deleted && isIsolatedWorkspace(w, workspaces ?? [], skipNonDevForks) + ) + ) + // Workspaces whose new forks skip isolation while non-dev forks are not isolated: the roots and + // their non-dev forks. A forking rule does not cascade to forks, so each needs its own. + let forkSources = $derived( + (workspaces ?? []).filter((w) => !w.deleted && !isIsolatedWorkspace(w, workspaces ?? [], true)) + ) + let nonDevForkCount = $derived( + (workspaces ?? []).filter( + (w) => + !w.deleted && isDevOrForkWorkspace(w) && !isIsolatedWorkspace(w, workspaces ?? [], true) + ).length + ) + // Roots anyone may fork: no rule withholds forking, or their rules could not be read, which + // must not hide the warning. `undefined` until checked. + let forkableRoots = $state<string[] | undefined>(undefined) + let forkableRootsRun = 0 + async function loadForkableRoots(roots: string[]) { + const run = ++forkableRootsRun + const unprotected: string[] = [] + for (let i = 0; i < roots.length; i += 8) { + const batch = await Promise.all( + roots.slice(i, i + 8).map(async (id) => { + try { + const rules = await WorkspaceService.listProtectionRules({ workspace: id }) + return !rules.some((r) => r.rules.includes('DisableWorkspaceForking')) + } catch { + return true + } + }) + ) + if (run !== forkableRootsRun) return + unprotected.push(...roots.slice(i, i + 8).filter((_, j) => batch[j])) + } + forkableRoots = unprotected + } + $effect(() => { + if (skipNonDevForks && workspaces !== undefined) { + loadForkableRoots(forkSources.map((w) => w.id)) + } + }) + let workspaceNames = $derived(Object.fromEntries((workspaces ?? []).map((w) => [w.id, w.name]))) + + async function loadWorkspaces() { + const all: Workspace[] = [] + for (let page = 1; ; page++) { + const batch = await WorkspaceService.listWorkspacesAsSuperAdmin({ page, perPage: 100 }) + all.push(...batch) + if (batch.length < 100) break + } + workspaces = all + } + + let queueStatus = $state<GetQueueStatusResponse | undefined>(undefined) + async function loadQueueStatus() { + try { + queueStatus = await WorkerService.getQueueStatus() + } catch { + queueStatus = undefined + } + } + + onMount(() => { + loadDevWorkspaceTagSuffix(true) + loadWorkspaces().catch((e) => console.error('Could not list workspaces', e)) + loadQueueStatus() + const interval = setInterval(loadQueueStatus, 15_000) + return () => clearInterval(interval) + }) + + type GroupEntry = { name: string; live: number; tags: string[] } + + function isDedicated(config: any): boolean { + return config?.dedicated_worker != undefined || (config?.dedicated_workers?.length ?? 0) > 0 + } + + let flaggedGroups: GroupEntry[] = $derived( + Object.entries(workerGroups ?? {}) + .filter(([_, c]) => c?.serves_dev_workspaces === true && !isDedicated(c)) + .map(([name, c]) => ({ name, live: liveWorkers[name] ?? 0, tags: c?.worker_tags ?? [] })) + ) + let liveFlaggedWorkers = $derived(flaggedGroups.reduce((acc, g) => acc + g.live, 0)) + let unflaggedGroupNames = $derived( + Object.entries(workerGroups ?? {}) + .filter(([_, c]) => c?.serves_dev_workspaces !== true && !isDedicated(c)) + .map(([name]) => name) + ) + // The only way to break isolation: an unflagged group listing a suffixed tag takes dev jobs. + let leakingGroups = $derived( + Object.entries(workerGroups ?? {}) + .filter(([_, c]) => c?.serves_dev_workspaces !== true) + .map(([name, c]) => ({ + name, + tags: ((c?.worker_tags ?? []) as string[]).filter((t) => t.endsWith(effectiveSuffix)) + })) + .filter((g) => g.tags.length > 0) + ) + let unservedDevTags = $derived( + enabled + ? (queueStatus ?? []).filter( + (s) => s.tag.endsWith(effectiveSuffix) && s.waiting > 0 && s.workers === 0 + ) + : [] + ) + + let groupToFlag = $state<string | undefined>(undefined) + let collapsed = $state(true) + let showWorkspaces = $state(false) + let showAdvanced = $state(false) + + let confirmEnable = $state(false) + let confirmDisable = $state(false) + let saving = $state(false) + + async function setIsolation(on: boolean) { + saving = true + try { + await SettingService.setGlobal({ + key: DEV_WORKSPACE_ISOLATION_SETTING, + requestBody: { value: on } + }) + devWorkspaceIsolation.update((i) => ({ + suffix: i?.suffix ?? effectiveSuffix, + skip_non_dev_forks: i?.skip_non_dev_forks ?? false, + enabled: on + })) + sendUserToast( + on + ? `Dev workspace and fork jobs now run on tags suffixed with ${effectiveSuffix}` + : 'Dev workspace isolation turned off' + ) + } catch (e) { + sendUserToast(`Could not save dev workspace isolation: ${e}`, true) + toggleChecked = enabled + } finally { + saving = false + } + } + + async function saveSuffix(value: string) { + saving = true + try { + await SettingService.setGlobal({ + key: DEV_WORKSPACE_TAG_SUFFIX_SETTING, + requestBody: { value } + }) + devWorkspaceIsolation.update((i) => ({ + enabled: i?.enabled ?? false, + skip_non_dev_forks: i?.skip_non_dev_forks ?? false, + suffix: value + })) + sendUserToast(`Dev workspace tag suffix set to ${value}`) + } catch (e) { + sendUserToast(`Could not save the dev workspace tag suffix: ${e}`, true) + } finally { + saving = false + } + } + + async function setSkipNonDevForks(skip: boolean) { + saving = true + try { + await SettingService.setGlobal({ + key: DEV_WORKSPACE_ISOLATION_SKIP_NON_DEV_FORKS_SETTING, + requestBody: { value: skip } + }) + devWorkspaceIsolation.update((i) => ({ + enabled: i?.enabled ?? false, + suffix: i?.suffix ?? effectiveSuffix, + skip_non_dev_forks: skip + })) + sendUserToast( + skip + ? 'Forks of non-dev workspaces now run on the workers of the workspace they fork' + : 'Forks of non-dev workspaces now run on dev workers' + ) + } catch (e) { + sendUserToast(`Could not save dev workspace isolation: ${e}`, true) + skipChecked = skipNonDevForks + } finally { + saving = false + } + } + + function onToggle(checked: boolean) { + if (checked === enabled) return + collapsed = false + if (checked) { + if (liveFlaggedWorkers === 0) { + confirmEnable = true + } else { + setIsolation(true) + } + } else { + confirmDisable = true + } + } + + function workspaceKind(w: Workspace): string { + if (w.parent_workspace_id) { + const parent = workspaceNames[w.parent_workspace_id] ?? w.parent_workspace_id + return w.is_dev_workspace ? `dev workspace of ${parent}` : `fork of ${parent}` + } + return 'fork whose parent was deleted' + } +</script> + +<ConfirmationModal + open={confirmEnable} + title="Turn on dev workspace isolation" + confirmationText="Turn on" + type="info" + onCanceled={() => { + confirmEnable = false + toggleChecked = enabled + }} + onConfirmed={async () => { + confirmEnable = false + await setIsolation(true) + }} +> + <div class="flex flex-col gap-2 text-sm"> + <p> + {#if workspaces === undefined} + Every dev workspace and fork + {:else} + <b>{pluralize(devWorkspaces.length, 'dev workspace or fork', 'dev workspaces and forks')}</b + > + {/if} + will have their jobs queued until a worker group serves them. + </p> + <p class="text-secondary text-xs"> + {#if flaggedGroups.length === 0} + No worker group is flagged as serving dev workspaces yet. + {:else} + The worker groups serving dev workspaces ({flaggedGroups.map((g) => g.name).join(', ')}) + have no live worker. + {/if} + Jobs never fall back to the other worker groups: they wait in the queue and run as soon as a serving + worker is up. + </p> + {#if unflaggedGroupNames.length > 0 && flaggedGroups.length === 0} + <div> + <Button + variant="default" + unifiedSize="sm" + startIcon={{ icon: Settings }} + onClick={() => { + confirmEnable = false + toggleChecked = enabled + onConfigureGroup(unflaggedGroupNames[0]) + }} + > + Flag a worker group first + </Button> + </div> + {/if} + </div> +</ConfirmationModal> + +<ConfirmationModal + open={confirmDisable} + title="Turn off dev workspace isolation" + confirmationText="Turn off" + type="danger" + onCanceled={() => { + confirmDisable = false + toggleChecked = enabled + }} + onConfirmed={async () => { + confirmDisable = false + await setIsolation(false) + }} +> + <p class="text-sm"> + New jobs of dev workspaces and forks will run on the same worker groups as root workspaces + again. Jobs already queued on a <code>{effectiveSuffix}</code> tag keep it, and the worker groups + serving dev workspaces still run them. + </p> +</ConfirmationModal> + +{#snippet isolationToggle()} + <Toggle + bind:checked={toggleChecked} + on:change={(e) => onToggle(e.detail)} + disabled={!canEdit || !$enterpriseLicense || saving || suffix === undefined} + options={{ right: 'Run dev workspaces and forks on separate workers' }} + size="xs" + /> +{/snippet} + +<Section + label="Dev workspace isolation" + tooltip="Dev workspaces and forks run code that has not been reviewed or deployed to a root workspace. Route their jobs to worker groups of their own, so they never run on the workers of your root workspaces." + eeOnly={!$enterpriseLicense} + collapsable + bind:collapsed + wrapperClass="mt-4 mb-6 rounded-md border border-light p-4 bg-surface-tertiary" +> + {#snippet action()} + {@render isolationToggle()} + {/snippet} + {#snippet badge()} + {@render isolationToggle()} + {/snippet} + + <div class="flex flex-col gap-4"> + <div class="grid grid-cols-[auto_auto_1fr] gap-x-3 gap-y-2 items-center text-xs max-w-2xl"> + <span class="font-semibold text-emphasis">Root workspaces</span> + <ArrowRight size={14} class="text-secondary" /> + <span class="text-primary"> + Worker groups not serving dev workspaces, on their usual tags: + <code>python3</code>, <code>gpu</code> + </span> + <span class="font-semibold text-emphasis">Dev workspaces and forks</span> + <ArrowRight size={14} class="text-secondary" /> + <span class="text-primary"> + {#if enabled} + Worker groups serving dev workspaces, on tags suffixed with + <code>{effectiveSuffix}</code>: + {:else} + Once on, worker groups serving dev workspaces, on suffixed tags: + {/if} + <code>{withDevSuffix('python3', effectiveSuffix)}</code>, + <code>{withDevSuffix('gpu', effectiveSuffix)}</code> + </span> + </div> + <p class="text-2xs text-secondary max-w-2xl"> + A workspace with a parent, and every fork (including a fork whose parent was deleted), counts + as a dev workspace, unless forks of non-dev workspaces are left out below. Every job is + covered: runs, previews, schedules, triggers, flow steps, AI agent tools and dependency jobs, + and inline runs are refused on workers not serving dev workspaces. A job whose tag no serving + worker listens to stays queued: it never falls back to the other worker groups. Dedicated + workers keep their own tags. + </p> + + <div class="flex flex-col gap-1 max-w-2xl"> + <Toggle + bind:checked={skipChecked} + on:change={(e) => setSkipNonDevForks(e.detail)} + disabled={!canEdit || !$enterpriseLicense || saving || suffix === undefined} + options={{ right: "Don't isolate forks of non-dev workspaces" }} + size="xs" + /> + <span class="text-2xs text-secondary"> + A fork with no dev workspace above it, like a fork of a production workspace or a fork of + that fork, runs on the same workers as that production workspace. Dev workspaces and their + forks stay isolated. Restrict who can create such forks with the <b + >Disable workspace forking</b + > + protection rule of each such workspace and fork. + {#if skipNonDevForks && workspaces !== undefined} + {pluralize(nonDevForkCount, 'fork')} currently {nonDevForkCount === 1 ? 'runs' : 'run'} + outside isolation. + {/if} + </span> + {#if skipNonDevForks && forkableRoots && forkableRoots.length > 0} + <Alert type="warning" size="xs" title="Workspaces anyone can fork onto their workers"> + Anyone who can fork + {#each forkableRoots.slice(0, 5) as id, i (id)} + {i > 0 ? ', ' : ''}<b>{workspaceNames[id] ?? id}</b> + {/each}{forkableRoots.length > 5 ? ` and ${forkableRoots.length - 5} more` : ''} + can run jobs on {forkableRoots.length === 1 ? 'its' : 'their'} workers. Add a + <b>Disable workspace forking</b> protection rule to {forkableRoots.length === 1 + ? 'it' + : 'them'}, bypassed by the people allowed to fork, or isolate these forks again. + </Alert> + {/if} + </div> + + <!-- Worker groups serving dev workspaces --> + <div class="flex flex-col gap-2"> + <span class="text-xs font-semibold text-emphasis">Worker groups serving dev workspaces</span> + {#if flaggedGroups.length > 0} + <div class="flex flex-wrap gap-2"> + {#each flaggedGroups as g (g.name)} + <Button + variant="default" + unifiedSize="sm" + startIcon={{ icon: Settings }} + onClick={() => onConfigureGroup(g.name)} + > + {g.name} + <span class={g.live > 0 ? 'text-secondary' : 'text-red-500'}> + · {pluralize(g.live, 'live worker')} + </span> + </Button> + {/each} + </div> + {:else} + <span class="text-xs text-secondary">None yet.</span> + {/if} + {#if canEdit && unflaggedGroupNames.length > 0} + <div class="flex gap-2 items-center"> + <Select + size="sm" + class="w-56" + placeholder="Pick a worker group" + items={unflaggedGroupNames.map((n) => ({ value: n }))} + bind:value={groupToFlag} + /> + <Button + variant="default" + unifiedSize="sm" + disabled={!groupToFlag} + onClick={() => groupToFlag && onConfigureGroup(groupToFlag)} + > + Flag as serving dev workspaces + </Button> + <Tooltip> + {#snippet text()} + Opens the group's config, where "Serves dev workspaces and forks" sits under its tags. + A dedicated group to start from: create a new group config, flag it, and start workers + with its name as <code>WORKER_GROUP</code>. + {/snippet} + </Tooltip> + </div> + {/if} + </div> + + {#if enabled && liveFlaggedWorkers === 0} + <Alert type="warning" size="xs" title="No worker serves dev workspaces"> + Jobs of dev workspaces and forks stay queued until a worker group flagged as serving dev + workspaces has live workers{flaggedGroups.length === 0 + ? ': flag a worker group as serving dev workspaces' + : ''}. + </Alert> + {/if} + + {#if unservedDevTags.length > 0} + <Alert type="warning" size="xs" title="Dev jobs waiting with no worker"> + No live worker listens to + {#each unservedDevTags as s, i (s.tag)} + {i > 0 ? ', ' : ''}<code>{s.tag}</code> ({s.waiting} waiting) + {/each}. These tags carry the <code>{effectiveSuffix}</code> suffix of dev workspace jobs: add + the unsuffixed tag to a worker group flagged as serving dev workspaces, or flag a group that + already lists it. + </Alert> + {/if} + + {#if leakingGroups.length > 0} + <Alert + type="warning" + size="xs" + title="A worker group not serving dev workspaces takes dev jobs" + > + {#each leakingGroups as g, i (g.name)} + {i > 0 ? '; ' : ''}<b>{g.name}</b> lists + {#each g.tags as t, j (t)}{j > 0 ? ', ' : ''}<code>{t}</code>{/each} + {/each}. Jobs of dev workspaces and forks run on these tags, so this group runs them next to + root workspace jobs. Remove the tags, or flag the group as serving dev workspaces. + </Alert> + {/if} + + <!-- Affected workspaces --> + <div class="flex flex-col gap-1"> + <div class="w-fit"> + <Button + variant="subtle" + unifiedSize="sm" + startIcon={{ icon: showWorkspaces ? ChevronDown : ChevronRight }} + onClick={() => (showWorkspaces = !showWorkspaces)} + > + {#if workspaces === undefined} + Workspaces routed to dev workers + {:else} + {pluralize(devWorkspaces.length, 'workspace')} + {enabled ? 'routed' : 'that would be routed'} to dev workers + {/if} + </Button> + </div> + {#if showWorkspaces} + {#if workspaces === undefined} + <span class="text-xs text-secondary">Loading…</span> + {:else if devWorkspaces.length === 0} + <span class="text-xs text-secondary" + >No dev workspace or fork yet. Only root workspaces exist.</span + > + {:else} + <ul class="flex flex-col gap-1 text-xs max-h-60 overflow-auto"> + {#each devWorkspaces as w (w.id)} + <li class="flex gap-2"> + <span class="font-mono text-primary">{w.id}</span> + <span class="text-secondary">{workspaceKind(w)}</span> + </li> + {/each} + </ul> + {/if} + {/if} + </div> + + <!-- Advanced --> + <div class="flex flex-col gap-2"> + <div class="w-fit"> + <Button + variant="subtle" + unifiedSize="sm" + startIcon={{ icon: showAdvanced ? ChevronDown : ChevronRight }} + onClick={() => (showAdvanced = !showAdvanced)} + > + Advanced + </Button> + </div> + {#if showAdvanced} + <div class="flex flex-col gap-1 max-w-md"> + <span class="text-xs font-semibold text-emphasis">Tag suffix</span> + <span class="text-2xs text-secondary"> + Appended last, after every other tag setting: with workspace-specific default tags a + fork's <code>python3-$workspace-fork</code> becomes + <code>{withDevSuffix('python3-$workspace-fork', effectiveSuffix)}</code>. Changing it + moves the worker groups serving dev workspaces to the new suffix right away, while jobs + already queued keep the old one: change it when no dev job is waiting. A dev job whose + tag would exceed 50 characters once suffixed is refused. + </span> + <div class="flex gap-2 items-start"> + <TextInput + bind:value={suffixDraft} + size="sm" + error={suffixError} + inputProps={{ + placeholder: DEFAULT_DEV_WORKSPACE_TAG_SUFFIX, + disabled: !canEdit || !$enterpriseLicense + }} + /> + <Button + variant="accent" + unifiedSize="sm" + startIcon={{ icon: Save }} + disabled={!canEdit || + !!suffixError || + suffixDraft.trim() === effectiveSuffix || + saving} + onClick={() => saveSuffix(suffixDraft.trim())} + > + Save + </Button> + </div> + {#if suffixError} + <span class="text-2xs text-red-500">{suffixError}</span> + {/if} + </div> + {/if} + </div> + </div> +</Section> diff --git a/frontend/src/lib/components/DevWorkspaceSetting.svelte b/frontend/src/lib/components/DevWorkspaceSetting.svelte index ff9932fa87..9f8f536bd7 100644 --- a/frontend/src/lib/components/DevWorkspaceSetting.svelte +++ b/frontend/src/lib/components/DevWorkspaceSetting.svelte @@ -8,7 +8,6 @@ import { sendUserToast } from '$lib/toast' import { switchWorkspace } from '$lib/storeUtils' import { goto } from '$app/navigation' - import { base } from '$lib/base' import { findCanonicalDevWorkspace, findWorkspaceAncestors, @@ -29,7 +28,14 @@ isRuleUnconditionallyActiveInRulesets, DEV_WORKSPACE_LOCK_RULE_NAME } from '$lib/workspaceProtectionRules.svelte' - import { GitFork, ExternalLink, Check, Minus, Pen } from 'lucide-svelte' + import { GitFork, ExternalLink, Check, Minus, Pen, Server } from 'lucide-svelte' + import { + devWorkspaceTagSuffix, + devWorkspaceSkipNonDevForks, + isIsolatedWorkspaceId, + loadDevWorkspaceTagSuffix, + withDevSuffix + } from '$lib/devWorkspaceTags' import { resource } from 'runed' import type { Snippet } from 'svelte' @@ -41,6 +47,7 @@ deployTarget }: { deployTarget?: Snippet } = $props() + loadDevWorkspaceTagSuffix() let currentWs = $derived($userWorkspaces.find((w) => w.id === $workspaceStore)) let isDev = $derived(currentWs?.is_dev_workspace ?? false) let currentLabel = $derived(devLabelKey(currentWs?.dev_workspace_label)) @@ -239,7 +246,7 @@ // scratch rather than from the current query so no stale `?workspace=<dev>` survives a switch. function rulesetsHref(name?: string): string { const rule = name ? `&rule=${encodeURIComponent(name)}` : '' - return `${base}/workspace_settings?tab=rulesets${rule}` + return `/workspace_settings?tab=rulesets${rule}` } function openRulesets(name?: string) { @@ -456,6 +463,15 @@ Pair this workspace with a dev workspace: the same code with a different environment (resource and variable values). Edits are made in the dev workspace and promoted here. </p> + <p class="text-2xs text-secondary"> + Attaching an existing workspace copies nothing: it keeps its own resources and variables. + Creating a new dev workspace copies this workspace's resources and variables, credentials + included; point them at staging before developers use it. + {#if $devWorkspaceTagSuffix} + Either way, its jobs then run on dev workers (tags suffixed with + <code>{$devWorkspaceTagSuffix}</code>). + {/if} + </p> <div class="flex flex-col gap-1"> <span class="text-xs font-semibold text-emphasis">Attach an existing workspace as dev</span> <Select @@ -531,7 +547,7 @@ <Button variant="default" startIcon={{ icon: GitFork }} - onclick={() => goto(`${base}/user/fork_workspace?dev=true`)} + onclick={() => goto('/user/fork_workspace?dev=true')} > Create a new dev workspace </Button> @@ -540,11 +556,26 @@ {/if} {/snippet} +{#snippet devWorkersNotice()} + {#if $devWorkspaceTagSuffix && isIsolatedWorkspaceId($workspaceStore, $userWorkspaces, $devWorkspaceSkipNonDevForks)} + <p class="text-2xs text-secondary max-w-2xl flex items-center gap-1.5"> + <Server size={12} /> + <span> + Jobs in this workspace run on dev workers (tags suffixed with + <code>{$devWorkspaceTagSuffix}</code>, e.g. + <code>{withDevSuffix('python3', $devWorkspaceTagSuffix)}</code>), set by the instance's dev + workspace isolation. + </span> + </p> + {/if} +{/snippet} + {#if isThrowawayFork} <p class="text-sm text-secondary max-w-2xl"> Dev workspace pairing is not available on a throwaway fork. This workspace is a fork of <b>{parentId}</b>. </p> + <div class="mt-2">{@render devWorkersNotice()}</div> {@render deployTarget?.()} {:else if isDev && parentId} <div class="flex flex-col gap-3 max-w-2xl"> @@ -564,6 +595,7 @@ <span class="font-mono">{currentLabel}</span> branch. </span> </div> + {@render devWorkersNotice()} </div> {@render deployTarget?.()} <div class="flex flex-col gap-3 max-w-2xl mt-6"> diff --git a/frontend/src/lib/components/DisplayResult.svelte b/frontend/src/lib/components/DisplayResult.svelte index a49f09bb02..afadcb5741 100644 --- a/frontend/src/lib/components/DisplayResult.svelte +++ b/frontend/src/lib/components/DisplayResult.svelte @@ -7,7 +7,6 @@ import { parseDbtRun } from '$lib/components/dbt/parseDbtRun' import { copyToClipboard, parseS3Object, roughSizeOfObject } from '$lib/utils' import ExpandableImage from '$lib/components/common/image/ExpandableImage.svelte' - import { base } from '$lib/base' import { downloadViaClient, shouldDownloadViaClient } from '$lib/utils/downloadFile' import { appendViewToken } from '$lib/viewToken' import { Badge, Button, Drawer, DrawerContent } from './common' @@ -254,7 +253,7 @@ ) let resultDownloadHref = $derived( resultApiPath - ? `${base}/api${resultApiPath}` + ? `/api${resultApiPath}` : `data:text/json;charset=utf-8,${encodeURIComponent(toJsonStr(result))}` ) let resultDownloadName = $derived(`${filename ?? 'result'}.json`) @@ -856,7 +855,6 @@ {workspaceId} {jobId} {nodeId} - {base} {result} {disableTooltips} on:open-drawer={() => openDrawer()} diff --git a/frontend/src/lib/components/DisplayResultControlBar.svelte b/frontend/src/lib/components/DisplayResultControlBar.svelte index 45011d2db1..6af502a1b8 100644 --- a/frontend/src/lib/components/DisplayResultControlBar.svelte +++ b/frontend/src/lib/components/DisplayResultControlBar.svelte @@ -14,7 +14,6 @@ workspaceId?: string | undefined jobId?: string | undefined nodeId?: string | undefined - base: string result: any disableTooltips?: boolean } @@ -25,7 +24,6 @@ workspaceId = undefined, jobId = undefined, nodeId = undefined, - base, result, disableTooltips = false }: Props = $props() @@ -67,7 +65,7 @@ download={downloadName} class="text-current" href={resultApiPath - ? `${base}/api${resultApiPath}` + ? `/api${resultApiPath}` : `data:text/json;charset=utf-8,${encodeURIComponent(toJsonStr(result))}`} > <Download size={14} /> diff --git a/frontend/src/lib/components/DrillPicker.svelte b/frontend/src/lib/components/DrillPicker.svelte index 99f2c3a9b1..a92ef11ddf 100644 --- a/frontend/src/lib/components/DrillPicker.svelte +++ b/frontend/src/lib/components/DrillPicker.svelte @@ -204,6 +204,9 @@ leaves and ignores the current scope. ) ) + /** Whether any row in this list has a second line, which sets every row's height. */ + const entriesTwoLine = $derived(entryList.some((e) => e.type === 'leaf' && !!e.node.secondary)) + // Browse rows annotated with the section header rendered above them. A // header is emitted when a leaf's section differs from the previous LEAF's // section — comparing against the previous entry of any type would insert a @@ -502,7 +505,12 @@ leaves and ignores the current scope. {/if} {/snippet} -{#snippet leafRow(leaf: DrillLeaf<L>, secondary: string | undefined, baseClass: string)} +{#snippet leafRow( + leaf: DrillLeaf<L>, + secondary: string | undefined, + baseClass: string, + twoLineHeight: boolean +)} {@const key = leaf.key} {@const isHl = key === highlightedKey} {@const isCur = !!leaf.current} @@ -541,9 +549,12 @@ leaves and ignores the current scope. onclick={(e) => pick(leaf, e.metaKey || e.ctrlKey)} > {@render defaultLeafIcon(leaf)} - <!-- Centred in the row's full height so a one-line leaf sits where a two-line - one's pair does, rather than riding high against the top. --> - <div class="min-w-0 flex-1 flex flex-col justify-center min-h-[2.25rem]"> + <!-- Centred in a two-line row's height so a one-line leaf sits where a two-line + one's pair does, rather than riding high against the top. A list with no + second line anywhere (a picker's pages) keeps its rows one line tall. --> + <div + class="min-w-0 flex-1 flex flex-col justify-center {twoLineHeight ? 'min-h-[2.25rem]' : ''}" + > {#if leaf.secondary} <div class="text-xs text-primary font-normal truncate">{leaf.label}</div> <div class="text-2xs text-hint font-normal font-mono truncate"> @@ -657,6 +668,7 @@ leaves and ignores the current scope. <div role="status" class="px-3 py-2 text-xs text-tertiary">No matches</div> {:else} {#each searchResultsByGroup as { key, label, items } (key)} + {@const twoLineHeight = items.some((r) => !!r.leaf.secondary)} {#if label} <div class="px-3 pt-3 pb-1 mt-2 first:mt-0 text-3xs uppercase tracking-wide text-hint font-medium" @@ -666,7 +678,9 @@ leaves and ignores the current scope. {/if} <ul class="pb-1"> {#each items as r (r.leaf.key)} - <li>{@render leafRow(r.leaf, r.leaf.secondary ?? r.leaf.label, 'py-1.5')}</li> + <li> + {@render leafRow(r.leaf, r.leaf.secondary ?? r.leaf.label, 'py-1.5', twoLineHeight)} + </li> {/each} </ul> {/each} @@ -692,7 +706,8 @@ leaves and ignores the current scope. {@render leafRow( entry.node, leafSecondary?.(entry.node, scope) ?? entry.node.secondary, - 'py-1.5' + 'py-1.5', + entriesTwoLine )} {:else} <button diff --git a/frontend/src/lib/components/DucklakePicker.svelte b/frontend/src/lib/components/DucklakePicker.svelte index 3a6f2bf739..d6ed4d0cdf 100644 --- a/frontend/src/lib/components/DucklakePicker.svelte +++ b/frontend/src/lib/components/DucklakePicker.svelte @@ -17,6 +17,9 @@ selectInputClass?: string class?: string onClear?: () => void + /** Size the input to its content, like Path's folder picker. */ + useContentEditable?: boolean + RightIcon?: any } let { @@ -27,7 +30,9 @@ placeholder = undefined, selectInputClass = '', class: className = '', - onClear = undefined + onClear = undefined, + useContentEditable = false, + RightIcon = undefined }: Props = $props() let ducklakes = usePromise(() => @@ -45,6 +50,8 @@ {placeholder} inputClass={selectInputClass} {onClear} + {useContentEditable} + {RightIcon} /> {#if showSchemaExplorer && value && assetCanBeExplored({ kind: 'ducklake', path: value })} <ExploreAssetButton class="mt-1 w-fit" asset={{ kind: 'ducklake', path: value }} /> diff --git a/frontend/src/lib/components/Editor.svelte b/frontend/src/lib/components/Editor.svelte index f9df8adcef..03bf5ce87e 100644 --- a/frontend/src/lib/components/Editor.svelte +++ b/frontend/src/lib/components/Editor.svelte @@ -1523,6 +1523,9 @@ } catch (e) { console.log('error initializing services', e) } + // Unmounted while the services loaded: the container is detached, and + // creating the editor on it throws. + if (destroyed || !divEl?.isConnected) return // vscode.languages.registerDefinitionProvider('*', { // provideDefinition(document, position, token) { diff --git a/frontend/src/lib/components/EditorBar.svelte b/frontend/src/lib/components/EditorBar.svelte index 81ef6c1c96..429c99c4a6 100644 --- a/frontend/src/lib/components/EditorBar.svelte +++ b/frontend/src/lib/components/EditorBar.svelte @@ -22,7 +22,6 @@ <script lang="ts"> import { ResourceService, VariableService, WorkspaceService, type Script } from '$lib/gen' - import { base } from '$lib/base' import type Editor from './Editor.svelte' import ItemPicker from './ItemPicker.svelte' import VariableEditor from './VariableEditor.svelte' @@ -105,6 +104,7 @@ | 'powershell' | 'bunnative' | 'claudesandbox' + | 'pisandbox' | 'wac_python' | 'wac_typescript' | 'ci_test_bun' @@ -844,7 +844,7 @@ JsonNode ${windmillPathToCamelCaseName(path)} = JsonNode.Parse(await client.GetS startIcon={{ icon: Plus }} target="_blank" variant="accent" - href="{base}/resources?connect_app=undefined" + href="/resources?connect_app=undefined" > Add resource </Button> @@ -903,7 +903,7 @@ JsonNode ${windmillPathToCamelCaseName(path)} = JsonNode.Parse(await client.GetS startIcon={{ icon: Settings }} target="_blank" variant="accent" - href="{base}/workspace_settings?tab=ducklake" + href="/workspace_settings?tab=ducklake" > Go to settings </Button> @@ -946,7 +946,7 @@ JsonNode ${windmillPathToCamelCaseName(path)} = JsonNode.Parse(await client.GetS startIcon={{ icon: Settings }} target="_blank" variant="accent" - href="{base}/workspace_settings?tab=windmill_data_tables" + href="/workspace_settings?tab=windmill_data_tables" > Go to settings </Button> diff --git a/frontend/src/lib/components/ErrorOrRecoveryHandler.svelte b/frontend/src/lib/components/ErrorOrRecoveryHandler.svelte index 0adb5dc690..6d95ad0c82 100644 --- a/frontend/src/lib/components/ErrorOrRecoveryHandler.svelte +++ b/frontend/src/lib/components/ErrorOrRecoveryHandler.svelte @@ -1,6 +1,4 @@ <script lang="ts" module> - import type { ErrorHandler } from '$lib/gen/types.gen' - export const errorHandlerArgs = [ 'path', 'workspace_id', @@ -19,17 +17,6 @@ ] export const slackErrorHandlerHubPathEnding = '/workspace-or-schedule-error-handler-slack' - - /** The stored `<script|flow>/<path>` form of a handler. `kind` is the Custom tab's Script/Flow - * choice and survives switching to a built-in tab, whose handlers are all scripts: stored as - * `flow/...` they never run. */ - export function handlerFullPath( - selected: ErrorHandler, - kind: 'flow' | 'script', - path: string - ): string { - return `${selected === 'custom' ? kind : 'script'}/${path}` - } </script> <script lang="ts"> @@ -43,7 +30,6 @@ import ChannelSelector from '$lib/components/ChannelSelector.svelte' import type { Schema, SupportedLanguage } from '$lib/common' - import { base } from '$lib/base' import { enterpriseLicense } from '$lib/stores' import MsTeamsIcon from '$lib/components/icons/MSTeamsIcon.svelte' import { classNames, emptySchema, emptyString, sendUserToast, tryEvery } from '$lib/utils' @@ -68,32 +54,22 @@ RotateCw, XCircle } from 'lucide-svelte' - import { hubPaths } from '$lib/hub' import { isCloudHosted } from '$lib/cloud' import SmtpConfigurationStatus from './common/smtp/SmtpConfigurationStatus.svelte' import { SettingService } from '$lib/gen' - import { isSmtpSettingsValid } from './instanceSettings/SmtpSettings.svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + import { builtinHubPath, type HandlerDraft, type HandlerMode } from './handlerDraft.svelte' const operatingWorkspace = useOperatingWorkspace() - const slackRecoveryHandler = hubPaths.slackRecoveryHandler - const slackHandlerScriptPath = hubPaths.slackErrorHandler - const slackSuccessHandler = hubPaths.slackSuccessHandler - const teamsRecoveryHandler = hubPaths.teamsRecoveryHandler - const teamsHandlerScriptPath = hubPaths.teamsErrorHandler - const teamsSuccessHandler = hubPaths.teamsSuccessHandler - interface Props { - errorOrRecovery: 'error' | 'recovery' | 'success' + errorOrRecovery: HandlerMode isEditable: boolean toggleText?: string showScriptHelpText?: boolean - handlerSelected: ErrorHandler - handlerPath: string | undefined - handlerExtraArgs: Record<string, any> + /** Owned by the caller, which restores it on Discard; every tab edits its own slot. */ + draft: HandlerDraft customScriptTemplate: string - customHandlerKind?: 'flow' | 'script' customTabTooltip?: import('svelte').Snippet noMargin?: boolean /** Workspace for handler lookup / settings / test jobs. Defaults to the operating @@ -109,11 +85,8 @@ isEditable, toggleText = 'Enable', showScriptHelpText = false, - handlerSelected = $bindable('custom'), - handlerPath = $bindable(), - handlerExtraArgs = $bindable(), + draft = $bindable(), customScriptTemplate, - customHandlerKind = $bindable('script'), customTabTooltip, noMargin = false, workspace = undefined, @@ -141,8 +114,6 @@ let connectionTestJob: { uuid: string; is_success: boolean; in_progress: boolean } | undefined = $state() - const EMAIL_RECIPIENTS_KEY = 'email_recipients' - const CHANNEL_KEY = 'channel' async function loadSlackResources() { const settings = await WorkspaceService.getPublicSettings({ workspace: effectiveWorkspace! }) @@ -170,11 +141,7 @@ async function loadSmtpConfiguration() { try { - const smtpSettings = (await SettingService.getGlobal({ key: 'smtp_settings' })) as Record< - string, - any - > | null - hasSmtpConfig = smtpSettings ? isSmtpSettingsValid(smtpSettings) : false + hasSmtpConfig = await SettingService.getSmtpConfigured() } catch (error) { hasSmtpConfig = false } @@ -189,7 +156,7 @@ let submitted_job = await testJobFunction({ workspace: effectiveWorkspace!, requestBody: { - hub_script_path: handlerPath, + hub_script_path: draft[platform].path, channel: channel, test_msg: `This is a notification to test the connection between ${platform} and Windmill workspace '${effectiveWorkspace!}'` } @@ -235,7 +202,11 @@ await sendMessage(channel, 'teams') } - async function loadHandlerScriptArgs(p: string, defaultArgs: string[] = []) { + async function loadHandlerScriptArgs( + p: string, + kind: 'script' | 'flow', + defaultArgs: string[] = [] + ) { try { let schema: Schema | undefined = emptySchema() if (p.startsWith('hub/')) { @@ -250,7 +221,7 @@ } } else { let scriptOrFlow: Script | Flow = - customHandlerKind === 'script' + kind === 'script' ? await ScriptService.getScriptByPath({ workspace: effectiveWorkspace!, path: p }) : await FlowService.getFlowByPath({ workspace: effectiveWorkspace!, path: p }) schema = scriptOrFlow.schema as Schema @@ -268,47 +239,6 @@ } } - function isSlackHandler(scriptPath: string | undefined) { - if (!scriptPath) { - return false - } - if (errorOrRecovery == 'error') { - return scriptPath.startsWith('hub/') && scriptPath.endsWith(slackErrorHandlerHubPathEnding) - } else if (errorOrRecovery == 'recovery') { - return ( - scriptPath.startsWith('hub/') && scriptPath.endsWith('/schedule-recovery-handler-slack') - ) - } else { - return scriptPath.startsWith('hub/') && scriptPath.endsWith('/schedule-success-handler-slack') - } - } - - function isTeamsHandler(scriptPath: string | undefined) { - if (!scriptPath) { - return false - } - if (errorOrRecovery == 'error') { - return ( - scriptPath.startsWith('hub/') && - scriptPath.endsWith('/workspace-or-schedule-error-handler-teams') - ) - } else if (errorOrRecovery == 'recovery') { - return ( - scriptPath.startsWith('hub/') && scriptPath.endsWith('/schedule-recovery-handler-teams') - ) - } else { - return scriptPath.startsWith('hub/') && scriptPath.endsWith('/schedule-success-handler-teams') - } - } - - function isEmailHandler(scriptPath: string | undefined) { - if (!scriptPath) { - return false - } - - return scriptPath.startsWith('hub/') && scriptPath.endsWith('/workspace-or-error-handler-email') - } - $effect(() => { if (effectiveWorkspace) { loadSlackResources() @@ -318,80 +248,24 @@ }) $effect(() => { - if (handlerSelected === 'slack' && isSlackHandler(handlerPath)) { - handlerExtraArgs['slack'] = '$res:f/slack_bot/bot_token' - } else { - handlerExtraArgs['slack'] = undefined - } - }) - - let lastHandlerSelected: ErrorHandler | undefined = $state(undefined) - let handlerCache = $state({ - slack: undefined as string | undefined, - teams: undefined as string | undefined, - email: undefined as string[] | undefined - }) - let handlerPathCache: Partial<Record<ErrorHandler, string | undefined>> = $state({}) - $effect(() => { - if (lastHandlerSelected !== handlerSelected && lastHandlerSelected !== undefined) { - if (lastHandlerSelected != 'custom') { - const key = lastHandlerSelected === 'email' ? EMAIL_RECIPIENTS_KEY : CHANNEL_KEY - handlerCache[lastHandlerSelected] = handlerExtraArgs[key] - } - handlerPathCache[lastHandlerSelected] = handlerPath - - if (handlerSelected === 'custom') { - delete handlerExtraArgs[CHANNEL_KEY] - delete handlerExtraArgs[EMAIL_RECIPIENTS_KEY] - handlerPath = handlerPathCache['custom'] - } else if (handlerSelected === 'email') { - handlerExtraArgs[EMAIL_RECIPIENTS_KEY] = handlerCache[handlerSelected] ?? [] - delete handlerExtraArgs[CHANNEL_KEY] - } else { - handlerExtraArgs[CHANNEL_KEY] = handlerCache[handlerSelected] ?? '' - delete handlerExtraArgs[EMAIL_RECIPIENTS_KEY] - handlerPath = handlerPathCache[handlerSelected] - } - } - - lastHandlerSelected = handlerSelected - }) - - $effect(() => { - handlerPath && - !isSlackHandler(handlerPath) && - !isTeamsHandler(handlerPath) && - !isEmailHandler(handlerPath) && - loadHandlerScriptArgs(handlerPath, errorHandlerArgs).then( + const { path, kind } = draft.custom + path && + loadHandlerScriptArgs(path, kind, errorHandlerArgs).then( (schema) => (customHandlerSchema = schema) ) }) $effect(() => { - handlerPath && - isSlackHandler(handlerPath) && - loadHandlerScriptArgs(handlerPath, [...errorHandlerArgs, 'slack']).then( + const path = draft.slack.path + path && + loadHandlerScriptArgs(path, 'script', [...errorHandlerArgs, 'slack']).then( (schema) => (slackHandlerSchema = schema) ) }) - - $effect(() => { - if (handlerSelected === 'email') { - handlerPath = hubPaths.emailErrorHandler - } - }) - - // The instance channels are reached by having no workspace handler at all, so the tab - // owns an empty path rather than a handler script. - $effect(() => { - if (handlerSelected === 'instance_alerts') { - handlerPath = undefined - } - }) </script> <div class={classNames('space-y-2', noMargin ? '' : 'mt-2')}> - <ToggleButtonGroup bind:selected={handlerSelected} disabled={!isEditable}> + <ToggleButtonGroup bind:selected={draft.selected} disabled={!isEditable}> {#snippet children({ item })} <ToggleButton label="Slack" value="slack" {item} disabled={!isEditable} /> <ToggleButton label="Teams" value="teams" {item} disabled={!isEditable} /> @@ -416,21 +290,21 @@ </ToggleButtonGroup> <div class="flex flex-col gap-6 p-4 rounded-md shadow-sm bg-surface-tertiary"> - {#if handlerSelected === 'custom'} + {#if draft.selected === 'custom'} <div class="flex flex-col gap-1"> <div class="flex flex-row"> <ScriptPicker disabled={!isEditable || !$enterpriseLicense} kinds={['script', 'failure']} allowFlow={true} - bind:scriptPath={handlerPath} - bind:itemKind={customHandlerKind} + bind:scriptPath={draft.custom.path} + bind:itemKind={draft.custom.kind} allowRefresh={isEditable} workspace={effectiveWorkspace} clearable /> - {#if !handlerPath} + {#if !draft.custom.path} <Button btnClasses="ml-4 whitespace-nowrap" variant="default" @@ -454,7 +328,7 @@ </div> {/if} </div> - {#if handlerPath} + {#if draft.custom.path} <div> <p class="font-semibold text-xs mb-1">Extra arguments</p> {#await import('$lib/components/SchemaForm.svelte')} @@ -463,7 +337,7 @@ <Module.default disabled={!isEditable} schema={customHandlerSchema} - bind:args={handlerExtraArgs} + bind:args={draft.custom.args} shouldHideNoInputs className="text-xs" /> @@ -473,7 +347,7 @@ {/if} </div> {/if} - {:else if handlerSelected === 'slack'} + {:else if draft.selected === 'slack'} <!-- Slack Connection Status --> <SlackConnectionStatus isConnected={workspaceConnectedToSlack} @@ -485,23 +359,15 @@ {#if workspaceConnectedToSlack} <Toggle disabled={!$enterpriseLicense || !isEditable} - checked={isSlackHandler(handlerPath)} + checked={!!draft.slack.path} options={{ right: toggleText }} - on:change={async (e) => { - if (e.detail && errorOrRecovery === 'error') { - handlerPath = slackHandlerScriptPath - } else if (e.detail && errorOrRecovery === 'recovery') { - handlerPath = slackRecoveryHandler - } else if (e.detail && errorOrRecovery === 'success') { - handlerPath = slackSuccessHandler - } else { - handlerPath = undefined - } + on:change={(e) => { + draft.slack.path = e.detail ? builtinHubPath(errorOrRecovery, 'slack') : undefined }} /> {/if} - {#if workspaceConnectedToSlack && isSlackHandler(handlerPath)} + {#if workspaceConnectedToSlack && draft.slack.path} <div class="flex flex-col gap-2"> {#await import('$lib/components/SchemaForm.svelte')} <Loader2 class="animate-spin" /> @@ -513,18 +379,18 @@ schemaFieldTooltip={{ channel: 'Slack channel name without the "#" - example: "windmill-alerts"' }} - bind:args={handlerExtraArgs} + bind:args={draft.slack.args} shouldHideNoInputs className="text-xs" /> {/await} - {#if $enterpriseLicense && isSlackHandler(handlerPath)} + {#if $enterpriseLicense} <Button - disabled={emptyString(handlerExtraArgs['channel'])} + disabled={emptyString(draft.slack.args['channel'])} wrapperClasses="w-fit" variant="default" - on:click={() => sendSlackMessage(handlerExtraArgs['channel'])} + on:click={() => sendSlackMessage(draft.slack.args['channel'])} unifiedSize="md">Send test message</Button > {#if connectionTestJob !== undefined} @@ -543,7 +409,7 @@ <a target="_blank" - href={`${base}/run/${connectionTestJob.uuid}?workspace=${effectiveWorkspace}`} + href={`/run/${connectionTestJob.uuid}?workspace=${effectiveWorkspace}`} class="inline-flex items-center gap-1" > {connectionTestJob.uuid} @@ -557,7 +423,7 @@ {:else if workspaceConnectedToSlack == undefined} <Loader2 class="animate-spin" size={10} /> {/if} - {:else if handlerSelected === 'teams'} + {:else if draft.selected === 'teams'} <!-- Teams Connection Status --> <TeamsConnectionStatus isConnected={workspaceConnectedToTeams} @@ -569,18 +435,10 @@ {#if workspaceConnectedToTeams} <Toggle disabled={!$enterpriseLicense || !isEditable} - checked={isTeamsHandler(handlerPath)} + checked={!!draft.teams.path} options={{ right: toggleText }} - on:change={async (e) => { - if (e.detail && errorOrRecovery === 'error') { - handlerPath = teamsHandlerScriptPath - } else if (e.detail && errorOrRecovery === 'recovery') { - handlerPath = teamsRecoveryHandler - } else if (e.detail && errorOrRecovery === 'success') { - handlerPath = teamsSuccessHandler - } else { - handlerPath = undefined - } + on:change={(e) => { + draft.teams.path = e.detail ? builtinHubPath(errorOrRecovery, 'teams') : undefined }} /> {/if} @@ -602,26 +460,26 @@ placeholder="Search Teams channels" workspace={effectiveWorkspace} teamId={teams_team_guid} - selectedChannel={handlerExtraArgs['channel'] + selectedChannel={draft.teams.args['channel'] ? { - channel_id: handlerExtraArgs['channel'], - channel_name: handlerExtraArgs['channel_name'] + channel_id: draft.teams.args['channel'], + channel_name: draft.teams.args['channel_name'] } : undefined} onSelectedChannelChange={(channel) => { - handlerExtraArgs['channel'] = channel?.channel_id - handlerExtraArgs['channel_name'] = channel?.channel_name + draft.teams.args['channel'] = channel?.channel_id + draft.teams.args['channel_name'] = channel?.channel_name }} onError={(e) => sendUserToast('Failed to load channels: ' + e.message, true)} /> </div> </div> - {#if $enterpriseLicense && isTeamsHandler(handlerPath) && workspaceConnectedToTeams} + {#if $enterpriseLicense && draft.teams.path && workspaceConnectedToTeams} <Button - disabled={emptyString(handlerExtraArgs['channel'])} + disabled={emptyString(draft.teams.args['channel'])} btnClasses="w-32 text-center whitespace-nowrap" variant="default" - on:click={() => sendTeamsMessage(handlerExtraArgs['channel'] ?? '')} + on:click={() => sendTeamsMessage(draft.teams.args['channel'] ?? '')} size="xs">Send test message</Button > {#if connectionTestJob !== undefined} @@ -636,7 +494,7 @@ Message sent via Windmill job <a target="_blank" - href={`${base}/run/${connectionTestJob.uuid}?workspace=${effectiveWorkspace}`} + href={`/run/${connectionTestJob.uuid}?workspace=${effectiveWorkspace}`} > {connectionTestJob.uuid} </a> @@ -647,7 +505,7 @@ {:else if workspaceConnectedToTeams == undefined} <Loader2 class="animate-spin" size={10} /> {/if} - {:else if handlerSelected === 'email'} + {:else if draft.selected === 'email'} {#if isCloudHosted()} <Alert type="info" title="Email notifications are not available in Cloud"> Email notifications for trigger failures are only available in self-hosted Windmill @@ -660,8 +518,8 @@ <MultiSelect items={[] as { label: string; value: string }[]} bind:value={ - () => handlerExtraArgs[EMAIL_RECIPIENTS_KEY] ?? [], - (recipients) => (handlerExtraArgs[EMAIL_RECIPIENTS_KEY] = recipients) + () => draft.email.args.email_recipients ?? [], + (recipients) => (draft.email.args.email_recipients = recipients) } placeholder="Enter email addresses..." onCreateItem={(email) => { @@ -670,23 +528,24 @@ sendUserToast('Invalid email format', true) return } - const currentArray = handlerExtraArgs[EMAIL_RECIPIENTS_KEY] ?? [] - handlerExtraArgs[EMAIL_RECIPIENTS_KEY] = [...currentArray, email] + draft.email.args.email_recipients = [ + ...(draft.email.args.email_recipients ?? []), + email + ] }} class="w-full" /> - {#if handlerExtraArgs[EMAIL_RECIPIENTS_KEY]?.length > 0} + {#if draft.email.args.email_recipients?.length > 0} <span class="text-xs text-secondary"> - {handlerExtraArgs[EMAIL_RECIPIENTS_KEY]?.length} email{handlerExtraArgs[ - EMAIL_RECIPIENTS_KEY - ]?.length === 1 + {draft.email.args.email_recipients.length} email{draft.email.args.email_recipients + .length === 1 ? '' : 's'} configured </span> {/if} </div> {/if} - {:else if handlerSelected === 'instance_alerts'} + {:else if draft.selected === 'instance_alerts'} <div class="flex flex-col gap-2"> <span class="text-xs text-secondary"> Failed jobs are reported to the Slack, Teams and email channels configured at the instance @@ -694,7 +553,7 @@ report is sent without adding an entry to the instance critical alert feed. Canceled jobs are not reported. </span> - <a class="text-xs w-fit" href="{base}/?workspace=admins#superadmin-settings"> + <a class="text-xs w-fit" href="/?workspace=admins#superadmin-settings"> Configure the instance critical alert channels </a> </div> diff --git a/frontend/src/lib/components/FlowBuilder.svelte b/frontend/src/lib/components/FlowBuilder.svelte index 57cd8b2953..73ce91083d 100644 --- a/frontend/src/lib/components/FlowBuilder.svelte +++ b/frontend/src/lib/components/FlowBuilder.svelte @@ -18,7 +18,13 @@ linkedAgentToolsVersion, migrateLinkedAgentToolsScope } from '$lib/components/flows/linkedAgentToolsStore.svelte' - import { enterpriseLicense, userStore, userWorkspaces, usedTriggerKinds } from '$lib/stores' + import { + enterpriseLicense, + userStore, + userWorkspaces, + usedTriggerKinds, + workspaceStore + } from '$lib/stores' import { generateRandomString, orderedJsonStringify, @@ -40,7 +46,7 @@ import { getContext, onDestroy, setContext, untrack, type Snippet } from 'svelte' import PageHeaderContent from '$lib/components/PageHeaderContent.svelte' import PathEditPopover from '$lib/components/PathEditPopover.svelte' - import { pageHeader, PHONE_BAR } from '$lib/components/pageHeaderRegistry.svelte' + import { pageHeader } from '$lib/components/pageHeaderRegistry.svelte' import { writable } from 'svelte/store' import CenteredPage from './CenteredPage.svelte' import { Button } from './common' @@ -49,6 +55,7 @@ import WorkspaceScriptSettingsDrawer from './flows/content/WorkspaceScriptSettingsDrawer.svelte' import FlowEditorDrawer from './flows/content/FlowEditorDrawer.svelte' import { dfs as dfsApply } from './flows/dfs' + import { dropStaleStepLocks } from './flows/staleStepLocks' import { claimLinkedToolsFetch, invalidateLinkedToolsFetches, @@ -110,13 +117,14 @@ import { UserDraft } from '$lib/userDraft.svelte' import { setOpenInSessionHandoff } from './sessions/openInSessionContext' import { getEditorStoragePath, setEditorStoragePath } from './editorStoragePathContext' - import { useOperatorBuilderFlows, useTriggerLock } from '$lib/operatorWriteRights' + import { useEditRights, useOperatorBuilderFlows, useTriggerLock } from '$lib/operatorWriteRights' import { useOperatingUser, useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' const triggerLock = useTriggerLock() const operatorBuilderFlows = useOperatorBuilderFlows() + const editRights = useEditRights() const operatingWorkspace = useOperatingWorkspace() const operatingUser = useOperatingUser() @@ -229,19 +237,14 @@ let pathSnapshot = $state<string | undefined>(undefined) let topbarWidth = $state(0) - // In the page header the buttons share the row with the breadcrumb, so they collapse sooner: - // the trail and the summary take ~560px before either truncates, and the full group — the - // dropdown, Diff, the preview trio and Deploy — is ~610px. - const compactBelow = $derived(ownsPageHeader ? 1200 : 720) - const compactTopbar = $derived.by(() => { - const w = ownsPageHeader ? pageHeader.barWidth : topbarWidth - return w > 0 && w < compactBelow - }) - // A phone's bar holds the trail and Deploy: the diff joins the menu and the preview buttons - // stand down, since there is no room to run a flow beside its own name. - const phoneTopbar = $derived( - ownsPageHeader && pageHeader.barWidth > 0 && pageHeader.barWidth < PHONE_BAR + // In the page header the bar folds the buttons (`actionFolds` below), once its breadcrumb has + // given all it can; anywhere else this editor's own top bar is theirs alone. + const compactTopbar = $derived( + ownsPageHeader ? pageHeader.actionFold >= 1 : topbarWidth > 0 && topbarWidth < 720 ) + // The second fold holds the trail and Deploy: the diff joins the menu and the preview buttons + // stand down, since there is no room to run a flow beside its own name. + const phoneTopbar = $derived(ownsPageHeader && pageHeader.actionFold >= 2) const diffEnabled = $derived(customUi?.topBar?.diff != false) // Nothing to compare against until a deployed version exists. @@ -555,9 +558,14 @@ // One lookup for the whole list: an agent lives in a folder, and the groups and admin // flag that answer for it are per workspace, so the nav user would answer for the wrong // membership when a session editor operates on another workspace. - const user = await getUserExt(opWorkspace ?? '').catch(() => undefined) + const user = + (await getUserExt(opWorkspace ?? '')) ?? + (opWorkspace === $workspaceStore ? $userStore : undefined) + const operatorSettings = $userWorkspaces.find( + (w) => w.id === opWorkspace + )?.operator_settings agentCanWrite = Object.fromEntries( - draftAgents.map((a) => [a.path, agentDraftCanWrite(a, user ?? $userStore ?? undefined)]) + draftAgents.map((a) => [a.path, agentDraftCanWrite(a, user, operatorSettings)]) ) // The path is passed, so a draft that renames the agent is refused here too: a rename is // the agent editor's to deploy, and this dialog lists the agent under the path the flow @@ -625,6 +633,16 @@ } } + // The editor clears a step's lock when its code is edited, but a draft written elsewhere + // can hold a step whose code changed and whose lock did not. A failed lookup skips the + // check rather than blocking the deploy. + const liveFlowValue = isNewFlow + ? undefined + : await FlowService.getFlowByPath({ workspace: opWorkspace!, path: initialPath }) + .then((f) => f.value) + .catch(() => undefined) + dropStaleStepLocks(flow.value, liveFlowValue) + if (isNewFlow) { await FlowService.createFlow({ workspace: opWorkspace!, @@ -1560,7 +1578,7 @@ <AIChangesWarningModal bind:open={aiChangesWarningOpen} onConfirm={aiChangesConfirmCallback} /> {#key renderCount} - {#if !actingUser?.operator || $operatorBuilderFlows} + {#if editRights.roleCanAuthor('flow')} {#if $pathStore} <FlowHistory bind:this={flowHistory} path={$pathStore} {onHistoryRestore} /> {/if} @@ -1581,16 +1599,17 @@ // Frozen while the rename popover is open so the trail holds still as the user types. kind: 'flow', path: pathSnapshot ?? $pathStore, + summary: flowStore.val.summary, summaryContent: flowSummary, // Gated like the summary's own editor: a host that allows neither field keeps the // band's segment, which copies the path. pathTrigger: - customUi?.topBar?.editablePath != false || - customUi?.topBar?.editableSummary != false + customUi?.topBar?.editablePath != false || customUi?.topBar?.editableSummary != false ? flowPathTrigger : undefined }} actions={flowHeaderActions} + actionFolds={2} contexts={headerContexts} separator="none" /> diff --git a/frontend/src/lib/components/FlowLogViewer.svelte b/frontend/src/lib/components/FlowLogViewer.svelte index 6a8db18a76..0efbdc332e 100644 --- a/frontend/src/lib/components/FlowLogViewer.svelte +++ b/frontend/src/lib/components/FlowLogViewer.svelte @@ -10,7 +10,6 @@ ExternalLink, Keyboard } from 'lucide-svelte' - import { base } from '$lib/base' import ObjectViewer from './propertyPicker/ObjectViewer.svelte' import LogViewer from './LogViewer.svelte' import FlowLogViewer from './FlowLogViewer.svelte' @@ -98,7 +97,7 @@ function getJobLink(jobId: string | undefined): string { if (!jobId) return '' - return `${base}/run/${jobId}?workspace=${workspaceId ?? $operatingWorkspace}` + return `/run/${jobId}?workspace=${workspaceId ?? $operatingWorkspace}` } function getStatusColor(status: FlowStatusModule['type'] | undefined): string { diff --git a/frontend/src/lib/components/FlowLoopIterationPreview.svelte b/frontend/src/lib/components/FlowLoopIterationPreview.svelte index f136cbfe39..8da0ee390e 100644 --- a/frontend/src/lib/components/FlowLoopIterationPreview.svelte +++ b/frontend/src/lib/components/FlowLoopIterationPreview.svelte @@ -10,9 +10,14 @@ import FlowProgressBar from './flows/FlowProgressBar.svelte' import { CornerDownLeft, Play, RefreshCw, X } from 'lucide-svelte' import type { Schema } from '$lib/common' - import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + import { + useOperatingUser, + useOperatingWorkspace + } from '$lib/components/operatingWorkspace.svelte' + import { previewOnBehalfOf } from '$lib/utils/previewOnBehalfOf' const operatingWorkspace = useOperatingWorkspace() + const operatingUser = useOperatingUser() interface Props { open: boolean @@ -112,7 +117,12 @@ restartedFrom, undefined, undefined, - opWorkspace?.() + opWorkspace?.(), + previewOnBehalfOf( + operatingUser.current, + flowStore.val.on_behalf_of, + flowStore.val.on_behalf_of_email + ) ) } catch (err: any) { // `runFlowPreview` resolves a linked agent's draft first and refuses when it cannot be read. diff --git a/frontend/src/lib/components/FlowMetadata.svelte b/frontend/src/lib/components/FlowMetadata.svelte index 022fa874a2..b28e694bc3 100644 --- a/frontend/src/lib/components/FlowMetadata.svelte +++ b/frontend/src/lib/components/FlowMetadata.svelte @@ -1,6 +1,5 @@ <script lang="ts"> import { type Job } from '$lib/gen' - import { base } from '$lib/base' import JobStatus from '$lib/components/JobStatus.svelte' import { flowPathToHref } from '$lib/scripts' import { displayDate, truncateRev } from '$lib/utils' @@ -58,7 +57,7 @@ <BarsStaggered size={SMALL_ICON_SIZE} class="min-w-3.5" /> <span class="whitespace-nowrap"> Step of flow - <a href={`${base}/run/${job.parent_job}?workspace=${$workspaceStore}`}> + <a href={`/run/${job.parent_job}?workspace=${$workspaceStore}`}> {truncateRev(job.parent_job, 18)} </a> </span> @@ -68,7 +67,7 @@ <Bot size={SMALL_ICON_SIZE} class="min-w-3.5" /> <span class="whitespace-nowrap"> Triggered by parent - <a href={`${base}/run/${job.parent_job}?workspace=${$workspaceStore}`}> + <a href={`/run/${job.parent_job}?workspace=${$workspaceStore}`}> {job.parent_job}</a > </span> @@ -96,7 +95,7 @@ {@const stem = `${job?.job_kind}s`} {@const isScript = job?.job_kind === 'script'} {@const viewHref = isScript - ? `${base}/${stem}/get/${job?.script_hash}` + ? `/${stem}/get/${job?.script_hash}` : flowPathToHref(job?.script_path ?? '')} <div class="flex flex-row gap-2 items-center"> {#if isScript} @@ -128,6 +127,6 @@ </div> <div class="text-secondary text-2xs pt-2 whitespace-nowrap"> run id: - <a href={`${base}/run/${job.id}?workspace=${job.workspace_id}`}> {job.id} </a> + <a href={`/run/${job.id}?workspace=${job.workspace_id}`}> {job.id} </a> </div> </div> diff --git a/frontend/src/lib/components/FlowPreviewContent.svelte b/frontend/src/lib/components/FlowPreviewContent.svelte index 151d35be77..e2de124c1d 100644 --- a/frontend/src/lib/components/FlowPreviewContent.svelte +++ b/frontend/src/lib/components/FlowPreviewContent.svelte @@ -48,6 +48,7 @@ useOperatingUser, useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + import { previewOnBehalfOf } from '$lib/utils/previewOnBehalfOf' const operatingWorkspace = useOperatingWorkspace() const operatingUser = useOperatingUser() @@ -211,7 +212,12 @@ restartedFrom, conversationId, devTempScriptRefs?.(), - opWorkspace?.() + opWorkspace?.(), + previewOnBehalfOf( + operatingUser.current, + flowStore.val.on_behalf_of, + flowStore.val.on_behalf_of_email + ) ) jobId = newJobId isRunning = true diff --git a/frontend/src/lib/components/FlowStatusViewerInner.svelte b/frontend/src/lib/components/FlowStatusViewerInner.svelte index 1d56c20b38..489d6c4769 100644 --- a/frontend/src/lib/components/FlowStatusViewerInner.svelte +++ b/frontend/src/lib/components/FlowStatusViewerInner.svelte @@ -15,7 +15,6 @@ type FlowNote, type FlowValue } from '$lib/gen' - import { base } from '$lib/base' import FlowJobResult from './FlowJobResult.svelte' import WorkflowTimeline from './WorkflowTimeline.svelte' import DisplayResult from './DisplayResult.svelte' @@ -69,6 +68,7 @@ retainLinkedToolsScope } from './flows/linkedAgentToolsStore.svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + import { AGENT_STEP_ID, agentStepLabel } from './flows/conversations/agentEditorChat' const operatingWorkspace = useOperatingWorkspace() @@ -1238,6 +1238,8 @@ id: string type: FlowModuleValue['type'] suspend?: boolean + /** Shown in place of the id. */ + label?: string } function allModulesForTimeline( @@ -1250,7 +1252,8 @@ ({ id: x.id, type: x.value.type, - suspend: x.suspend != undefined + suspend: x.suspend != undefined, + label: x.id === AGENT_STEP_ID ? agentStepLabel(job?.script_path) : undefined }) as FlowModuleForTimeline, { skipToolNodes: true @@ -1933,7 +1936,7 @@ </Button> {:else} <Button - href="{base}/api{logsApiPath}" + href="/api{logsApiPath}" download={logsName} color="light" size="xs" @@ -2195,7 +2198,7 @@ class="text-right text-xs" rel="noreferrer" target="_blank" - href="{base}/run/{node.job_id ?? + href="/run/{node.job_id ?? ''}?workspace={job?.workspace_id}" > {truncateRev(node.job_id ?? '', 10)} diff --git a/frontend/src/lib/components/FlowTimeline.svelte b/frontend/src/lib/components/FlowTimeline.svelte index 4ed13c1df1..640c8728ce 100644 --- a/frontend/src/lib/components/FlowTimeline.svelte +++ b/frontend/src/lib/components/FlowTimeline.svelte @@ -179,12 +179,12 @@ /> </div> {/if} - {#each flowModules as { id: k, type: typ, suspend: isSuspend } (k)} + {#each flowModules as { id: k, type: typ, suspend: isSuspend, label } (k)} {@const subItems = items?.[k]?.filter((x) => x.created_at && x.started_at)} <div class="relative px-3 py-1.5"> <div class="flex items-center justify-between mb-0.5"> <div class="text-xs font-medium" - >{k.startsWith('subflow:') ? k.substring(8) : k} + >{label ?? (k.startsWith('subflow:') ? k.substring(8) : k)} {#if localModuleStates[k]?.selectedForloop && (typ == 'forloopflow' || typ == 'whileloopflow')} <span class="text-xs font-mono font-medium inline-flex items-center -my-2"> <button onclick={(e) => e.stopPropagation()}> diff --git a/frontend/src/lib/components/GitRepoViewer.svelte b/frontend/src/lib/components/GitRepoViewer.svelte index 53ddea2a96..d00449f168 100644 --- a/frontend/src/lib/components/GitRepoViewer.svelte +++ b/frontend/src/lib/components/GitRepoViewer.svelte @@ -3,7 +3,6 @@ import { untrack } from 'svelte' import { Alert, Button } from './common' import S3FilePickerInner from './S3FilePickerInner.svelte' - import { base } from '$lib/base' import { Loader, Loader2, ChevronDown, ChevronRight, ExternalLink } from 'lucide-svelte' import { hubPaths } from '$lib/hub' import { sleep } from '$lib/utils' @@ -237,7 +236,7 @@ {#if runningJobId} <a class="inline-flex items-center gap-1 mt-2 text-sm underline" - href={`${base}/run/${runningJobId}?workspace=${ws}`} + href={`/run/${runningJobId}?workspace=${ws}`} target="_blank" rel="noreferrer noopener" > @@ -272,7 +271,7 @@ {#if runningJobId} <a class="inline-flex items-center gap-1 text-xs underline text-secondary" - href={`${base}/run/${runningJobId}?workspace=${ws}`} + href={`/run/${runningJobId}?workspace=${ws}`} target="_blank" rel="noreferrer noopener" > diff --git a/frontend/src/lib/components/GroupEditor.svelte b/frontend/src/lib/components/GroupEditor.svelte index f8d0445840..2c256207e1 100644 --- a/frontend/src/lib/components/GroupEditor.svelte +++ b/frontend/src/lib/components/GroupEditor.svelte @@ -15,7 +15,7 @@ import Row from './table/Row.svelte' import Cell from './table/Cell.svelte' import { sendUserToast } from '$lib/toast' - import { canWrite } from '$lib/utils' + import { useEditRights } from '$lib/operatorWriteRights' import ToggleButtonGroup from './common/toggleButton-v2/ToggleButtonGroup.svelte' import ToggleButton from './common/toggleButton-v2/ToggleButton.svelte' import Label from './Label.svelte' @@ -42,6 +42,7 @@ const operatingWorkspace = useOperatingWorkspace() const operatingUser = useOperatingUser() const actingUser = $derived(operatingUser.current) + const editRights = useEditRights() const ROLE_TOOLTIPS = { member: @@ -92,7 +93,7 @@ // Derived for the same reason as the trigger editors: the acting user's role can land after // the group does, and a snapshot taken first would stay read-only. const can_write = $derived( - writeVerdict ?? (groupPerms !== undefined && canWrite(name, groupPerms, actingUser)) + writeVerdict ?? (groupPerms !== undefined && editRights.canEditItem('group', name, groupPerms)) ) let group: Group | undefined let instance_group: InstanceGroup | undefined = $state() @@ -329,10 +330,10 @@ } catch (e) { sendUserToast(e.body ?? String(e), true) // A failed create is not proof the group is absent: `create_group` commits before a - // git-sync step that can still fail the request, including with a 4xx. Only the name - // conflict says it was never written. Report rather than resolve — a group found by + // git-sync step that can still fail the request, including with a 4xx. Only a name + // conflict or reservation proves absence. Report rather than resolve — a group found by // name may be someone else's, and adopting it would send this draft's writes there. - const nameTaken = String(e?.body ?? '').includes('already exists') + const nameTaken = /already exists|is reserved/.test(String(e?.body ?? '')) if (created && !alreadyCreated && !nameTaken) { sendUserToast(`Group ${name} may have been created anyway — reopen it to check`, true) } diff --git a/frontend/src/lib/components/HeaviestScriptsDrawer.svelte b/frontend/src/lib/components/HeaviestScriptsDrawer.svelte new file mode 100644 index 0000000000..a4591924c9 --- /dev/null +++ b/frontend/src/lib/components/HeaviestScriptsDrawer.svelte @@ -0,0 +1,201 @@ +<script lang="ts"> + import { WorkerService } from '$lib/gen' + import { resource } from 'runed' + import { Alert, Drawer, DrawerContent, Section, Skeleton } from './common' + import TextInput from './text_input/TextInput.svelte' + import ToggleButtonGroup from './common/toggleButton-v2/ToggleButtonGroup.svelte' + import ToggleButton from './common/toggleButton-v2/ToggleButton.svelte' + import Select from './select/Select.svelte' + import DataTable from './table/DataTable.svelte' + import Head from './table/Head.svelte' + import Cell from './table/Cell.svelte' + import { formatMemory, msToReadableTime } from '$lib/utils' + import { logFeatureUsage } from '$lib/utils/featureUsage' + + interface Props { + workerGroups: string[] + } + + let { workerGroups }: Props = $props() + + const WINDOWS = { + '24h': 24 * 3600, + '7d': 7 * 24 * 3600, + '30d': 30 * 24 * 3600 + } + const ORDERS = { + total_duration: 'Total runtime', + max_memory: 'Max memory', + cpu: 'CPU time' + } as const + type OrderBy = keyof typeof ORDERS + // The server gathers every run without a stable path (previews, dependency jobs) under this one. + const ADHOC_PATH = '<adhoc>' + + let drawer: Drawer | undefined = $state() + let opened = $state(false) + let windowKey: keyof typeof WINDOWS = $state('24h') + let orderBy: OrderBy = $state('total_duration') + let workerGroup: string | undefined = $state() + let workspace = $state('') + + export function openDrawer(group?: string) { + workerGroup = group + opened = true + drawer?.openDrawer() + logFeatureUsage('worker_resource_stats', 'opened') + } + + const stats = resource( + () => ({ opened, windowKey, orderBy, workerGroup, workspace: workspace.trim() }), + async (q, _, { signal }) => { + if (!q.opened) return undefined + try { + return await WorkerService.getRunnableStats({ + windowSecs: WINDOWS[q.windowKey], + orderBy: q.orderBy, + workerGroup: q.workerGroup || undefined, + workspace: q.workspace || undefined + }) + } finally { + // A slower answer for filters no longer selected must not replace the current one: + // `resource` drops the abort error thrown in its place. + signal.throwIfAborted() + } + }, + { debounce: 200 } + ) + + // Many scripts run for well under a second, which `msToReadableTime` rounds to "0.0s". + function duration(ms: number) { + return ms < 1000 ? `${Math.round(ms)}ms` : msToReadableTime(ms, 1) + } + + function cores(cpuMs: number, durationMs: number) { + return durationMs > 0 ? (cpuMs / durationMs).toFixed(2) : '-' + } +</script> + +<Drawer bind:this={drawer} size="1100px" on:close={() => (opened = false)}> + <DrawerContent title="Heaviest scripts" on:close={drawer?.closeDrawer}> + <Section + label="Resource usage per script" + tooltip="Aggregated by the workers once an hour, per script and worker group, so the last hour is incomplete. Memory is the peak of the job's main process. CPU time counts that process and the child processes it waited for. Scripts run inside the worker process (SQL, native TypeScript) and jobs of dedicated workers report neither, and a killed job reports no CPU time." + > + {#snippet action()} + <ToggleButtonGroup bind:selected={windowKey} noWFull> + {#snippet children({ item })} + {#each Object.keys(WINDOWS) as key (key)} + <ToggleButton value={key} label={key} size="sm" {item} /> + {/each} + {/snippet} + </ToggleButtonGroup> + {/snippet} + + <div class="flex flex-wrap items-center gap-4 pb-4"> + <div class="flex items-center gap-2"> + <span class="text-xs text-secondary">Sort by</span> + <ToggleButtonGroup + bind:selected={ + () => orderBy, + (v) => { + orderBy = v + logFeatureUsage('worker_resource_stats', 'sort', { key: v }) + } + } + noWFull + > + {#snippet children({ item })} + {#each Object.entries(ORDERS) as [value, label] (value)} + <ToggleButton {value} {label} size="sm" {item} /> + {/each} + {/snippet} + </ToggleButtonGroup> + </div> + <div class="w-48"> + <Select + items={workerGroups.map((g) => ({ label: g, value: g }))} + bind:value={workerGroup} + placeholder="All worker groups" + clearable + size="sm" + /> + </div> + <div class="w-48"> + <TextInput + bind:value={workspace} + inputProps={{ placeholder: 'Workspace id' }} + size="sm" + /> + </div> + </div> + + {#if stats.error} + <Alert type="error" title="Failed to load the script statistics"> + {stats.error.message} + </Alert> + {:else if stats.current === undefined} + <Skeleton layout={[[8]]} /> + {:else if stats.current.length === 0} + <p class="text-secondary text-xs">No jobs were recorded for this selection.</p> + {:else} + <DataTable size="sm" noBorder={false} rounded={true}> + <Head> + <tr> + <Cell head first>Script</Cell> + <Cell head>Workspace</Cell> + <Cell head>Worker group</Cell> + <Cell head numeric>Jobs</Cell> + <Cell head numeric>Total runtime</Cell> + <Cell head numeric>Avg runtime</Cell> + <Cell head numeric>Max memory</Cell> + <Cell head numeric>Avg memory</Cell> + <Cell head numeric>CPU time</Cell> + <Cell head numeric last>Avg CPUs</Cell> + </tr> + </Head> + <tbody> + {#each stats.current as s (s.workspace_id + '\0' + s.runnable_path + '\0' + s.worker_group)} + <tr class="border-b last:border-b-0"> + <Cell first class="text-xs text-primary"> + {#if s.runnable_path === ADHOC_PATH} + <span class="text-secondary">Previews and other ad-hoc runs</span> + {:else} + <span class="font-mono">{s.runnable_path}</span> + {/if} + </Cell> + <Cell class="text-xs text-primary">{s.workspace_id}</Cell> + <Cell class="text-xs text-primary">{s.worker_group}</Cell> + <Cell numeric class="text-xs text-primary">{s.job_count}</Cell> + <Cell numeric class="text-xs text-primary"> + {duration(s.total_duration_ms)} + </Cell> + <Cell numeric class="text-xs text-primary"> + <!-- A workflow suspended and not yet completed has time recorded and no job. --> + {s.job_count > 0 ? duration(s.total_duration_ms / s.job_count) : '-'} + </Cell> + {#if s.memory_sample_count > 0} + <Cell numeric class="text-xs text-primary"> + {formatMemory(s.max_memory_peak)} + </Cell> + <Cell numeric class="text-xs text-primary"> + {formatMemory(Math.round(s.sum_memory_peak / s.memory_sample_count))} + </Cell> + {:else} + <Cell numeric class="text-xs text-secondary">-</Cell> + <Cell numeric class="text-xs text-secondary">-</Cell> + {/if} + <Cell numeric class="text-xs text-primary"> + {duration(s.total_cpu_ms)} + </Cell> + <Cell numeric last class="text-xs text-primary"> + {cores(s.total_cpu_ms, s.total_duration_ms)} + </Cell> + </tr> + {/each} + </tbody> + </DataTable> + {/if} + </Section> + </DrawerContent> +</Drawer> diff --git a/frontend/src/lib/components/InputTransformForm.svelte b/frontend/src/lib/components/InputTransformForm.svelte index 9f8c77ce77..b87afb00f1 100644 --- a/frontend/src/lib/components/InputTransformForm.svelte +++ b/frontend/src/lib/components/InputTransformForm.svelte @@ -105,6 +105,8 @@ pickableProperties?: PickableProperties | undefined enableAi?: boolean hideHelpButton?: boolean + /** A footnote under the input, sharing the Help toggle's row when there is one. */ + hint?: string class?: string editor?: SimpleEditor | undefined otherArgs?: Record<string, InputTransform> @@ -150,6 +152,7 @@ pickableProperties = undefined, enableAi = false, hideHelpButton = false, + hint = undefined, class: className = '', editor = $bindable(undefined), otherArgs = {}, @@ -907,7 +910,9 @@ step-input autocompletion (ghost text, accepted with Tab) doesn't hide the Help dropdown — the two stay independent. --> {#if !hideHelpButton && propertyType === 'javascript' && argKind === 'javascript' && arg.expr != undefined} - <DynamicInputHelpBox /> + <DynamicInputHelpBox {hint} /> + {:else if hint} + <p class="mt-1 text-2xs text-hint">{hint}</p> {/if} {#snippet innerInput()} diff --git a/frontend/src/lib/components/InstanceSetting.svelte b/frontend/src/lib/components/InstanceSetting.svelte index d6740c6c9b..a3a2d19fd6 100644 --- a/frontend/src/lib/components/InstanceSetting.svelte +++ b/frontend/src/lib/components/InstanceSetting.svelte @@ -21,6 +21,7 @@ import SimpleEditor from './SimpleEditor.svelte' import CriticalAlertChannels from './instanceSettings/CriticalAlertChannels.svelte' import RetentionPeriodOverrides from './instanceSettings/RetentionPeriodOverrides.svelte' + import AgentWorkloadIdentityIssuers from './instanceSettings/AgentWorkloadIdentityIssuers.svelte' import SmtpSettings from './instanceSettings/SmtpSettings.svelte' import SecretBackendConfig from './instanceSettings/SecretBackendConfig.svelte' import ExternalInstancePgSettings from './instanceSettings/ExternalInstancePgSettings.svelte' @@ -629,6 +630,8 @@ </Button> </div> </div> + {:else if setting.fieldType == 'agent_workload_identity_issuers'} + <AgentWorkloadIdentityIssuers {values} disabled={!$enterpriseLicense} /> {:else if setting.fieldType == 'critical_error_channels'} <CriticalAlertChannels {values} {openSmtpSettings} {oauths} /> {:else if setting.fieldType == 'otel'} diff --git a/frontend/src/lib/components/InstanceSettings.svelte b/frontend/src/lib/components/InstanceSettings.svelte index 1476b9ad87..0883d9fb5e 100644 --- a/frontend/src/lib/components/InstanceSettings.svelte +++ b/frontend/src/lib/components/InstanceSettings.svelte @@ -29,6 +29,7 @@ import SettingsPageHeader from './settings/SettingsPageHeader.svelte' import WorkspaceRegistries from './instanceSettings/WorkspaceRegistries.svelte' import DbHealth from './instanceSettings/DbHealth.svelte' + import OidcSigningStatus from './instanceSettings/OidcSigningStatus.svelte' interface Props { tab?: string @@ -306,6 +307,8 @@ const connectConfigTemplates: Record<string, any> = Object.fromEntries( Object.entries(oauthConnectRegistry) .filter(([, cfg]) => cfg && typeof cfg === 'object' && 'connect_config_template' in cfg) + // ms_teams takes its tenant from the pinned Teams tile; the backend fills the URLs. + .filter(([name]) => name !== 'ms_teams') .map(([name, cfg]) => [name, (cfg as any).connect_config_template]) ) @@ -325,6 +328,12 @@ // instance name + its registry template (substituting {instance} into the // URLs). Replaces the old per-provider setup functions. function setupTemplatedOauthUrls() { + // The backend falls back to the pre-rename `teams` key when `ms_teams` is absent, so + // turning the Teams tile off (ms_teams saved before, gone now) has to drop both. + // TODO: remove with the backend fallback. + if (oauths && initialOauths?.['ms_teams'] && !oauths['ms_teams'] && oauths['teams']) { + delete oauths['teams'] + } for (const [name, tmpl] of Object.entries(connectConfigTemplates)) { if (!oauths?.[name]) continue const key = tmpl.extra_params_key ?? 'instance' @@ -1186,6 +1195,21 @@ description="On-demand database diagnostics. Analyze table sizes, job retention, connection pool health, vacuum status, and more." /> <DbHealth /> + {:else if category == 'OIDC signing'} + <SettingsPageHeader + title="OIDC signing" + description="What signs the OIDC tokens Windmill issues, and the keys its JWKS serves to verifiers. Read-only: signing is configured with environment variables." + link="https://www.windmill.dev/docs/core_concepts/oidc#signing-key" + /> + {#if $enterpriseLicense} + <OidcSigningStatus /> + {/if} + {:else if category == 'Agent workers'} + <SettingsPageHeader + title="Agent workers" + description="Optional. Agent workers authenticate with the agent token (AGENT_TOKEN) you create on the Workers page with New agent worker, which needs nothing set here. Add an issuer only to also accept workload identity tokens." + link="https://www.windmill.dev/docs/core_concepts/agent_workers" + /> {:else if category == 'Auth/OAuth/SAML'} <AuthSettings bind:oauths diff --git a/frontend/src/lib/components/JobArgs.svelte b/frontend/src/lib/components/JobArgs.svelte index 64ca912608..e0712d66c7 100644 --- a/frontend/src/lib/components/JobArgs.svelte +++ b/frontend/src/lib/components/JobArgs.svelte @@ -15,6 +15,7 @@ import { isWindmillTooBigObject } from './job_args' import { downloadViaClient, shouldDownloadViaClient } from '$lib/utils/downloadFile' import { appendViewToken } from '$lib/viewToken' + import { apiBaseUrl } from '$lib/apiBaseUrl.svelte' interface Props { id?: string | undefined @@ -246,7 +247,7 @@ ${Object.entries(displayArgs) If using the wmill client in your code, set the following env variables: <pre ><code - >BASE_URL="{window.location.origin}" + >BASE_URL="{apiBaseUrl()}" WM_TOKEN="{'<TOKEN>'}"</code ></pre > diff --git a/frontend/src/lib/components/JobLoader.svelte b/frontend/src/lib/components/JobLoader.svelte index c59f4266b7..fa812cc6e4 100644 --- a/frontend/src/lib/components/JobLoader.svelte +++ b/frontend/src/lib/components/JobLoader.svelte @@ -268,7 +268,8 @@ args: Record<string, any>, flow: OpenFlow & { tag?: string }, callbacks?: Callbacks, - path?: string + path?: string, + onBehalfOf?: string ): Promise<string> { return abstractRun( () => @@ -278,7 +279,8 @@ args, value: flow.value, tag: flow.tag, - path + path, + on_behalf_of: onBehalfOf } }), callbacks @@ -336,7 +338,8 @@ flowPath?: string, modules?: Record<string, import('$lib/gen').ScriptModule> | null, tempScriptRefs?: Record<string, string>, - timeout?: number + timeout?: number, + previewAs?: { onBehalfOf?: string; viewerDataAccess?: boolean } ): Promise<string> { return abstractRun( () => @@ -353,7 +356,9 @@ script_hash: hash, flow_path: flowPath, modules: modules ?? undefined, - temp_script_refs: tempScriptRefs + temp_script_refs: tempScriptRefs, + on_behalf_of: previewAs?.onBehalfOf, + viewer_data_access: previewAs?.viewerDataAccess || undefined } }), callbacks diff --git a/frontend/src/lib/components/JobStatus.svelte b/frontend/src/lib/components/JobStatus.svelte index 7945081482..5e79303371 100644 --- a/frontend/src/lib/components/JobStatus.svelte +++ b/frontend/src/lib/components/JobStatus.svelte @@ -34,7 +34,7 @@ <Badge {large} color="orange" title={job.resolution_note}> <!-- `resolved_by` is absent both for an automatic resolution and for a manual one outside EE, so the automatic wording comes from `resolved_automatically`. --> - Failed after {msToReadableTime(job.duration_ms)}, resolved{job.resolved_automatically + {job.canceled ? 'Canceled' : 'Failed'} after {msToReadableTime(job.duration_ms)}, resolved{job.resolved_automatically ? ' automatically' : job.resolved_by ? ` by ${job.resolved_by}` @@ -49,7 +49,7 @@ </Badge> {:else if job && 'success' in job} <Badge {large} color="red"> - Failed after {msToReadableTime(job.duration_ms)} + {job.canceled ? 'Canceled' : 'Failed'} after {msToReadableTime(job.duration_ms)} {#if job.self_wait_time_ms || job.aggregate_wait_time_ms} <WaitTimeWarning self_wait_time_ms={job.self_wait_time_ms} diff --git a/frontend/src/lib/components/JsonInputs.svelte b/frontend/src/lib/components/JsonInputs.svelte index 2f4b04f8e4..546ab36069 100644 --- a/frontend/src/lib/components/JsonInputs.svelte +++ b/frontend/src/lib/components/JsonInputs.svelte @@ -13,13 +13,18 @@ * payload nobody has typed into tracks the schema instead of going stale. The first edit * hands the buffer to the user and later changes stop overwriting it. */ initialCode?: string + /** Show the payload without taking edits. For a caller that must keep this editor + * mounted while refusing writes: swapping it for the fields instead would mount the + * widgets, and a `password` field mints a variable from whatever literal it opens on. */ + readOnly?: boolean } let { updateOnBlur = true, placeholder = 'Write a JSON payload. The input schema will be inferred.<br/><br/>Example:<br/><br/>{<br/>  "foo": "12"<br/>}', selected = false, - initialCode = '' + initialCode = '', + readOnly = false }: Props = $props() let pendingJson = $state(untrack(() => initialCode)) @@ -130,6 +135,7 @@ bind:code={pendingJson} lang="json" class="h-full json-inputs-editor" + {readOnly} {placeholder} /> </div> diff --git a/frontend/src/lib/components/LogViewer.svelte b/frontend/src/lib/components/LogViewer.svelte index be4ecb5b36..f15b87f9ef 100644 --- a/frontend/src/lib/components/LogViewer.svelte +++ b/frontend/src/lib/components/LogViewer.svelte @@ -14,7 +14,6 @@ import { ClipboardCopy, Download, Expand, Loader2, Timer, Cpu } from 'lucide-svelte' import { Button, Drawer, DrawerContent } from './common' import { copyToClipboard } from '$lib/utils' - import { base } from '$lib/base' import { withExternalDomain } from '$lib/externalDomain' import { downloadViaClient, shouldDownloadViaClient } from '$lib/utils/downloadFile' import { appendViewToken } from '$lib/viewToken' @@ -253,7 +252,7 @@ } }) let logsApiPath = $derived(appendViewToken(`/w/${$operatingWorkspace}/jobs_u/get_logs/${jobId}`)) - let downloadHref = $derived(withExternalDomain(`${base}/api${logsApiPath}`)) + let downloadHref = $derived(withExternalDomain(`/api${logsApiPath}`)) let downloadName = $derived(`windmill_logs_${jobId}.txt`) let truncatedContent = $derived( truncateContent(effectiveContent, loadedFromObjectStore, LOG_LIMIT) diff --git a/frontend/src/lib/components/Login.svelte b/frontend/src/lib/components/Login.svelte index 76f4a2b995..1199d01079 100644 --- a/frontend/src/lib/components/Login.svelte +++ b/frontend/src/lib/components/Login.svelte @@ -30,7 +30,6 @@ import { OauthService, UserService, WorkspaceService } from '$lib/gen' import { usersWorkspaceStore, workspaceStore, userStore } from '$lib/stores' import { emptyString, escapeHtml, parseQueryParams } from '$lib/utils' - import { base } from '$lib/base' import { getUserExt } from '$lib/user' import { sendUserToast } from '$lib/toast' import { isCloudHosted } from '$lib/cloud' @@ -354,7 +353,7 @@ // See (root)/+layout.svelte for why /projects/import skips the picker. } else if ( resolvedRd?.startsWith('/user/workspaces') || - resolvedRd?.startsWith(`${base}/projects/import`) + resolvedRd?.startsWith('/projects/import') ) { goto(resolvedRd) } else if (resolvedRd == '/#user-settings') { @@ -575,7 +574,7 @@ if (automatic) params.set('auto', 'true') if (guestApp) params.set('guest_app', guestApp) const query = params.size > 0 ? '?' + params.toString() : '' - let url = base + '/api/oauth/login/' + provider + query + let url = '/api/oauth/login/' + provider + query console.log('storeRedirect', popup, url) if (popup) { @@ -856,7 +855,7 @@ {#if smtpConfigured} <div class="text-center pt-2"> <a - href="{base}/user/forgot-password" + href="/user/forgot-password" class="text-2xs text-blue-500 hover:text-blue-600 dark:text-blue-400 dark:hover:text-blue-300" > Forgot password? diff --git a/frontend/src/lib/components/MemoryFootprintViewer.svelte b/frontend/src/lib/components/MemoryFootprintViewer.svelte index 9547861bc3..14ad1a2b06 100644 --- a/frontend/src/lib/components/MemoryFootprintViewer.svelte +++ b/frontend/src/lib/components/MemoryFootprintViewer.svelte @@ -3,7 +3,7 @@ import { type MetricDataPoint, MetricsService } from '$lib/gen' import { displayTime } from '$lib/utils' - import { workspaceStore } from '$lib/stores' + import { useOperatingWorkspace } from './operatingWorkspace.svelte' import { CategoryScale, Chart as ChartJS, @@ -26,6 +26,8 @@ let { jobId, jobUpdateLastFetch }: Props = $props(); + const operatingWorkspace = useOperatingWorkspace() + let jobMetricsLastFetch: Date | undefined = undefined let jobMemoryStats: MetricDataPoint[] | undefined = $state(undefined) @@ -38,7 +40,7 @@ async function loadMetricsData() { try { let jobStatsPromise = MetricsService.getJobMetrics({ - workspace: $workspaceStore!, + workspace: $operatingWorkspace!, id: jobId, requestBody: { from_timestamp: jobMetricsLastFetch?.toISOString(), diff --git a/frontend/src/lib/components/ModuleTest.svelte b/frontend/src/lib/components/ModuleTest.svelte index 8d2b51e8d0..e7a0769960 100644 --- a/frontend/src/lib/components/ModuleTest.svelte +++ b/frontend/src/lib/components/ModuleTest.svelte @@ -19,11 +19,15 @@ normalizeAgentRef, type LinkedAgentDraft } from './flows/linkedAgentDrafts' - import { AGENT_FLOW_LOCAL_KEYS } from './flows/agentResourceUtils' - import { agentTestInputTransforms } from './flows/agentFormFields' + import { AGENT_LINKED_STEP_KEYS } from './flows/agentResourceUtils' + import { AGENT_OVERRIDE_KEYS, agentTestInputTransforms } from './flows/agentFormFields' import { sendUserToast } from '$lib/toast' import { quickjsReady } from '$lib/utils/quickjsEval.svelte' - import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + import { + useOperatingUser, + useOperatingWorkspace + } from '$lib/components/operatingWorkspace.svelte' + import { previewOnBehalfOf } from '$lib/utils/previewOnBehalfOf' const operatingWorkspace = useOperatingWorkspace() @@ -57,6 +61,16 @@ } = getContext<FlowEditorContext>('FlowEditorContext') let previewBase = $derived($pathStore ?? '') + const operatingUser = useOperatingUser() + // A step runs as the flow does, so its test does too; a workspace script with its own + // `on_behalf_of` runs as that instead, in the flow as here. + let onBehalfOf = $derived( + previewOnBehalfOf( + operatingUser.current, + flowStore?.val?.on_behalf_of, + flowStore?.val?.on_behalf_of_email + ) + ) // Acting workspace when the flow editor runs in an AI session; else the nav workspace. let opWs = $derived(opWorkspace?.() ?? $operatingWorkspace) @@ -126,7 +140,8 @@ previewBase, undefined, devTempScriptRefs?.(), - timeout + timeout, + { onBehalfOf } ) } else if (val.type == 'script') { const script = val.hash @@ -144,7 +159,15 @@ previewBase, undefined, undefined, - timeout + timeout, + { + onBehalfOf: + previewOnBehalfOf( + operatingUser.current, + script.on_behalf_of, + script.on_behalf_of_email + ) ?? onBehalfOf + } ) } else if (val.type == 'flow') { await jobLoader?.runFlowByPath(val.path, args, callbacks) @@ -186,7 +209,13 @@ const inputTransforms = agentTestInputTransforms( agentVal.agent ? {} : ((agentVal.input_transforms ?? {}) as Record<string, InputTransform>), args, - draft ? AGENT_FLOW_LOCAL_KEYS : Object.keys(args) + // An override the step does not hold is left out: fed from the form it would arrive as an + // authored empty value, which clears the agent's saved effort. + (draft ? AGENT_LINKED_STEP_KEYS : Object.keys(args)).filter( + (key) => + !(AGENT_OVERRIDE_KEYS as readonly string[]).includes(key) || + val.input_transforms?.[key] != undefined + ) ) await jobLoader?.runFlowPreview( @@ -213,7 +242,8 @@ schema }, callbacks, - previewBase + previewBase, + onBehalfOf ) } else if (val.type == 'aidecision') { const { schema } = await loadSchemaFromModule(mod, opWs) @@ -235,7 +265,8 @@ schema }, callbacks, - previewBase + previewBase, + onBehalfOf ) } else { throw Error('Not supported module type') diff --git a/frontend/src/lib/components/NavBreadcrumb.svelte b/frontend/src/lib/components/NavBreadcrumb.svelte index 889fe17377..2169149426 100644 --- a/frontend/src/lib/components/NavBreadcrumb.svelte +++ b/frontend/src/lib/components/NavBreadcrumb.svelte @@ -16,13 +16,11 @@ not this component) — so the lead can run the whole line. import WorkspaceItemKindIcon from './WorkspaceItemKindIcon.svelte' import { Menu, Menubar } from '$lib/components/meltComponents' import MeltButton from '$lib/components/meltComponents/MeltButton.svelte' - import BreadcrumbItemContent from './BreadcrumbItemContent.svelte' import WorkspacePickerBody from '$lib/components/sidebar/WorkspacePickerBody.svelte' - import BreadcrumbSegment from '$lib/components/BreadcrumbSegment.svelte' + import BreadcrumbNavPicker from './BreadcrumbNavPicker.svelte' import { userWorkspaces, workspaceStore, workspaceColor, superadmin } from '$lib/stores' import { findWorkspaceRoot } from '$lib/utils/workspaceHierarchy' import { useForkableWorkspaces } from '$lib/utils/useForkableWorkspaces.svelte' - import { base } from '$lib/base' import { twMerge } from 'tailwind-merge' import { Badge } from '$lib/components/common' import Skeleton from '$lib/components/common/skeleton/Skeleton.svelte' @@ -31,17 +29,28 @@ not this component) — so the lead can run the whole line. import { page } from '$app/state' import { navPageFor } from './sidebar/navPages' import { copyToClipboard, getContrastTextColor } from '$lib/utils' - import { KIND_LABEL_LOWER, kindKey } from '$lib/components/workspacePicker' + import { KIND_LABEL_LOWER } from '$lib/components/workspacePicker' import type { PageHeaderItem, PageHeaderSection } from './pageHeaderRegistry.svelte' import type { Snippet } from 'svelte' + import { + BAR_STAGES, + FLOOR, + shownPathLevels, + type Part, + type TrailMeasures, + type TrailStage + } from './pageHeaderStages' let { item, section, afterName, actingWorkspaceId, - narrow = false, - nameOnly = false + nameOnly = false, + stage = BAR_STAGES[0], + caps = {}, + scopesGive = false, + measures = $bindable() }: { item?: PageHeaderItem section?: PageHeaderSection @@ -50,9 +59,14 @@ not this component) — so the lead can run the whole line. afterName?: Snippet /** The workspace the page acts on, when it differs from the one the app is pointed at. */ actingWorkspaceId?: string - /** The bar is short of room: the path holds a tighter cap, so it cannot claim a third of the - * line before anything else has given way. The names truncate at every width either way. */ - narrow?: boolean + /** Which parts the bar has dropped for room (see pageHeaderStages). */ + stage?: TrailStage + /** Max widths the bar holds the names to, once dropping whole parts is not enough. */ + caps?: Partial<Record<Part, number>> + /** The folders above the name truncate too: even the name at its last floor does not fit. */ + scopesGive?: boolean + /** Filled in for the bar to choose a stage with; left undefined, nothing is measured. */ + measures?: TrailMeasures /** Only the page's own name, with no workspace part and no picker — the band inside a * session's preview frame, where the workspace is the host's and leading the reader out of * it is exactly what that band must not offer. The page still has to say what it is. */ @@ -61,7 +75,7 @@ not this component) — so the lead can run the whole line. const scopeId = $derived(actingWorkspaceId ?? $workspaceStore ?? undefined) const homeHref = $derived( - actingWorkspaceId ? `${base}/?workspace=${encodeURIComponent(actingWorkspaceId)}` : `${base}/` + actingWorkspaceId ? `/?workspace=${encodeURIComponent(actingWorkspaceId)}` : `/` ) // With no item or section registered, the route still says where the user is: Runs, Variables, @@ -69,7 +83,7 @@ not this component) — so the lead can run the whole line. // Home is the root the workspace part already stands for, so it names no page of its own. const routePage = $derived.by(() => { if (item || section) return undefined - const found = navPageFor(page.url.pathname, base) + const found = navPageFor(page.url.pathname) return found?.path === '/' ? undefined : found }) @@ -146,6 +160,9 @@ not this component) — so the lead can run the whole line. // The summary is the band's, not the breadcrumb's (see PageHeaderBar), so the path reads as the // last segment only for an item that has no summary to follow it. const itemIsLast = $derived(!!item && !item.summaryContent && !item.summary) + /** Only the summary's text names the item: a control offering to add one does not, and the path + * then stays at every stage. */ + const summaryNamesItem = $derived(!!item?.summary?.trim()) // No hover fill: the chevron beside it is what reacts to the pointer. The accent stays on the // fork's own name inside, so the family's name is not painted as if it were the fork. @@ -157,15 +174,8 @@ not this component) — so the lead can run the whole line. twMerge(SEGMENT, 'hover:bg-transparent', workspaceIsLast && !showFork ? LAST : LEAD) ) - // Capped: a draft's path is a 40-character uuid slug, and the trail yields so grudgingly that - // one would push a page's buttons off the end of the bar. const pathSegment = $derived( - twMerge( - SEGMENT, - 'gap-1.5 overflow-hidden', - itemIsLast ? LAST : LEAD, - narrow ? 'max-w-[11rem]' : 'max-w-[16rem]' - ) + twMerge(SEGMENT, 'gap-1.5 overflow-hidden', itemIsLast ? LAST : LEAD) ) // Copying is the one thing a segment does that leaves no mark on the page, so it is the one // without a hover fill: the pointer and the confirmation under it are the affordance. A segment @@ -192,6 +202,18 @@ not this component) — so the lead can run the whole line. const scopeKind = $derived(item?.path?.split('/')[0]) /** The path's levels, the `f`/`u` prefix dropped — that is what the icon says. */ const pathLevels = $derived((item?.path ?? '').split('/').slice(1).filter(Boolean)) + + // The off-screen copies stand in a fixed-width box for what a page renders into the trail: a + // second render of a page's snippet would be a second live copy of its controls. + let afterNameWidth = $state(0) + let sectionContentWidth = $state(0) + + /** A measured copy holds each name at its floor; the trail on screen at the bar's cap. */ + function capStyle(part: Part, measure: boolean): string | undefined { + if (measure) return `max-width: ${FLOOR[part]}px` + const cap = caps[part] + return cap === undefined ? undefined : `max-width: ${cap}px` + } </script> {#snippet workspaceDisc()} @@ -236,94 +258,149 @@ not this component) — so the lead can run the whole line. {/if} {/snippet} +{#snippet navPicker(measure: boolean)} + <!-- The page's own name is the last segment, so the chevron after it moves to a sibling page or + item. Not in a session's preview band, which must not lead out of the host's workspace. --> + {#if !nameOnly && !section?.noNavPicker} + {#if measure} + <span class="flex items-center h-9 px-1.5 shrink-0"> + <ChevronDown size={ICON} class="flex-shrink-0" /> + </span> + {:else} + <BreadcrumbNavPicker {item} pagePath={routePage?.path} {actingWorkspaceId} iconSize={ICON} /> + {/if} + {/if} +{/snippet} + {#snippet slash(extra = '')} <!-- `extra` tops the workspace part's own 4px gap up to the 6px the breadcrumb puts around its other separators, so the slash before a fork is spaced like every other slash on the line. --> <span class={twMerge('shrink-0 text-hint/40 text-xs', extra)} aria-hidden="true">/</span> {/snippet} -<nav - aria-label="Breadcrumb" - class="flex items-center gap-1.5 min-w-0 text-xs font-normal text-primary" -> +{#snippet workspaceMenu_(measure: boolean)} + {#if measure} + <span class="flex items-center h-9 px-1.5 shrink-0"> + <ChevronDown size={ICON} class="flex-shrink-0" /> + </span> + {:else} + <Menubar> + {#snippet children({ createMenu })} + <Menu + bind:this={workspaceMenu} + {createMenu} + usePointerDownOutside + placement="bottom-start" + class="h-auto" + contentStyle="margin-left: {-nameWidth}px" + > + {#snippet triggr({ trigger })} + <MeltButton + meltElement={trigger} + class="flex items-center h-9 px-1.5 rounded text-tertiary hover:bg-surface-hover hover:text-primary transition-colors" + title="Switch workspace" + > + <ChevronDown size={ICON} class="flex-shrink-0" /> + </MeltButton> + {/snippet} + {#snippet children({ item: menuItem })} + <WorkspacePickerBody + item={menuItem} + collapseFamilies={actingWorkspaceId != undefined} + closeMenu={() => workspaceMenu?.close()} + /> + {/snippet} + </Menu> + {/snippet} + </Menubar> + {/if} +{/snippet} + +{#snippet trail(f: TrailStage, measure: boolean)} + {@const scopeTitle = showFork ? `${familyName} / ${scopeName}` : familyName} {#if !nameOnly} <!-- One part for where the user is: the name of the workspace they are standing in — a fork - included, in its own colour — leading home, and one chevron whose picker changes it. The - picker lists the families and expands one to reach its forks, so a fork needs no part of - its own here. --> - <!-- `shrink-[999]`: the whole trail can give width back, and this part gives it first. Flex - takes it from the parts in proportion to what they ask for, so a factor this far above - the rest means the names here are eaten down to their icons before the page's own name - loses a character. --> - <div class="flex items-center min-w-0 shrink-[999]"> + included, in its own colour — leading home, and one chevron whose picker changes it. The + picker lists the families and expands one to reach its forks, so a fork needs no part of + its own here. Its parts never shrink on their own: the bar drops them whole and caps the + names left, in the order pageHeaderStages sets. --> + <div class="flex items-center shrink-0"> <!-- No hover fill on the name: the chevron beside it is the thing that lights up, and two - boxes reacting to one pass of the pointer read as two controls fighting. --> + boxes reacting to one pass of the pointer read as two controls fighting. --> <!-- bind:clientWidth: the menu hangs from the chevron, so it is shifted back by the width of - the name to line its left edge up with the disc. --> - <div class="flex items-center min-w-0" bind:clientWidth={nameWidth}> - <a - href={homeHref} - class={scopeChipClass} - title={showFork ? `${familyName} / ${scopeName}` : familyName} + the name to line its left edge up with the disc. --> + <div + class="flex items-center" + bind:clientWidth={() => nameWidth, (w) => !measure && (nameWidth = w)} + > + <svelte:element + this={measure ? 'span' : 'a'} + href={measure ? undefined : homeHref} + class={f.wsButton ? 'flex items-center gap-1 pl-1 py-0.5 rounded' : scopeChipClass} + title={scopeTitle} > - <!-- The family's name goes before the fork's: the fork is where the work happens, the - family is which product it is part of, and of the two that is the one a reader can - do without. Both truncate to nothing rather than disappearing at a breakpoint — - what is left then is what the part cannot be read without, the disc in the - workspace's own colour, the fork mark and the environment. The hover title - carries the names whole, and the picker beside it names them all. --> - <span class="flex items-center gap-1 min-w-0 shrink-[999]"> - <BreadcrumbItemContent label={familyName} icon={workspaceDisc} /> - </span> - {#if showFork} - {@render slash('mx-0.5')} - <span class={forkChipClass} style={forkAccent}> - <GitFork size={ICON} class="flex-shrink-0" /> - <span class="truncate">{scopeName}</span> - {@render envBadgeMark()} + {#if f.wsButton} + <!-- Down to its disc, the part still leads home: the fork it stands in rides on the + disc as a mark, and the environment stays beside it. --> + <span class="relative flex shrink-0"> + {@render workspaceDisc()} + {#if showFork} + <span + class={twMerge( + 'absolute -right-1 -bottom-0.5 size-3.5 rounded-full grid place-items-center ring-2 ring-surface', + forkAccent + ? 'bg-[color:var(--fork-accent-badge)] text-white' + : 'bg-surface-sunken text-primary' + )} + style={forkAccent} + > + <GitFork size={9} /> + </span> + {/if} </span> - {:else} {@render envBadgeMark()} + {:else} + <!-- The family's name goes before the fork's: the fork is where the work happens, + the family is which product it is part of, and of the two that is the one a + reader can do without. Outside a fork it is the workspace's own name and stays + until the part is down to its disc. --> + <span class="flex items-center gap-1 shrink-0"> + {@render workspaceDisc()} + {#if f.familyName || !showFork} + <span class="truncate" style={capStyle('family', measure)}>{familyName}</span> + {/if} + </span> + {#if showFork} + {@render slash('mx-0.5')} + <span class={twMerge(forkChipClass, 'shrink-0')} style={forkAccent}> + <GitFork size={ICON} class="flex-shrink-0" /> + {#if f.forkName} + <span class="truncate" style={capStyle('fork', measure)}>{scopeName}</span> + {/if} + {@render envBadgeMark()} + </span> + {:else} + {@render envBadgeMark()} + {/if} {/if} - </a> + </svelte:element> </div> - <Menubar> - {#snippet children({ createMenu })} - <Menu - bind:this={workspaceMenu} - {createMenu} - usePointerDownOutside - placement="bottom-start" - contentStyle="margin-left: {-nameWidth}px" - > - {#snippet triggr({ trigger })} - <MeltButton - meltElement={trigger} - class="flex items-center p-1.5 rounded text-tertiary hover:bg-surface-hover hover:text-primary transition-colors" - title="Switch workspace" - > - <ChevronDown size={ICON} class="flex-shrink-0" /> - </MeltButton> - {/snippet} - {#snippet children({ item: menuItem })} - <WorkspacePickerBody - item={menuItem} - collapseFamilies={actingWorkspaceId != undefined} - closeMenu={() => workspaceMenu?.close()} - /> - {/snippet} - </Menu> - {/snippet} - </Menubar> + {@render workspaceMenu_(measure)} </div> {/if} - {#if !nameOnly && (item || section || routePage)} + <!-- The summary that follows is the item's name for a person, so on a short bar it is the path + that goes (see `TrailStage.path`). What the page hangs after the name stays. --> + {@const pathShown = f.path || !summaryNamesItem} + {#if !nameOnly && (item ? pathShown : section || routePage)} {@render slash()} {/if} {#if item} - {#if item.path} + {#if !pathShown} + {@render afterNameSlot(measure)} + {:else if item.path} + {@const shown = shownPathLevels(pathLevels, f)} <!-- The path whole, as one label rather than a row of pickers: it is what a person reads to know which item this is, and what they reach for to paste somewhere else. --> <div class="relative flex items-center min-w-0"> @@ -334,19 +411,28 @@ not this component) — so the lead can run the whole line. {:else} {@render folderIcon()} {/if} - {#each pathLevels as level, i (i)} + {#each shown as level, i (i)} {#if i > 0}{@render slash()}{/if} - <!-- The scopes above the name absorb the squeeze, the name itself last: a path is - read from its end, and which folder a thing is in is answerable from the - picker while the thing's own name is not. --> - <span - class={i === pathLevels.length - 1 - ? 'truncate' - : 'truncate min-w-0 shrink-[999] max-w-[8rem]'}>{level}</span - > + {#if i === shown.length - 1} + <span class="truncate shrink-0" style={capStyle('name', measure)}>{level}</span> + {:else if level === '…' && !f.middleLevels} + <span class="shrink-0 text-tertiary">…</span> + {:else} + <!-- The folder or user gives width only once the name is down to a few + characters: it is short and says whose thing this is, while a name long + enough to need truncating still reads from its first words. --> + <span + class={twMerge( + 'truncate max-w-[8rem]', + scopesGive && !measure ? 'min-w-0' : 'shrink-0' + )}>{level}</span + > + {/if} {/each} {/snippet} - {#if item.pathTrigger} + {#if measure} + <span class={pathSegment}>{@render pathLabel()}</span> + {:else if item.pathTrigger} <!-- The page hangs its own rename off this segment, anchored here so the editor opens under the path rather than beside the summary. It wears the segment's own classes, so a clickable path reads the same as one that only copies. --> @@ -361,8 +447,9 @@ not this component) — so the lead can run the whole line. {@render pathLabel()} </button> {/if} - {#if afterName}{@render afterName()}{/if} - {#if pathCopied} + {#if itemIsLast}{@render navPicker(measure)}{/if} + {@render afterNameSlot(measure)} + {#if pathCopied && !measure} <span class="absolute left-0 top-full mt-1 z-[6000] rounded-md border bg-surface px-2 py-1 text-2xs text-secondary shadow-md whitespace-nowrap" role="status" @@ -386,40 +473,116 @@ not this component) — so the lead can run the whole line. </span> {/if} {:else if section?.kind} - <BreadcrumbSegment - label={KIND_LABEL_LOWER[section.kind]} - icon={sectionKindIcon} - extraClass={twMerge(SEGMENT, LAST)} - isCurrent - initialHighlight={kindKey(section.kind)} - initialScope={{ kind: section.kind }} - onPick={() => {}} - /> - {:else if section} - <!-- A section's own widget lays out as a row: its title, and whatever belongs with it. --> <span - class={twMerge( - SEGMENT, - LAST, - 'hover:bg-transparent hover:text-emphasis', - section.content ? '' : 'truncate' - )} - aria-current="page" + class={twMerge(SEGMENT, LAST, 'shrink-0 hover:bg-transparent hover:text-emphasis')} + aria-current={measure ? undefined : 'page'} > - {#if section.content}{@render section.content()}{:else}{section.label}{/if} + {@render sectionKindIcon()} + <span class="truncate">{KIND_LABEL_LOWER[section.kind]}</span> </span> - {#if afterName}{@render afterName()}{/if} + {@render navPicker(measure)} + {:else if section} + {#if section.parent} + <!-- Gives width back with the workspace part, before the section's own name does. --> + <span + class={twMerge(SEGMENT, LEAD, 'shrink-[999] hover:bg-transparent hover:text-secondary')} + > + <span class="truncate">{section.parent}</span> + </span> + {@render slash()} + {/if} + {#if section.content && measure} + <span class="shrink-0" style="width: {sectionContentWidth}px"></span> + {:else} + <!-- A section's own widget lays out as a row: its title, and whatever belongs with it. --> + <span + class={twMerge( + SEGMENT, + LAST, + 'hover:bg-transparent hover:text-emphasis', + section.content ? '' : 'shrink-0' + )} + aria-current={measure ? undefined : 'page'} + bind:clientWidth={ + () => sectionContentWidth, (w) => !measure && section.content && (sectionContentWidth = w) + } + > + <!-- A plain label is the page's name, so it truncates the way an item's name does, in + its turn: a run's id, left to flex, is squeezed to nothing under the buttons. --> + {#if section.content}{@render section.content()}{:else}<span + class="truncate" + style={capStyle('name', measure)}>{section.label}</span + >{/if} + </span> + {/if} + {@render navPicker(measure)} + {@render afterNameSlot(measure)} {:else if routePage} {@const RouteIcon = routePage.icon} <!-- shrink-0: a page's own name is short and is the one part of the trail worth keeping whole, so the workspace and fork names give way first when the bar is full. --> <span class={twMerge(SEGMENT, LAST, 'shrink-0 hover:bg-transparent hover:text-emphasis')} - aria-current="page" + aria-current={measure ? undefined : 'page'} > {#if RouteIcon}<RouteIcon size={ICON} class="flex-shrink-0 text-tertiary" />{/if} <span class="truncate">{routePage.label}</span> </span> - {#if afterName}{@render afterName()}{/if} + {@render navPicker(measure)} + {@render afterNameSlot(measure)} {/if} +{/snippet} + +{#snippet afterNameSlot(measure: boolean)} + {#if afterName} + {#if measure} + <span class="shrink-0" style="width: {afterNameWidth}px"></span> + {:else} + <span class="flex items-center shrink-0" bind:clientWidth={afterNameWidth}> + {@render afterName()} + </span> + {/if} + {/if} +{/snippet} + +<nav + aria-label="Breadcrumb" + class="flex items-center gap-1.5 min-w-0 text-xs font-normal text-primary" +> + {@render trail(stage, false)} </nav> + +{#if measures} + <!-- The trail at every stage, each name at its floor, for the bar to choose a stage with; and + each name whole, for it to cap them with. Same snippet, same classes, so the widths are the + ones the trail on screen would take. --> + <div class="absolute -left-[99999px] top-0 invisible" aria-hidden="true" inert> + {#each BAR_STAGES as s, i (i)} + <nav + class="flex items-center gap-1.5 w-max text-xs font-normal text-primary" + bind:clientWidth={measures.trail[i]} + > + {@render trail(s, true)} + </nav> + {/each} + <!-- Always rendered, empty where the page has no such part: a width of 0 is how the bar + knows the part is not there. --> + <span + class={twMerge(scopeChipClass, 'inline-block whitespace-nowrap p-0')} + bind:clientWidth={measures.family}>{nameOnly ? '' : familyName}</span + > + <span + class={twMerge(forkChipClass, 'inline-block whitespace-nowrap p-0')} + bind:clientWidth={measures.fork}>{!nameOnly && showFork ? scopeName : ''}</span + > + <span + class={twMerge('inline-block whitespace-nowrap text-xs', itemIsLast || !item ? LAST : LEAD)} + bind:clientWidth={measures.name} + >{item?.path + ? (pathLevels[pathLevels.length - 1] ?? '') + : !item && section && !section.kind && !section.content + ? section.label + : ''}</span + > + </div> +{/if} diff --git a/frontend/src/lib/components/OAuthSetting.svelte b/frontend/src/lib/components/OAuthSetting.svelte index 60f8e8ef5f..59cbb9247e 100644 --- a/frontend/src/lib/components/OAuthSetting.svelte +++ b/frontend/src/lib/components/OAuthSetting.svelte @@ -90,7 +90,7 @@ disabled={eeOnly && !$enterpriseLicense} on:change={(e) => { if (e.detail) { - if (name === 'teams') { + if (name === 'ms_teams') { value = { id: '', secret: '', tenant: '' } } else { value = { id: '', secret: '' } @@ -106,7 +106,7 @@ </label> {#if enabled} <SettingCard class="mb-4 flex flex-col gap-6"> - {#if name != 'slack' && name != 'teams'} + {#if name != 'slack' && name != 'ms_teams'} <label class="flex flex-col gap-1"> <span class="text-emphasis font-semibold text-xs">Custom Name</span> <TextInput @@ -130,10 +130,10 @@ bind:password={value['secret']} /> </label> - {#if name == 'microsoft' || name == 'teams'} + {#if name == 'microsoft' || name == 'ms_teams'} <label class="flex flex-col gap-1"> <span class="text-emphasis font-semibold text-xs">Tenant Id</span> - {#if name === 'teams'} + {#if name === 'ms_teams'} <TextInput inputProps={{ type: 'text', placeholder: 'Tenant Id' }} bind:value={value['tenant']} @@ -280,14 +280,17 @@ </div> </div> </CollapseLink> - {:else if name == 'teams'} + {:else if name == 'ms_teams'} <CollapseLink text="Instructions"> <div class="text-xs text-primary rounded-md"> Follow this guide on <a href="https://www.windmill.dev/docs/misc/setup_oauth#microsoft-teams" target="_blank">Windmill Docs</a > to create a new Microsoft Teams App. Then paste Client ID, Tenant ID, and Client Secret - here. + here. The same app serves the Teams bot (Enterprise Edition) and the Microsoft Teams + OAuth resource: to connect that resource, also add the redirect URI + <code>BASE_URL/oauth/callback/ms_teams</code> and the delegated Microsoft Graph + permissions you need to the app. </div> </CollapseLink> {/if} diff --git a/frontend/src/lib/components/OnBehalfOfSelector.svelte b/frontend/src/lib/components/OnBehalfOfSelector.svelte index 67648936ae..127e21a9e2 100644 --- a/frontend/src/lib/components/OnBehalfOfSelector.svelte +++ b/frontend/src/lib/components/OnBehalfOfSelector.svelte @@ -19,14 +19,16 @@ kind === 'app' || kind === 'raw_app' || kind === 'trigger' || - isTriggerOrScheduleKind(kind) + isTriggerOrScheduleKind(kind) || + // Only an agent's value carries an identity, so no other resource has a source value. + kind === 'resource' if (!supported) return false return !!sourceValue } </script> <script lang="ts"> - import { Check, UserCog, Users, ExternalLink } from 'lucide-svelte' + import { Check, User as UserIcon, UserCog, Users, ExternalLink } from 'lucide-svelte' import MeltPopover from './meltComponents/Popover.svelte' import Portal from './Portal.svelte' import Modal from './common/modal/Modal.svelte' @@ -74,6 +76,9 @@ * one is the wrong name whenever the deploy targets a different workspace. */ myPermissionedAs?: string + /** Without `canPreserve`, show the current user as plain text instead of a popover whose + * only enabled option is "me". The host must treat that as the choice already made. */ + readOnlyWithoutPreserve?: boolean } let { @@ -88,7 +93,8 @@ folderDefault = undefined, aboveConfirmationModal = false, onPickerOpenChange = undefined, - myPermissionedAs = undefined + myPermissionedAs = undefined, + readOnlyWithoutPreserve = false }: Props = $props() const isTrigger = $derived(kind === 'trigger' || isTriggerOrScheduleKind(kind)) @@ -187,77 +193,84 @@ }) </script> -<MeltPopover - placement="bottom" - contentClasses={aboveConfirmationModal ? 'z-[10001]' : ''} - on:openChange={(e) => e.detail && loadUsers()} -> - {#snippet trigger()} - <span class="inline-flex items-center gap-1"> - <UserCog class="w-4 h-4 {selected ? 'text-green-500' : 'text-yellow-500'}" /> - {#if selectedDisplayName} - <span class="text-xs truncate max-w-24">{selectedDisplayName}</span> - {/if} - {#if isFolderDefaultSelected} - <span - class="text-[10px] px-1 py-0.5 rounded bg-blue-50 dark:bg-blue-950/50 text-blue-700 dark:text-blue-300 border border-blue-200 dark:border-blue-900" - title="From this folder's default_permissioned_as rule" +{#if readOnlyWithoutPreserve && !canPreserve} + <span class="inline-flex items-center gap-1 text-xs text-secondary"> + <UserIcon class="w-4 h-4" /> + {myDisplayName} + </span> +{:else} + <MeltPopover + placement="bottom" + contentClasses={aboveConfirmationModal ? 'z-[10001]' : ''} + on:openChange={(e) => e.detail && loadUsers()} + > + {#snippet trigger()} + <span class="inline-flex items-center gap-1"> + <UserCog class="w-4 h-4 {selected ? 'text-green-500' : 'text-yellow-500'}" /> + {#if selectedDisplayName} + <span class="text-xs truncate max-w-24">{selectedDisplayName}</span> + {/if} + {#if isFolderDefaultSelected} + <span + class="text-[10px] px-1 py-0.5 rounded bg-blue-50 dark:bg-blue-950/50 text-blue-700 dark:text-blue-300 border border-blue-200 dark:border-blue-900" + title="From this folder's default_permissioned_as rule" + > + folder default + </span> + {/if} + </span> + {/snippet} + {#snippet content({ close: closePopover })} + <div class="p-3 flex flex-col gap-2 min-w-48"> + <div class="text-xs font-medium text-secondary mb-1">{label}</div> + <!-- Target option --> + {#if targetValue} + <button + class="flex items-center gap-2 px-2 py-1.5 rounded text-left text-xs hover:bg-surface-hover {!canPreserve + ? 'opacity-50 cursor-not-allowed' + : ''}" + disabled={!canPreserve} + onclick={() => onSelect('target')} + > + <Check class="w-3 h-3 {selected === 'target' ? 'opacity-100' : 'opacity-0'}" /> + <span class="truncate max-w-40">{targetDisplayName}</span> + <span class="text-xs text-tertiary">{isDeployment ? '(target)' : '(current)'}</span> + </button> + {/if} + <!-- Me option --> + <button + class="flex items-center gap-2 px-2 py-1.5 rounded text-left text-xs hover:bg-surface-hover" + onclick={() => onSelect('me')} > - folder default - </span> - {/if} - </span> - {/snippet} - {#snippet content({ close: closePopover })} - <div class="p-3 flex flex-col gap-2 min-w-48"> - <div class="text-xs font-medium text-secondary mb-1">{label}</div> - <!-- Target option --> - {#if targetValue} + <Check class="w-3 h-3 {selected === 'me' ? 'opacity-100' : 'opacity-0'}" /> + <span class="truncate max-w-40">{myDisplayName}</span> + <span class="text-xs text-tertiary">(me)</span> + </button> + <!-- Custom / Pick from workspace --> <button class="flex items-center gap-2 px-2 py-1.5 rounded text-left text-xs hover:bg-surface-hover {!canPreserve ? 'opacity-50 cursor-not-allowed' : ''}" disabled={!canPreserve} - onclick={() => onSelect('target')} + onclick={() => { + closePopover() + openModal() + }} > - <Check class="w-3 h-3 {selected === 'target' ? 'opacity-100' : 'opacity-0'}" /> - <span class="truncate max-w-40">{targetDisplayName}</span> - <span class="text-xs text-tertiary">{isDeployment ? '(target)' : '(current)'}</span> + {#if selected === 'custom' && customDisplayName} + <Check class="w-3 h-3 opacity-100" /> + <span class="truncate max-w-40">{customDisplayName}</span> + <span class="text-xs text-tertiary">(custom)</span> + {:else} + <Check class="w-3 h-3 opacity-0" /> + <Users class="w-3 h-3 text-tertiary" /> + <span>Pick from workspace…</span> + {/if} </button> - {/if} - <!-- Me option --> - <button - class="flex items-center gap-2 px-2 py-1.5 rounded text-left text-xs hover:bg-surface-hover" - onclick={() => onSelect('me')} - > - <Check class="w-3 h-3 {selected === 'me' ? 'opacity-100' : 'opacity-0'}" /> - <span class="truncate max-w-40">{myDisplayName}</span> - <span class="text-xs text-tertiary">(me)</span> - </button> - <!-- Custom / Pick from workspace --> - <button - class="flex items-center gap-2 px-2 py-1.5 rounded text-left text-xs hover:bg-surface-hover {!canPreserve - ? 'opacity-50 cursor-not-allowed' - : ''}" - disabled={!canPreserve} - onclick={() => { - closePopover() - openModal() - }} - > - {#if selected === 'custom' && customDisplayName} - <Check class="w-3 h-3 opacity-100" /> - <span class="truncate max-w-40">{customDisplayName}</span> - <span class="text-xs text-tertiary">(custom)</span> - {:else} - <Check class="w-3 h-3 opacity-0" /> - <Users class="w-3 h-3 text-tertiary" /> - <span>Pick from workspace…</span> - {/if} - </button> - </div> - {/snippet} -</MeltPopover> + </div> + {/snippet} + </MeltPopover> +{/if} <!-- User selection modal. Portalled: the modal positions itself with `fixed`, which resolves against the nearest transformed ancestor — inside a dialog card (which is transformed for diff --git a/frontend/src/lib/components/PageHeaderBar.svelte b/frontend/src/lib/components/PageHeaderBar.svelte index 7a97d60f2e..1ad2602d8e 100644 --- a/frontend/src/lib/components/PageHeaderBar.svelte +++ b/frontend/src/lib/components/PageHeaderBar.svelte @@ -7,15 +7,19 @@ section name — and the route's own buttons at the far end. The row's height matches the sidebar's own header row, so the two read as one band. --> <script lang="ts"> - import { PanelLeft } from 'lucide-svelte' + import { ChevronDown, PanelLeft } from 'lucide-svelte' import { Button } from '$lib/components/common' import { navDetached } from './sidebar/navDetached.svelte' import { navHandleSlot } from './sidebar/navHandlePlacement.svelte' import NavBreadcrumb from './NavBreadcrumb.svelte' + import BreadcrumbNavPicker from './BreadcrumbNavPicker.svelte' import { BAR_HEIGHT, pageHeader, PHONE_BAR } from './pageHeaderRegistry.svelte' import ContextBridge from './ContextBridge.svelte' import { afterNavigate } from '$app/navigation' import { twMerge } from 'tailwind-merge' + import { onDestroy } from 'svelte' + import type { Attachment } from 'svelte/attachments' + import { BAR_STAGES, FLOOR, fitBar, type BarFit, type TrailMeasures } from './pageHeaderStages' let { navHidden = false, @@ -32,15 +36,101 @@ The row's height matches the sidebar's own header row, so the two read as one ba const item = $derived(content?.item) const section = $derived(content?.section) + const hasSummary = $derived(!!item && !!(item.summaryContent || item.summary)) + /** A summary control can be a placeholder offering to add one; the text is what names the item. */ + const summaryNamesItem = $derived(!!item?.summary?.trim()) + const pickerAfterSummary = $derived(hasSummary && !navHidden && !!item?.path) - // Below this the trail holds a tighter cap on the path it draws. The names in it truncate on - // their own at any width (see NavBreadcrumb), so this is not a breakpoint the look changes at — - // it only stops a long path from claiming a third of a short bar before the squeeze starts. - const NARROW_BAR = 1000 - const narrow = $derived(pageHeader.barWidth > 0 && pageHeader.barWidth < NARROW_BAR) - /** A phone's bar: the trail gives way before the page's buttons do (see the markup). */ + /** A phone's bar: a tighter gutter around the same row. */ const phone = $derived(pageHeader.barWidth > 0 && pageHeader.barWidth < PHONE_BAR) + // What the bar drops, and when the page's actions fold, follows from the widths of what is in + // it (see pageHeaderStages): measured here and in NavBreadcrumb, never guessed per page. + /** `gap-1` between the bar's boxes. */ + const GAP = 4 + /** Actions that shrink or fill the bar have no width of their own to plan around: the trail + * leaves them this much and they take whatever is left. */ + const FLEXIBLE_ACTIONS_RESERVE = 240 + + let trailMeasures = $state<TrailMeasures>({ trail: [], family: 0, fork: 0, name: 0 }) + /** The summary held at its floor, with the dot before it. */ + let summaryFloorWidth = $state(0) + let summaryTextWidth = $state(0) + /** A page's own summary control, last seen uncapped. */ + let summaryContentWidth = $state(0) + let handleWidth = $state(0) + /** The actions box at each fold level it has been seen at, for this page. */ + let actionWidthsByVersion = $state<Record<string, (number | undefined)[]>>({}) + let actionsEpoch = $state(0) + const actionsVersion = $derived(content?.actionsVersion ?? '') + const actionWidths = $derived(actionWidthsByVersion[actionsVersion] ?? []) + + const handleShown = $derived((navDetached.val || panelled) && !navHidden) + // The bar's own padding, in px, as the classes on the row below set it. + const padLeft = $derived(navHidden ? 16 : phone ? 4 : 8) + const padRight = $derived(content?.actionsFill ? 0 : phone ? 8 : 16) + const actionsRigid = $derived(!content?.actionsFlexible && !content?.actionsFill) + const FULL: BarFit = { stage: 0, fold: 0, caps: {}, scopesGive: false } + + const fit = $derived.by((): BarFit => { + // Unmeasured counts as wide: the bar measures itself on mount, and starting narrow would fold + // a page's buttons for one frame and pop them back out the next. + if (pageHeader.barWidth === 0) return FULL + return fitBar({ + barWidth: pageHeader.barWidth, + chrome: padLeft + padRight + (handleShown ? handleWidth + GAP : 0), + trail: trailMeasures.trail, + summary: BAR_STAGES.map(() => (hasSummary ? GAP + summaryFloorWidth : 0)), + actions: + actions.length === 0 ? [0] : actionsRigid ? actionWidths : [GAP + FLEXIBLE_ACTIONS_RESERVE], + folds: actions.length > 0 && actionsRigid ? (content?.actionFolds ?? 0) : 0, + earlyFolds: content?.earlyActionFolds, + summaryNamesItem, + natural: { + family: trailMeasures.family, + fork: trailMeasures.fork, + summary: hasSummary ? (item?.summaryContent ? summaryContentWidth : summaryTextWidth) : 0, + name: trailMeasures.name + } + }) + }) + const stage = $derived(BAR_STAGES[fit.stage]) + /** The level alone: `fit` is a new object on every recompute, and the attachment re-measuring + * on each one would feed itself. */ + const fold = $derived(fit.fold) + onDestroy(pageHeader.provideActionFold(() => fold)) + + // Re-attached whenever the fold level, the page or the actions' version changes, so the first + // reading there is taken even when the row comes out exactly as wide as it was before. + // The page's actions can change on screen — a run's Cancel goes once the job completes — and + // the other levels most likely changed with them, so a change here drops their widths: kept, a + // stale wider one would hold the row folded for good. The bar measures them again by trying. + function recordActions(fold: number, width: number) { + const version = actionsVersion + const widths = actionWidthsByVersion[version] ?? [] + const seen = widths[fold] + // Unchanged, nothing is written: a write recomputes `fit`, and a reading that always wrote + // kept the bar measuring every frame. + if (seen === width) return + const next = seen !== undefined ? [] : [...widths] + next[fold] = width + actionWidthsByVersion[version] = next + } + function measureActions( + fold: number, + _epoch: number, + _version: string + ): Attachment<HTMLElement> { + return (node) => { + const ro = new ResizeObserver(() => recordActions(fold, GAP + node.offsetWidth)) + ro.observe(node) + return () => ro.disconnect() + } + } + // Until the row has been seen at the level the bar picked, it is laid out but not shown: the bar + // may find it does not fit and fold it further, and that should not flash. + const actionsUnmeasured = $derived(actionsRigid && actionWidths[fit.fold] === undefined) + // The band's edge is there to say "something is passing under me", so it is drawn only while // something is. Scroll events do not bubble, but they do capture, so one listener on the window // sees every box under the band — which matters because most pages scroll inside their own @@ -68,8 +158,14 @@ The row's height matches the sidebar's own header row, so the two read as one ba scrolledUnder = next } // A page left while scrolled would otherwise hand its edge to the next one, which may have - // nothing to scroll at all. - afterNavigate(() => (scrolledUnder = false)) + // nothing to scroll at all. Its actions' widths go with it. + afterNavigate(({ from, to }) => { + scrolledUnder = false + if (from?.url.pathname !== to?.url.pathname) { + actionWidthsByVersion = {} + actionsEpoch++ + } + }) const separator = $derived(pageHeader.content?.separator ?? 'onScroll') const showEdge = $derived(separator === 'always' || (separator === 'onScroll' && scrolledUnder)) @@ -85,132 +181,213 @@ The row's height matches the sidebar's own header row, so the two read as one ba data-page-header bind:clientWidth={() => pageHeader.barWidth, (w) => pageHeader.setBarWidth(w)} class={twMerge( - 'flex items-center gap-1 shrink-0 min-w-0 bg-surface transition-shadow duration-150', - // One row at every width. A wrapping row never squeezes anything — flex moves an item to the - // next line instead of taking it below its content width — so wrapping here would hand the - // trail a line of its own and leave it whole, which is the opposite of what a narrow bar - // wants: the trail truncating from its start. - phone ? `${BAR_HEIGHT} pl-1 pr-2` : `${BAR_HEIGHT} pl-2 pr-4`, - // The filling surface is what meets the right edge, so the bar keeps no gutter of its own - // there. - content?.actionsFill && 'pr-0', - // The small left padding is there to sit a button against: the sidebar handle, or the - // workspace disc, both of which carry their own visual margin. Embedded there is neither, - // and the page's name would start as bare text 8px from the edge. - navHidden && 'pl-4', + 'flex flex-col shrink-0 min-w-0 bg-surface transition-shadow duration-150', showEdge && 'shadow-[inset_0_-1px_0_0_rgb(var(--color-border-light))] dark:shadow-[inset_0_-1px_0_0_#374151] [html.github-dark_&]:shadow-[inset_0_-1px_0_0_rgb(var(--color-border-light))]' )} > - {#if (navDetached.val || panelled) && !navHidden} - <!-- Reveals the hidden sidebar, and only that: the card follows the pointer, holding while it + <div + class={twMerge( + 'flex items-center gap-1 min-w-0', + // No flex-wrap. A wrapping row never squeezes anything — flex moves an item to the next line + // instead of taking it below its content width — so wrapping here would hand the trail a + // line of its own and leave it whole. What needs a line of its own asks for one through + // `belowBar`, at a fold the bar picks. + phone ? `${BAR_HEIGHT} pl-1 pr-2` : `${BAR_HEIGHT} pl-2 pr-4`, + // The filling surface is what meets the right edge, so the bar keeps no gutter of its own + // there. + content?.actionsFill && 'pr-0', + // The small left padding is there to sit a button against: the sidebar handle, or the + // workspace disc, both of which carry their own visual margin. Embedded there is neither, + // and the page's name would start as bare text 8px from the edge. + navHidden && 'pl-4' + )} + > + {#if (navDetached.val || panelled) && !navHidden} + <!-- Reveals the hidden sidebar, and only that: the card follows the pointer, holding while it is on the handle, on the card, or in a menu either opened, and sliding back out when it - leaves. Where no pointer hovers, a tap opens it and it stays until dismissed. Attaching + leaves. A click or tap pins it instead, until another one here, a press on the page or Esc + puts it back. Attaching it for good belongs to the toggle in the sidebar's own footer, where detaching it happened. Docked, the sidebar speaks for itself and nothing leads the bar. --> - <!-- svelte-ignore a11y_no_static_element_interactions --> - <div - data-nav-handle - onmouseenter={() => navHandleSlot.open()} - onmouseleave={() => navHandleSlot.scheduleClose()} - > - <!-- No tooltip: hovering here already slides the sidebar in, which says what the button + <!-- svelte-ignore a11y_no_static_element_interactions --> + <div + data-nav-handle + bind:clientWidth={handleWidth} + onmouseenter={() => navHandleSlot.open()} + onmouseleave={() => navHandleSlot.scheduleClose()} + > + <!-- No tooltip: hovering here already slides the sidebar in, which says what the button does better than a label popping up over it. --> - <Button - variant="subtle" - unifiedSize="sm" - iconOnly - startIcon={{ icon: PanelLeft }} - aria-label="Show sidebar" - onclick={() => navHandleSlot.open()} - /> - </div> - {/if} + <Button + variant="subtle" + unifiedSize="sm" + iconOnly + startIcon={{ icon: PanelLeft }} + aria-label="Show sidebar" + selected={navHandleSlot.pinned} + aria-pressed={navHandleSlot.pinned} + onclick={() => navHandleSlot.toggle()} + /> + </div> + {/if} - <!-- The breadcrumb yields width more slowly than the page's controls (shrink-[0.3]) but it does - yield, at every width: the trail truncates from its start, so the squeeze is spent on the - workspace and the folders before it ever reaches the name of the thing the page is about. - The 5rem floor is what is left when every name in it has gone — the workspace disc, the - fork mark and the environment badge, which is as small as the part can be and still say - where the user is. + <!-- The breadcrumb's parts are rigid and the bar sizes them (see `fit`): it drops whole parts + and caps the names left, so this box only shrinks past what they add up to on a bar too + narrow for even the last stage. An embed (`navHidden`) keeps the page's own name but drops the workspace part around it: the trail would offer to navigate the host's workspace, while the name is what says which page the controls beside it belong to. --> - <div class="flex shrink-[0.3] min-w-[5rem]"> - <!-- Bridged like the actions below: what a page hangs off its own name renders here, out of + <div class="flex min-w-0"> + <!-- Bridged like the actions below: what a page hangs off its own name renders here, out of the tree that named it, and the rename editor in there asks that tree who the acting user is before it offers to rename anything. --> - <!-- Each fragment the band renders comes from another tree and reads that tree's state. The + <!-- Each fragment the band renders comes from another tree and reads that tree's state. The registry already tolerates a registration that cannot answer while its owner's data is being cleared (see `read`); the same window reaches rendering, and an error here would otherwise travel to the root and blank the app rather than the one fragment. A boundary per fragment keeps that to the fragment. --> - <svelte:boundary onerror={(e) => console.error('page header: breadcrumb failed to render', e)}> - {#key content?.contexts} - <ContextBridge contexts={content?.contexts}> - <NavBreadcrumb - {item} - {section} - {narrow} - nameOnly={navHidden} - afterName={content?.afterName} - actingWorkspaceId={content?.actingWorkspaceId} - /> - </ContextBridge> - {/key} - </svelte:boundary> - </div> - - {#if item && (item.summaryContent || item.summary)} - <!-- No kind icon: the page below is the item, and saying "this is a flow" above a flow - editor tells the reader what they can already see. --> - <div class={twMerge('flex items-center gap-1 min-w-0', phone && 'shrink')}> - <!-- A dot rather than a slash: the summary names the same item the path just located, it - is not another level of it. Inside this box so that it narrows with the summary. --> - <span class="shrink-0 text-hint/40 text-xs px-0.5" aria-hidden="true">·</span> - {#if item.summaryContent} - <svelte:boundary onerror={(e) => console.error('page header: summary failed to render', e)}> - {#key content?.contexts} - <ContextBridge contexts={content?.contexts}> - {@render item.summaryContent()} - </ContextBridge> - {/key} - </svelte:boundary> - {:else} - <span class="min-w-0 truncate text-xs font-medium text-emphasis">{item.summary}</span> - {/if} + <svelte:boundary + onerror={(e) => console.error('page header: breadcrumb failed to render', e)} + > + {#key content?.contexts} + <ContextBridge contexts={content?.contexts}> + <NavBreadcrumb + {item} + {section} + {stage} + caps={fit.caps} + scopesGive={fit.scopesGive} + bind:measures={trailMeasures} + nameOnly={navHidden} + afterName={content?.afterName} + actingWorkspaceId={content?.actingWorkspaceId} + /> + </ContextBridge> + {/key} + </svelte:boundary> </div> - {/if} - {#if actions.length > 0} - <!-- min-w-0, not shrink-0: a page whose actions are a filter row (Runs) puts a control in - here that can give width back, and it can only do that if this box may shrink. A phone - only tightens the gutter — pages fold their own buttons into a menu at that width, and - a box that refused to shrink would make the one flexible field take its max instead. --> - <!-- `actionsFill`: the actions are a surface rather than a row, so they take the rest of the + {#if item && hasSummary} + <!-- No kind icon: the page below is the item, and saying "this is a flow" above a flow + editor tells the reader what they can already see. --> + <div class="flex items-center gap-1 shrink-0"> + <!-- A dot after the path: the summary names the same item the path just located, it is not + another level of it. With the path dropped it follows the workspace, and the slash is + the trail's own separator. Fixed width, so either fits the width measured below. --> + <span class="shrink-0 w-2 text-center text-hint/40 text-xs" aria-hidden="true" + >{stage.path || !summaryNamesItem ? '·' : '/'}</span + > + {#if item.summaryContent} + <!-- Read only while uncapped: capped, the box says how wide the bar let it be, not how + wide the page's control wants to be. --> + <div + class="flex min-w-0 overflow-hidden" + style={fit.caps.summary === undefined ? undefined : `max-width: ${fit.caps.summary}px`} + bind:clientWidth={ + () => summaryContentWidth, + (w) => fit.caps.summary === undefined && (summaryContentWidth = w) + } + > + <svelte:boundary + onerror={(e) => console.error('page header: summary failed to render', e)} + > + {#key content?.contexts} + <ContextBridge contexts={content?.contexts}> + {@render item.summaryContent()} + </ContextBridge> + {/key} + </svelte:boundary> + </div> + {:else} + <span + class="truncate text-xs font-medium text-emphasis" + style={fit.caps.summary === undefined ? undefined : `max-width: ${fit.caps.summary}px`} + >{item.summary}</span + > + {/if} + <!-- The summary ends the trail here, so the breadcrumb's chevron follows it instead. Not + before the path lands: the picker opens in the item's folder, which it reads once. --> + {#if pickerAfterSummary} + <BreadcrumbNavPicker {item} actingWorkspaceId={content?.actingWorkspaceId} /> + {/if} + </div> + {/if} + + {#if actions.length > 0} + <!-- A plain row of buttons holds its width (shrink-0): squeezing it only pushes buttons out + of the bar, so the bar makes room by dropping breadcrumb parts and then by asking the + page to fold (`actionFolds`). Flexible actions (the Runs filter row) are a control that + can give width back, which it can only do if this box may shrink. --> + <!-- `actionsFill`: the actions are a surface rather than a row, so they take the rest of the bar and run to its right edge, and they stretch its full height because that surface sits on the bottom edge. --> + <div + {@attach measureActions(fold, actionsEpoch, actionsVersion)} + class={twMerge( + 'flex', + // pl-4: the gap between the breadcrumb and the filling surface is bare bar, so it + // belongs here rather than inside that surface, where it would be filled. + content?.actionsFill + ? 'flex-1 min-w-0 self-stretch items-stretch pl-4' + : 'ml-auto items-center', + !content?.actionsFill && (actionsRigid ? 'shrink-0' : 'min-w-0'), + !content?.actionsFill && (phone ? 'gap-1 pl-1' : 'gap-2 pl-4'), + actionsUnmeasured && 'invisible' + )} + > + {#each actions as entry, i (i)} + <svelte:boundary + onerror={(e) => console.error('page header: actions failed to render', e)} + > + {#key entry.contexts} + <ContextBridge contexts={entry.contexts}> + {@render entry.render()} + </ContextBridge> + {/key} + </svelte:boundary> + {/each} + </div> + {/if} + + {#if item && hasSummary} + <!-- The summary at its floor, which is what a stage that keeps it needs; and whole, which is + what the bar caps it from. A page's own control stands in at the width last seen. --> + <div class="absolute -left-[99999px] top-0 invisible" aria-hidden="true" inert> + <div class="flex items-center gap-1 w-max" bind:clientWidth={summaryFloorWidth}> + <span class="shrink-0 w-2 text-center text-hint/40 text-xs">·</span> + {#if item.summaryContent} + <span style="width: {Math.min(summaryContentWidth, FLOOR.summary)}px"></span> + {:else} + <span class="truncate text-xs font-medium" style="max-width: {FLOOR.summary}px" + >{item.summary}</span + > + {/if} + {#if pickerAfterSummary} + <span class="flex items-center h-9 px-1.5 shrink-0"><ChevronDown size={14} /></span> + {/if} + </div> + <span + class="inline-block whitespace-nowrap text-xs font-medium" + bind:clientWidth={summaryTextWidth}>{item.summary ?? ''}</span + > + </div> + {/if} + </div> + {#if content?.belowBar && fit.fold >= (content.belowBarFold ?? 0)} + <!-- Same gutter as the row above, so what moved down lines up with the breadcrumb's start. --> <div - class={twMerge( - 'flex', - // pl-4: the gap between the breadcrumb and the filling surface is bare bar, so it - // belongs here rather than inside that surface, where it would be filled. - content?.actionsFill - ? 'flex-1 min-w-0 self-stretch items-stretch pl-4' - : 'ml-auto items-center', - !content?.actionsFill && (phone && !content?.actionsFlexible ? 'shrink-0' : 'min-w-0'), - !content?.actionsFill && (phone ? 'gap-1 pl-1' : 'gap-2 pl-4') - )} + class={twMerge('flex items-center pb-2', phone ? 'px-2' : 'pl-3 pr-4', navHidden && 'pl-4')} > - {#each actions as entry, i (i)} - <svelte:boundary onerror={(e) => console.error('page header: actions failed to render', e)}> - {#key entry.contexts} - <ContextBridge contexts={entry.contexts}> - {@render entry.render()} - </ContextBridge> - {/key} - </svelte:boundary> - {/each} + <svelte:boundary + onerror={(e) => console.error('page header: second row failed to render', e)} + > + {#key content?.contexts} + <ContextBridge contexts={content?.contexts}> + {@render content.belowBar()} + </ContextBridge> + {/key} + </svelte:boundary> </div> {/if} </div> diff --git a/frontend/src/lib/components/PageHeaderContent.svelte b/frontend/src/lib/components/PageHeaderContent.svelte index 2630faf863..cc37b727cb 100644 --- a/frontend/src/lib/components/PageHeaderContent.svelte +++ b/frontend/src/lib/components/PageHeaderContent.svelte @@ -18,6 +18,11 @@ the header, so nesting is decided by the caller rather than guessed from context actionsOrder, actionsFlexible, actionsFill, + actionFolds, + earlyActionFolds, + actionsVersion, + belowBar, + belowBarFold, separator, contexts, actingWorkspaceId, @@ -33,6 +38,11 @@ the header, so nesting is decided by the caller rather than guessed from context actionsOrder, actionsFlexible, actionsFill, + actionFolds, + earlyActionFolds, + actionsVersion, + belowBar, + belowBarFold, separator, contexts, actingWorkspaceId, diff --git a/frontend/src/lib/components/ParqetCsvTableRenderer.svelte b/frontend/src/lib/components/ParqetCsvTableRenderer.svelte index f51d9b4536..da409b697a 100644 --- a/frontend/src/lib/components/ParqetCsvTableRenderer.svelte +++ b/frontend/src/lib/components/ParqetCsvTableRenderer.svelte @@ -8,7 +8,6 @@ import { twMerge } from 'tailwind-merge' import DarkModeObserver from './DarkModeObserver.svelte' import { AppService, HelpersService } from '$lib/gen' - import { base } from '$lib/base' import { downloadViaClient, shouldDownloadViaClient } from '$lib/utils/downloadFile' import { enterpriseLicense } from '$lib/stores' import { Download } from 'lucide-svelte' @@ -267,7 +266,7 @@ {:else} <a target="_blank" - href="{base}/api{csvApiPath}" + href="/api{csvApiPath}" class="text-secondary w-full text-right underline text-2xs whitespace-nowrap" ><div class="flex flex-row-reverse gap-2 items-center"><Download size={12} /> CSV</div></a > diff --git a/frontend/src/lib/components/PersistentScriptDrawer.svelte b/frontend/src/lib/components/PersistentScriptDrawer.svelte index 168169e937..e1bd3401bd 100644 --- a/frontend/src/lib/components/PersistentScriptDrawer.svelte +++ b/frontend/src/lib/components/PersistentScriptDrawer.svelte @@ -3,7 +3,6 @@ import { Badge, Button, Drawer } from './common' import DrawerContent from './common/drawer/DrawerContent.svelte' import { createEventDispatcher, onDestroy } from 'svelte' - import { base } from '$lib/base' import { displayDate, sleep, sendUserToast } from '$lib/utils' import TableCustom from './TableCustom.svelte' import { Hourglass, Loader2, Play, RefreshCw } from 'lucide-svelte' @@ -141,7 +140,7 @@ <td class="text-xs"> <a class="pr-3" - href="{base}/scripts/get/{scriptHash}?workspace={$operatingWorkspace}" + href="/scripts/get/{scriptHash}?workspace={$operatingWorkspace}" target="_blank" > {scriptHash} @@ -150,7 +149,7 @@ <td class="text-xs"> <a class="pr-3" - href="{base}/run/{jobId}?workspace={$operatingWorkspace}" + href="/run/{jobId}?workspace={$operatingWorkspace}" target="_blank">{jobId.substring(24)}</a > </td> diff --git a/frontend/src/lib/components/ResourceEditor.svelte b/frontend/src/lib/components/ResourceEditor.svelte index 9847454aca..33ab00abbf 100644 --- a/frontend/src/lib/components/ResourceEditor.svelte +++ b/frontend/src/lib/components/ResourceEditor.svelte @@ -7,7 +7,8 @@ type Resource, type ResourceType } from '$lib/gen' - import { canWrite } from '$lib/utils' + import { canEditItem } from '$lib/editRights' + import { userWorkspaces } from '$lib/stores' import { createEventDispatcher, onDestroy, untrack } from 'svelte' import { sendUserToast } from '$lib/toast' import { clearJsonSchemaResourceCache } from './schema/jsonSchemaResource.svelte' @@ -261,8 +262,16 @@ if (!initialPath || !selected) return true const r = fetchedResources[selected] if (!r || !acting.resolved(selected)) return undefined - return canWrite(current?.path ?? initialPath, r.extra_perms ?? {}, acting.in(selected)) + return canEditResourceIn(selected, current?.path ?? initialPath, r.extra_perms) }) + function canEditResourceIn( + ws: string, + path: string, + extraPerms: Record<string, boolean> | undefined + ): boolean { + const settings = $userWorkspaces.find((w) => w.id === ws)?.operator_settings + return canEditItem('resource', path, extraPerms, acting.in(ws), settings) + } const dirtyWorkspaces = $derived( Object.keys(states).filter((ws) => !draftValuesEqual(states[ws].draft, initialStates[ws])) @@ -423,9 +432,7 @@ const dirtyCanWrite = $derived( dirtyWorkspaces.every((ws) => { const r = fetchedResources[ws] - return ( - !r || canWrite(states[ws]?.draft?.path ?? initialPath, r.extra_perms ?? {}, acting.in(ws)) - ) + return !r || canEditResourceIn(ws, states[ws]?.draft?.path ?? initialPath, r.extra_perms) }) ) @@ -645,6 +652,11 @@ const s = states[ws].draft! const ini = initialStates[ws] if (existedInitially[ws]) { + const fetched = fetchedResources[ws] + // An agent keeps the identity its value names, as its own editor keeps it: without + // the flag an admin's save would take it over. The backend resets it to the writer + // for anyone not allowed to keep it. + const keepAgentObo = fetched?.resource_type === 'ai_agent' && !!s.args?.on_behalf_of await ResourceService.updateResource({ workspace: ws, path: ini.path, @@ -653,10 +665,10 @@ value: s.args, description: s.description, labels: s.labels, - ws_specific: s.wsSpecific + ws_specific: s.wsSpecific, + preserve_on_behalf_of: keepAgentObo ? true : undefined } }) - const fetched = fetchedResources[ws] if (fetched?.resource_type === 'json_schema') { clearJsonSchemaResourceCache(ini.path, ws) } diff --git a/frontend/src/lib/components/RunForm.svelte b/frontend/src/lib/components/RunForm.svelte index 7be09785b1..c01f7598ca 100644 --- a/frontend/src/lib/components/RunForm.svelte +++ b/frontend/src/lib/components/RunForm.svelte @@ -75,6 +75,13 @@ } export async function run(overrideScheduledForStr?: string | undefined | null) { + // Ahead of everything, including the flush below: the secret processing further down + // creates a variable per `password` argument, so a refusal that waits for `runAction` + // has already written. The keybinding reaches here without the button. + if (runRefusal) { + sendUserToast(runRefusal, true) + return + } // An editor whose text does not parse never wrote it to `args`, so running now would send // the last value that did parse. Flush first: a keystroke still inside the editor debounce // has not been parsed yet, and per-field editors parse it in an effect, hence the tick. @@ -127,6 +134,15 @@ extra_perms?: Record<string, boolean> } | undefined + /** Set to refuse every write this form can make, and to say so when a run is + * attempted: the fields are disabled, the dynamic-select helper is not wired, the JSON + * editor is read-only, and `run()` refuses before it mints the `password` arguments it + * would send — so a caller cannot gate this in `runAction`, which comes after that + * mint. For a form standing in for a chat card under plan mode, which promised none of + * it. The caller must also leave this form on the side it is showing: swapping fields + * for JSON or back mounts a `password` widget, which mints from the literal it opens + * on regardless of being disabled. */ + runRefusal?: string runAction: ( scheduledForStr: string | undefined, args: Record<string, any>, @@ -160,6 +176,7 @@ let { runnable, runAction, + runRefusal = undefined, buttonText = 'Run', schedulable = true, detailed = true, @@ -178,6 +195,8 @@ actions = undefined }: Props = $props() + const argsReadonly = $derived(!!runRefusal) + let showPsCommonParams = $derived( runnable?.language === 'powershell' && runnable?.schema?.['x-windmill-ps-cmd-binding'] === true ) @@ -333,7 +352,10 @@ > <JsonInputs bind:this={jsonEditor} + readOnly={argsReadonly} on:select={(e) => { + // The other way into the arguments, and the one disabling the fields misses. + if (argsReadonly) return blockedByUnparseable = false if (e.detail) { args = enforceDisabledDefaults(e.detail, runnable?.schema).args @@ -350,11 +372,14 @@ {#key reloadArgs} <div bind:clientHeight={schemaHeight}> <SchemaForm - helperScript={{ - source: 'deployed', - path: runnable.path!, - runnable_kind: runnable.hash ? 'script' : 'flow' - }} + helperScript={argsReadonly + ? undefined + : { + source: 'deployed', + path: runnable.path!, + runnable_kind: runnable.hash ? 'script' : 'flow' + }} + disabled={argsReadonly} prettifyHeader {noVariablePicker} {autofocus} @@ -382,7 +407,7 @@ variant="accent" unifiedSize="md" btnClasses="!inline-flex" - disabled={!isValid && !jsonView} + disabled={(!isValid && !jsonView) || argsReadonly} on:click={() => run()} shortCut={{ Icon: CornerDownLeft, hide: !viewKeybinding }} > @@ -431,7 +456,7 @@ variant="accent" unifiedSize="md" btnClasses="!inline-flex" - disabled={!isValid && !jsonView} + disabled={(!isValid && !jsonView) || argsReadonly} on:click={() => run(null)} shortCut={{ Icon: CornerDownLeft, hide: !viewKeybinding }} > @@ -444,7 +469,7 @@ <Button btnClasses="!px-6 !py-1 w-full" variant="accent" - disabled={!isValid && !jsonView} + disabled={(!isValid && !jsonView) || argsReadonly} on:click={() => run(null)} shortCut={{ Icon: CornerDownLeft, hide: !viewKeybinding }} > diff --git a/frontend/src/lib/components/RunsPage.svelte b/frontend/src/lib/components/RunsPage.svelte index 72950dc53c..9019c2d16e 100644 --- a/frontend/src/lib/components/RunsPage.svelte +++ b/frontend/src/lib/components/RunsPage.svelte @@ -11,14 +11,12 @@ import { sendUserToast } from '$lib/toast' import { displayDate } from '$lib/utils' + import { userWorkspaces, superadmin, devopsRole, enterpriseLicense } from '$lib/stores' + import { useHostedPage } from '$lib/components/hostedPage' import { - userStore, - workspaceStore, - userWorkspaces, - superadmin, - devopsRole, - enterpriseLicense - } from '$lib/stores' + useOperatingUser, + useOperatingWorkspace + } from '$lib/components/operatingWorkspace.svelte' import { Button, Drawer, DrawerContent, Skeleton, Tab, Tabs } from '$lib/components/common' import TextInput from '$lib/components/text_input/TextInput.svelte' import RunChart from '$lib/components/RunChart.svelte' @@ -37,9 +35,8 @@ import RunsQueue from '$lib/components/runs/RunsQueue.svelte' import OpenInSessionButton from '$lib/components/sessions/OpenInSessionButton.svelte' import PageHeaderContent from '$lib/components/PageHeaderContent.svelte' - import { pageHeader, PHONE_BAR } from '$lib/components/pageHeaderRegistry.svelte' - import { pageHref, RUNS_PATH } from '$lib/components/sessions/previewPaths' - import { twMerge } from 'tailwind-merge' + import { pageHeader } from '$lib/components/pageHeaderRegistry.svelte' + import { RUNS_PATH } from '$lib/components/sessions/previewPaths' import { computeJobKinds, useJobsLoader } from '$lib/components/runs/useJobsLoader.svelte' import ConcurrentJobsChart from '$lib/components/ConcurrentJobsChart.svelte' import BatchLoadProgress from '$lib/components/BatchLoadProgress.svelte' @@ -81,6 +78,13 @@ let { initialPath }: Props = $props() + // Under a host — an AI session's preview tab — the document URL, the page header band and + // the navigation workspace all belong to the host: the filters live where it keeps them, + // the filter row renders in the page, and requests go to the workspace it names. + const hosted = useHostedPage() + const operatingWorkspace = useOperatingWorkspace() + const operatingUser = useOperatingUser() + let paths: string[] = $state([]) let usernames: string[] = $state([]) let folders: string[] = $state([]) @@ -91,7 +95,7 @@ folders, jobTriggerKinds, isSuperAdminOrDevops: !!$superadmin || !!$devopsRole, - isAdminsWorkspace: $workspaceStore === 'admins' + isAdminsWorkspace: $operatingWorkspace === 'admins' }) ) let perPage = useLocalStorageValue('runs_per_page', 1000, 'number') @@ -115,6 +119,8 @@ // what was seeded at mount is gone. Re-apply it. Editing a filter writes with `replaceState`, // which never reaches `page.url`, so a filter the user clears stays cleared. $effect(() => { + // A host remounts the page when it re-points it, and its document URL is not this page's. + if (hosted) return page.url.href untrack(() => filters.seed(filterSeeds())) }) @@ -146,6 +152,7 @@ title: string confirmBtnText: string loading?: boolean + description?: string preContent?: string onConfirm?: (forceCancel: boolean) => void type?: ConfirmationModal['$$prop_def']['type'] @@ -171,7 +178,9 @@ let manualTimeframe = $derived(timeframe.type === 'manual' ? timeframe : undefined) let graph: 'RunChart' | 'ConcurrencyChart' = $state( - typeOfChart(page.url.searchParams.get('graph')) + typeOfChart( + (hosted ? new URLSearchParams(hosted.search) : page.url.searchParams).get('graph') + ) ) let innerWidth = $state(window.innerWidth) let jobsLoader = useJobsLoader(() => ({ @@ -183,7 +192,7 @@ resultError, perPage: perPage.val, lookback: graph === 'RunChart' ? 0 : lookback, - currentWorkspace: $workspaceStore ?? '' + currentWorkspace: $operatingWorkspace ?? '' })) let batchProgress = $derived(jobsLoader.batchProgress) let currentBatchSize = $derived(jobsLoader.currentBatchSize) @@ -211,18 +220,18 @@ } async function loadUsernames(): Promise<void> { - usernames = await UserService.listUsernames({ workspace: $workspaceStore! }) + usernames = await UserService.listUsernames({ workspace: $operatingWorkspace! }) } async function loadFolders(): Promise<void> { folders = await FolderService.listFolders({ - workspace: $workspaceStore! + workspace: $operatingWorkspace! }).then((x) => x.map((y) => y.name)) } async function loadPaths() { - const npaths_scripts = await ScriptService.listScriptPaths({ workspace: $workspaceStore ?? '' }) - const npaths_flows = await FlowService.listFlowPaths({ workspace: $workspaceStore ?? '' }) + const npaths_scripts = await ScriptService.listScriptPaths({ workspace: $operatingWorkspace ?? '' }) + const npaths_flows = await FlowService.listFlowPaths({ workspace: $operatingWorkspace ?? '' }) paths = npaths_scripts.concat(npaths_flows).sort() } @@ -265,7 +274,7 @@ const resultFilter = filters.val.result && JSON.parse(filters.val.result) const { minTs, maxTs } = timeframe.computeMinMax() return { - workspace: $workspaceStore ?? '', + workspace: $operatingWorkspace ?? '', startedBefore: maxTs ?? undefined, startedAfter: minTs ?? undefined, schedulePath: filters.val.schedule_path ?? undefined, @@ -323,7 +332,7 @@ } async function cancelJobs(uuidsToCancel: string[], forceCancel: boolean = false) { const uuids = await JobService.cancelSelection({ - workspace: $workspaceStore ?? '', + workspace: $operatingWorkspace ?? '', requestBody: uuidsToCancel, forceCancel: forceCancel, allWorkspaces: filters.val.all_workspaces || undefined @@ -350,7 +359,7 @@ for (const j of jobs ?? []) if (j.workspace_id) workspaceById.set(j.id, j.workspace_id) const byWorkspace = new Map<string, string[]>() for (const id of jobIds) { - const ws = workspaceById.get(id) ?? $workspaceStore ?? '' + const ws = workspaceById.get(id) ?? $operatingWorkspace ?? '' const bucket = byWorkspace.get(ws) if (bucket) bucket.push(id) else byWorkspace.set(ws, [id]) @@ -428,7 +437,8 @@ } async function reRunJobs(jobIdsToReRun: string[], batchReRunOptions: BatchReRunOptions) { - if (!$workspaceStore) return + if (!$operatingWorkspace) return + const batching = filterMatchedIds !== undefined if (askingForConfirmation) { askingForConfirmation.loading = true @@ -442,7 +452,7 @@ // workaround because EventSource does not support POST requests // https://medium.com/@david.richards.tech/sse-server-sent-events-using-a-post-request-without-eventsource-1c0bd6f14425 - const response = await fetch(`${OpenAPI.BASE}/w/${$workspaceStore}/jobs/run/batch_rerun_jobs`, { + const response = await fetch(`${OpenAPI.BASE}/w/${$operatingWorkspace}/jobs/run/batch_rerun_jobs`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) @@ -478,7 +488,11 @@ } if (reRanUuids.length !== jobIdsToReRun.length) { sendUserToast( - `Failed to re-run ${jobIdsToReRun.length - reRanUuids.length} jobs. Check console for details`, + `Failed to re-run ${jobIdsToReRun.length - reRanUuids.length} jobs. Check console for details` + + // Only a re-run resolves its source, so these stay first in line. + (batching + ? '. They stay unresolved and the next batch will try them again: resolve them to skip them' + : ''), true ) // We do not get explicit error from backend if the job script don't exist @@ -501,13 +515,31 @@ jobsLoader?.loadJobs(true, true) } + // Every failed or canceled job "Re-run all jobs matching filters" found, oldest first, so a + // batch limit takes the oldest ones. Re-running resolves them, so under "Hide resolved runs" + // the next click picks up where the previous batch stopped. + let filterMatchedIds: string[] | undefined = $state() + let rerunLimit: number | undefined = $state() + // The pane closes from several places, the table included; a stale match list would then + // offer its limit over a selection it no longer describes. + $effect(() => { + if (!batchRerunOptionsIsOpen) untrack(() => (filterMatchedIds = undefined)) + }) + + function setRerunLimit(limit: number | undefined) { + if (!filterMatchedIds) return + rerunLimit = limit && limit > 0 ? limit : undefined + selectedIds = filterMatchedIds.slice(0, rerunLimit ?? filterMatchedIds.length) + } + async function onRerunAllJobsMatchingFilters() { const selectedFilters = getSelectedFilters() selectedIds = [] const loadingToast = sendUserToast('Loading job ids', 'info') - if (filters.val.job_kinds !== 'runs') { + // Selecting "runs" deletes the key, since it is the default. + if ((filters.val.job_kinds ?? 'runs') !== 'runs') { sendUserToast('Batch re-run is only supported for scripts and flows', true) loadingToast.destroy() return @@ -516,11 +548,21 @@ // workspace. started_at >= minTs implies completed_at >= minTs, so completedAfter adds a // lossless indexed lower bound ((workspace_id, completed_at DESC)); started_at stays the // exact recheck. (completedBefore is omitted: it would drop jobs that finish after maxTs.) - selectedIds = await JobService.listFilteredJobsUuids({ + const ids = await JobService.listFilteredJobsUuids({ ...selectedFilters, completedAfter: selectedFilters.startedAfter, - jobKinds: 'script,flow' + orderDesc: false }) + // Batching needs both halves of its promise: only failed or canceled sources are resolved + // by a re-run, and only a status filter keeps the queue out of the lookup, whose union + // drops the ordering. Anything else re-runs every match, as one batch. + if (selectedFilters.status === 'failure' || selectedFilters.status === 'canceled') { + filterMatchedIds = ids + setRerunLimit(rerunLimit) + } else { + filterMatchedIds = undefined + selectedIds = ids + } loadingToast.destroy() batchRerunOptionsIsOpen = true } @@ -530,6 +572,10 @@ askingForConfirmation = { title: `Confirm re-running the selected jobs`, confirmBtnText: `Re-run ${jobIdsToReRun.length} jobs`, + // The server skips resolution for operators, who cannot resolve. + description: operatingUser.current?.operator + ? undefined + : "Failed or canceled jobs among them will be marked resolved, with the new run's id as the note.", type: 'reload', onConfirm: async () => { await reRunJobs(jobIdsToReRun, batchReRunOptions) @@ -555,7 +601,7 @@ } $effect(() => { - if ($workspaceStore) { + if ($operatingWorkspace) { untrack(() => { loadUsernames() loadFolders() @@ -603,7 +649,12 @@ openedRunId = undefined } let resolutionNote = $state('') - const phone = $derived(pageHeader.barWidth > 0 && pageHeader.barWidth < PHONE_BAR) + // The bar folds this row (`actionFolds` below) once its breadcrumb has given all it can: first + // the counters, which are a glance and repeat the chart below; then the session button; then + // the filter field moves to a row of its own rather than shrinking past usable. Hosted, the row + // is the page's own and wraps instead. + const fold = $derived(hosted ? 0 : pageHeader.actionFold) + const filterBelow = $derived(fold >= 3) </script> {#snippet runsHint()} @@ -615,18 +666,34 @@ </Tooltip> {/snippet} +{#snippet runsFilter(cls: string)} + <FilterSearchbar + class={cls} + schema={runsFilterSearchbarSchema} + presets={buildRunsFilterPresets({ + isSuperAdminOrDevops: !!$superadmin || !!$devopsRole, + isAdminsWorkspace: $operatingWorkspace === 'admins' + })} + bind:value={filters.val} + placeholder="Filter runs..." + size="sm" + autofocus={!hosted} + /> +{/snippet} + +{#snippet filterRow()} + {@render runsFilter('relative w-full min-w-0')} +{/snippet} + {#snippet headerActions()} <!-- The page's own row inside the band's actions box: these controls are denser than a page's - two or three buttons, so they take a wider gap than the band's own. `flex-1 min-w-0` passes - the band's flexibility down to the search field, the one control here that gives width - back; the rest keep theirs or drop out of the row entirely at a width. --> - <div class="flex items-center gap-3 flex-1 min-w-0"> + two or three buttons, so they take a wider gap than the band's own. Every control keeps its + width: the bar measures the row and folds it rather than squeezing it. --> + <div class="flex items-center gap-3 {hosted ? 'flex-wrap justify-end' : ''}"> <!-- Always the icon form: the bar has room for two counters, never for the two labelled blocks. pr-2 on top of the row's own gap because the counts hang outside their icons, - so without it the badge butts against the first filter. - A phone's bar has room for the filter field and the timeframe and nothing else: the - counters are a glance, and the same numbers are on the chart below. --> - <div class="flex items-center pr-2 {phone ? 'hidden' : ''}"> + so without it the badge butts against the first filter. --> + <div class="flex items-center pr-2 {fold >= 1 ? 'hidden' : ''}"> <RunsQueue success={filters.val.status ?? null} {queue_count} @@ -797,32 +864,10 @@ </div> </div> - <!-- The one control in the band that gives way: everything else keeps the width it asked - for, or drops out of the row at a width, and this takes what is left. --> - <FilterSearchbar - class={twMerge( - // A width of its own, and only ever less. As `flex-1` the field was whatever the row - // had left over, so a chip appearing or a filter committing resized it under the - // cursor and the last pixels came off the breadcrumb. 18rem is its width whenever the - // row fits, and it still shrinks when the row runs short, which is what keeps the row - // inside a box the bar lets shrink (`actionsFlexible`). `min-w-0` is what makes that - // shrink unconditional: a flex item's floor is its min-content width, which the chips - // inside the field raise, so without it a typed filter would push the field wider - // again exactly when the row has no room to give. - 'relative w-[18rem] min-w-0 max-w-full', - // A phone's bar cannot spare that much before the timeframe beside it. - phone && 'w-[10rem]' - )} - schema={runsFilterSearchbarSchema} - presets={buildRunsFilterPresets({ - isSuperAdminOrDevops: !!$superadmin || !!$devopsRole, - isAdminsWorkspace: $workspaceStore === 'admins' - })} - bind:value={filters.val} - placeholder="Filter runs..." - size="sm" - autofocus - /> + <!-- A width of its own, never what the row has left over: as `flex-1` a chip appearing or a + filter committing resized it under the cursor. `shrink-0` keeps it at that width, which + is the row's width the bar measures and folds. --> + {#if !filterBelow}{@render runsFilter('relative w-[18rem] shrink-0')}{/if} <TimeframeSelect unifiedSize="sm" onClick={() => jobsLoader?.loadJobs(true)} @@ -833,11 +878,11 @@ <!-- The filters are shallow-routed, so the search has to come off `window.location` at click time — `page.url` never sees them. Always the canonical `/runs`: only that is a recognized preview page, and the `/runs/<path>` route mirrors its path into `?path=` anyway. --> - <div class={phone ? 'hidden' : 'contents'}> + <div class={fold >= 2 || hosted ? 'hidden' : 'contents'}> <OpenInSessionButton source={{ - page: () => pageHref(RUNS_PATH) + window.location.search, - workspaceId: $workspaceStore ?? undefined + page: () => RUNS_PATH + window.location.search, + workspaceId: $operatingWorkspace ?? undefined }} btnProps={{ unifiedSize: 'sm' }} /> @@ -860,6 +905,9 @@ askingForConfirmation = undefined }} > + {#if askingForConfirmation?.description} + <p class="text-xs text-secondary">{askingForConfirmation.description}</p> + {/if} {#if askingForConfirmation?.preContent} <pre>{askingForConfirmation.preContent}</pre> <Toggle @@ -900,22 +948,33 @@ </DrawerContent> </Drawer> +<!-- The document's history is the host's: its Back is not a move on this page. --> <svelte:window onpopstate={() => { - reset() + if (!hosted) reset() }} /> -{#if $userStore?.operator && $workspaceStore && !$userWorkspaces.find((_) => _.id === $workspaceStore)?.operator_settings?.runs} +{#if operatingUser.current?.operator && $operatingWorkspace && !$userWorkspaces.find((_) => _.id === $operatingWorkspace)?.operator_settings?.runs} <div class="bg-red-100 border-l-4 border-red-600 text-orange-700 p-4 m-4 mt-12" role="alert"> <p class="font-bold">Unauthorized</p> <p>Page not available for operators</p> </div> {:else} <div class="w-full h-full flex flex-col" bind:clientWidth={innerWidth}> - <!-- `actionsFlexible`: the filter row holds a search field that can give width back, so the - bar lets this box shrink on a phone instead of holding its content width. --> - <PageHeaderContent afterName={runsHint} actions={headerActions} actionsFlexible /> + {#if hosted} + <div class="flex px-4 pt-3 pb-2"> + {@render headerActions()} + </div> + {:else} + <PageHeaderContent + afterName={runsHint} + actions={headerActions} + actionFolds={3} + belowBar={filterRow} + belowBarFold={3} + /> + {/if} <!-- Graph --> <div id="runs-chart" class="p-2 px-4 bg-surface-tertiary mx-4 border rounded-md"> @@ -1103,14 +1162,15 @@ action: () => { manualSelectionMode = 'rerun' selectedIds = [] + filterMatchedIds = undefined batchRerunOptionsIsOpen = true } }, - ...(!$userStore?.operator + ...(!operatingUser.current?.operator ? [ { // Operators are rejected by the endpoint, so offering it would only 403. - displayName: 'Resolve failed jobs', + displayName: 'Resolve failed or canceled jobs', action: () => ( (manualSelectionMode = 'resolve'), (selectedIds = []), @@ -1192,7 +1252,7 @@ class="rounded-md bg-surface-tertiary border absolute inset-0 mb-4 flex flex-col items-center justify-center gap-3 p-4" > <p class="text-xs text-secondary text-center max-w-xs"> - Resolving keeps the run a failure but stops it showing as one in the runs list. + Resolving keeps the run's status but marks it as handled in the runs list. </p> <TextInput bind:value={resolutionNote} @@ -1285,15 +1345,59 @@ {/snippet} {#snippet batchRerunOptions()} - {#await import('$lib/components/runs/BatchReRunOptionsPane.svelte') then BatchReRunOptionsPane} - <BatchReRunOptionsPane.default - {selectedIds} - onCancel={() => ((batchRerunOptionsIsOpen = false), (manualSelectionMode = undefined))} - onConfirm={async (options) => { - await onReRunSelectedJobs(options) - }} - /> - {/await} + <div class="flex flex-col h-full"> + {#if filterMatchedIds} + <div class="flex flex-col gap-1 pb-2 text-xs text-secondary"> + <div class="flex flex-row items-center gap-2"> + <span>{filterMatchedIds.length} jobs match the filters, re-run at most</span> + <TextInput + inputProps={{ type: 'number', min: 1, placeholder: 'All' }} + size="sm" + class="w-24" + bind:value={ + () => rerunLimit?.toString() ?? '', + (v) => setRerunLimit(v ? parseInt(v.toString()) : undefined) + } + /> + </div> + {#if filters.val.resolved === 'unresolved'} + <span class="text-hint"> + Oldest first. Re-run jobs are marked resolved, so the next batch starts where this one + stops. + </span> + {:else} + <div class="flex flex-row items-center gap-2 text-orange-600 dark:text-orange-400"> + <TriangleAlertIcon size={14} class="shrink-0" /> + <span> + Resolved runs are included, so the next batch will pick these same jobs again. + </span> + <Button + variant="default" + unifiedSize="xs" + btnClasses="shrink-0" + onClick={() => { + filters.val.resolved = 'unresolved' + onRerunAllJobsMatchingFilters() + }} + > + Hide resolved runs + </Button> + </div> + {/if} + </div> + {/if} + <div class="flex-1 min-h-0 flex flex-col"> + {#await import('$lib/components/runs/BatchReRunOptionsPane.svelte') then BatchReRunOptionsPane} + <BatchReRunOptionsPane.default + {selectedIds} + onCancel={() => ((batchRerunOptionsIsOpen = false), (manualSelectionMode = undefined))} + onConfirm={async (options) => { + await onReRunSelectedJobs(options) + }} + /> + {/await} + </div> + </div> {/snippet} {#snippet jobPreview(pending?: Snippet)} diff --git a/frontend/src/lib/components/S3FilePicker.svelte b/frontend/src/lib/components/S3FilePicker.svelte index ce1af47118..a5e4849c57 100644 --- a/frontend/src/lib/components/S3FilePicker.svelte +++ b/frontend/src/lib/components/S3FilePicker.svelte @@ -105,6 +105,7 @@ size="1200px" > <DrawerContent + noPadding title={s3ResourcePath ? `Exploring ${s3ResourcePath}` : 'S3 file browser'} on:close={() => { s3FilePickerInner?.exit?.() diff --git a/frontend/src/lib/components/S3FilePickerInner.svelte b/frontend/src/lib/components/S3FilePickerInner.svelte index 1bf1b4358a..89c23e84ae 100644 --- a/frontend/src/lib/components/S3FilePickerInner.svelte +++ b/frontend/src/lib/components/S3FilePickerInner.svelte @@ -8,8 +8,35 @@ Loader2, Download, Trash, - MoveRight + MoveRight, + Ellipsis, + FileText, + FileCode, + FileJson, + FileSpreadsheet, + FileImage, + FileArchive, + FilePlay, + FileAudio, + Table2 } from 'lucide-svelte' + import { Pane, Splitpanes } from 'svelte-splitpanes' + import TextInput from './text_input/TextInput.svelte' + import Select from './select/Select.svelte' + import Toggle from './Toggle.svelte' + import ToggleButtonGroup from './common/toggleButton-v2/ToggleButtonGroup.svelte' + import ToggleButton from './common/toggleButton-v2/ToggleButton.svelte' + import type { IDbTableOps } from './dbOps' + import { resource } from 'runed' + import { staticDbTableOps } from './staticDbTableOps' + import { + fetchJsonTableRows, + isJsonFile, + JSON_TABLE_MAX_BYTES, + s3TableOps, + serverTableFormat, + type S3TableSource + } from './s3TableOps' import { CancelablePromise, HelpersService, @@ -28,21 +55,19 @@ type MoveS3FileData, type MoveS3FileResponse } from '$lib/gen' - import { base } from '$lib/base' import { displayDate, displaySize, emptyString, parseS3Object, sendUserToast, - type S3Object + type S3Object, + type IconType } from '$lib/utils' import { downloadViaClient, shouldDownloadViaClient } from '$lib/utils/downloadFile' - import { Alert, Button } from './common' - import Section from './Section.svelte' + import { Alert, Button, CopyButton } from './common' import { createEventDispatcher, untrack, type Snippet } from 'svelte' import VirtualList from '@tutorlatin/svelte-tiny-virtual-list' - import TableSimple from './TableSimple.svelte' import ConfirmationModal from './common/confirmationModal/ConfirmationModal.svelte' import FileUploadModal from './common/fileUpload/FileUploadModal.svelte' import S3FilePreview from './S3FilePreview.svelte' @@ -144,8 +169,14 @@ let rootPath = $state(initialRootPath) let rootPathNestingLevel = $derived(1 * (rootPath.split('/').length - 1)) - let csvSeparatorChar: string = $state(',') + let csvSeparatorChar: string | undefined = $state(undefined) let csvHasHeader: boolean = $state(true) + const CSV_SEPARATORS = [ + { value: ',', label: ',' }, + { value: ';', label: ';' }, + { value: '\t', label: 'Tab' }, + { value: '|', label: '|' } + ] let dispatch = createEventDispatcher<{ close: { s3: string; storage: string | undefined } | undefined @@ -179,6 +210,68 @@ } | undefined = $state(undefined) + let viewMode: 'table' | 'text' = $state('table') + /** The selected file, when it can be shown as a table. Its own requests can't read + * files behind a custom listing (git repos), so those keep the text preview. */ + let tableSource = $derived.by(() => { + if (hideS3SpecificDetails || !fileMetadata || !ws) return undefined + const fileKey = fileMetadata.fileKey + const inBrowser = isJsonFile(fileKey) && (fileMetadata.size ?? Infinity) <= JSON_TABLE_MAX_BYTES + if (!inBrowser && !serverTableFormat(fileKey)) return undefined + return { + workspace: ws, + fileKey, + storage, + s3ResourcePath, + csvSeparator: csvSeparatorChar, + csvHasHeader, + inBrowser + } + }) + let tableKey = $derived(tableSource && JSON.stringify(tableSource)) + let tableOps = resource( + () => (viewMode === 'table' ? tableSource : undefined), + async (source, _previous, { signal }) => { + if (!source) return undefined + const key = JSON.stringify(source) + // A response for a file or options since left must not replace the current one; + // the resource drops a fetch that throws an AbortError. + const superseded = () => new DOMException('Superseded', 'AbortError') + try { + const table = source.inBrowser ? await jsonTable(source) : await s3TableOps(source) + if (signal.aborted) throw superseded() + return { key, ops: table?.ops, csvSeparator: table?.csvSeparator } + } catch (e) { + throw signal.aborted ? superseded() : e + } + } + ) + async function jsonTable( + source: S3TableSource + ): Promise<{ ops: IDbTableOps; csvSeparator?: string } | undefined> { + const rows = await fetchJsonTableRows(source) + return rows && { ops: staticDbTableOps(rows, 'duckdb', source.fileKey.split('/').pop() ?? '') } + } + /** The loaded table, once it belongs to the selected file and options. */ + let currentTable = $derived(tableOps.current?.key === tableKey ? tableOps.current : undefined) + /** A JSON file that turns out not to be an array has no table to show. */ + let showTable = $derived( + viewMode === 'table' && !!tableSource && !(currentTable && !currentTable.ops) + ) + // Each file starts on the separator the server guesses from its first bytes. + $effect(() => { + fileMetadata?.fileKey + untrack(() => { + csvSeparatorChar = undefined + detectedCsvSeparator = undefined + }) + }) + /** Kept while the file stays selected, so the text view still shows what was guessed. */ + let detectedCsvSeparator: string | undefined = $state(undefined) + $effect(() => { + if (currentTable?.csvSeparator) detectedCsvSeparator = currentTable.csvSeparator + }) + /** Identifies the metadata request that currently owns the preview pane. */ let metadataRequestId = 0 @@ -229,6 +322,25 @@ /** Per-level listing only makes sense while browsing; searching stays flat. */ let lazyMode = $derived(lazyFolders && filter.trim() === '') + /** `nestingLevel` counts two per folder depth. */ + function treeRowIndent(nestingLevel: number): string { + return `padding-left: ${12 + (nestingLevel / 2) * 16}px;` + } + + const FILE_ICONS: [RegExp, IconType][] = [ + [/\.(csv|tsv|xlsx?|parquet|ods)$/i, FileSpreadsheet], + [/\.(json|jsonl|ndjson)$/i, FileJson], + [/\.(png|jpe?g|gif|webp|svg|bmp|ico|tiff?)$/i, FileImage], + [/\.(zip|tar|gz|tgz|bz2|xz|7z|rar|zst)$/i, FileArchive], + [/\.(mp4|mov|webm|mkv|avi)$/i, FilePlay], + [/\.(mp3|wav|ogg|flac|m4a)$/i, FileAudio], + [/\.(py|ts|js|go|rs|sh|sql|java|rb|php|ya?ml|toml|html|css|xml)$/i, FileCode], + [/\.(txt|md|log|pdf|docx?|rtf)$/i, FileText] + ] + function fileIconFor(name: string): IconType { + return FILE_ICONS.find(([re]) => re.test(name))?.[1] ?? FileIcon + } + function nestingLevelOf(key: string): number { const slashes = (key.match(/\//g) ?? []).length return (key.endsWith('/') ? slashes - 1 : slashes) * 2 @@ -1047,41 +1159,50 @@ }) </script> +{#snippet tableLoading()} + <div class="flex items-center gap-2 p-3 text-xs text-tertiary"> + <Loader2 size={14} class="animate-spin" /> Loading table... + </div> +{/snippet} + {#if workspaceSettingsInitialized === false} - {#if fromWorkspaceSettings} - <Alert type="error" title="Connection to remote S3 bucket unsuccessful"> - <div class="flex flex-row gap-x-1 w-full items-center"> - <p class="text-clip grow min-w-0"> Double check the S3 resource fields and try again. </p> - </div> - </Alert> - {:else if s3ResourcePath} - <Alert type="error" title="Could not connect to the object storage of {s3ResourcePath}"> - <div class="flex flex-row gap-x-1 w-full items-center"> - <p class="text-clip grow min-w-0"> - Double check the resource fields and that its object storage is reachable, then try again. - </p> - <Button variant="default" on:click={reloadContent} startIcon={{ icon: RotateCw }} /> - </div> - </Alert> - {:else} - <Alert type="error" title="Workspace not connected to any S3 storage"> - <div class="flex flex-row gap-x-1 w-full items-center"> - <p class="text-clip grow min-w-0"> - The workspace needs to be connected to an S3 storage to use this feature. You can <a - target="_blank" - href="{base}/workspace_settings?tab=windmill_lfs">configure it here</a - >. - </p> - <Button variant="default" on:click={reloadContent} startIcon={{ icon: RotateCw }} /> - </div> - </Alert> - {/if} + <div class="p-4"> + {#if fromWorkspaceSettings} + <Alert type="error" title="Connection to remote S3 bucket unsuccessful"> + <div class="flex flex-row gap-x-1 w-full items-center"> + <p class="text-clip grow min-w-0"> Double check the S3 resource fields and try again. </p> + </div> + </Alert> + {:else if s3ResourcePath} + <Alert type="error" title="Could not connect to the object storage of {s3ResourcePath}"> + <div class="flex flex-row gap-x-1 w-full items-center"> + <p class="text-clip grow min-w-0"> + Double check the resource fields and that its object storage is reachable, then try + again. + </p> + <Button variant="default" on:click={reloadContent} startIcon={{ icon: RotateCw }} /> + </div> + </Alert> + {:else} + <Alert type="error" title="Workspace not connected to any S3 storage"> + <div class="flex flex-row gap-x-1 w-full items-center"> + <p class="text-clip grow min-w-0"> + The workspace needs to be connected to an S3 storage to use this feature. You can <a + target="_blank" + href="/workspace_settings?tab=windmill_lfs">configure it here</a + >. + </p> + <Button variant="default" on:click={reloadContent} startIcon={{ icon: RotateCw }} /> + </div> + </Alert> + {/if} + </div> {:else} {#if fileListUnavailable == true} {#if replaceUnauthorizedWarning} {@render replaceUnauthorizedWarning()} {:else} - <div class="mb-2"> + <div class="p-3 border-b"> <Alert type="info" title="Access to S3 bucket restricted"> <p> You don't have access to the S3 bucket resource and your administrator has restricted @@ -1098,28 +1219,25 @@ </div> {/if} {/if} - <div class="flex flex-row border rounded-md h-full min-h-0 overflow-hidden"> + <Splitpanes class="h-full min-h-0 overflow-hidden"> {#if !fileListUnavailable} - <div class="min-w-[30%] border-r flex flex-col min-h-0"> + <Pane size={28} minSize={15} class="flex flex-col min-h-0"> {#if !rootPath} - <div class="w-full p-1 border-b"> - <input - type="text" - placeholder="Search by path prefix" + <div class="mx-3 mt-3"> + <TextInput bind:value={filter} - class="text-xl" + inputProps={{ placeholder: 'Search by path prefix...' }} /> </div> {/if} {#if displayedFileKeys.length === 0} {#if fileListLoading} - <div class="grow min-h-0 flex justify-center items-center"> - <div class="flex text-secondary text-xs items-center"> - <Loader2 size={12} class="animate-spin mr-1" /> Loading content - </div> + <div class="flex items-center gap-2 text-tertiary p-3"> + <Loader2 class="animate-spin" size={14} /> + <span class="text-xs">Loading...</span> </div> {:else} - <div class="p-4 text-primary text-xs text-center italic"> + <div class="p-3 text-tertiary text-xs"> {#if filter.trim() !== ''} No files starting with "{filter.trim()}" {:else} @@ -1131,19 +1249,19 @@ can remove every match. Without this the only control that could resume the listing would be hidden behind the empty state. --> <div class="flex justify-center pb-4"> - <Button variant="default" size="xs2" on:click={() => loadNextFlatPage()}> + <Button variant="default" unifiedSize="xs" onClick={() => loadNextFlatPage()}> Keep looking </Button> </div> {/if} {/if} {:else} - <div class="grow min-h-0" bind:clientHeight={listDivHeight}> + <div class="grow min-h-0 mt-1.5" bind:clientHeight={listDivHeight}> <VirtualList width="100%" height={listDivHeight} itemCount={displayedFileKeys.length} - itemSize={42} + itemSize={32} > {#snippet header()}{/snippet} {#snippet footer()}{/snippet} @@ -1155,199 +1273,249 @@ {@const load_more_prefix = is_load_more ? item_key.slice(0, -1) : ''} {@const file_info = allFilesByKey[item_key]} - <div - {style} - class={twMerge( - 'hover:bg-surface-hover border-b', - index === displayedFileKeys.length - 1 && 'border-b-0' - )} - > + <div {style}> {#if is_load_more} <!-- Indented like the siblings it belongs to, so it must discount the browsing root the same way entry rows do. --> {@const loadMoreNesting = nestingLevelOf(load_more_prefix + 'x') - 2 * rootPathNestingLevel} {@const loadingMore = folderState[load_more_prefix]?.loading === true} - <!-- svelte-ignore a11y_click_events_have_key_events --> - <!-- svelte-ignore a11y_no_static_element_interactions --> - <div + <button onclick={() => !loadingMore && loadMore(load_more_prefix)} - class={twMerge( - 'flex flex-row h-full text-xs items-center justify-start text-secondary', - loadingMore ? 'cursor-default' : 'cursor-pointer' - )} + disabled={loadingMore} + class="w-full text-xs font-normal flex gap-2 items-center h-8 pr-1 text-secondary hover:bg-surface-hover cursor-pointer disabled:cursor-default disabled:hover:bg-transparent" + style={treeRowIndent(loadMoreNesting)} > - <div - class="flex flex-row w-full gap-2 h-full items-center" - style={`margin-left: ${(2 + loadMoreNesting) * 0.25}rem;`} - > - <!-- Occupies the same slot as the sibling rows' file/folder icon so - the labels line up, and holds its width when the spinner swaps in. --> - <div class="w-4 shrink-0 flex items-center justify-center"> - {#if loadingMore} - <Loader2 size={16} class="animate-spin" /> - {:else} - <ChevronDown size={16} /> - {/if} - </div> - <div class="truncate text-ellipsis w-56">Load more</div> - </div> - </div> + <span class="shrink-0 w-3.5"></span> + {#if loadingMore} + <Loader2 class="shrink-0 animate-spin" size={14} /> + {:else} + <Ellipsis class="shrink-0" size={14} /> + {/if} + <span class="truncate">Load more</span> + </button> {:else if file_info} {@const nestingLevel = file_info.nestingLevel - 2 * rootPathNestingLevel} - <!-- svelte-ignore a11y_click_events_have_key_events --> - <!-- svelte-ignore a11y_no_static_element_interactions --> - <div + {@const isSelected = selectedFileKey?.s3 === file_info.full_key} + {@const isFolder = file_info.type === 'folder'} + {@const RowIcon = isFolder + ? file_info.collapsed + ? FolderClosed + : FolderOpen + : fileIconFor(file_info.display_name)} + <button onclick={() => selectItem(index)} + title={file_info.full_key.slice(rootPath.length)} class={twMerge( - 'flex flex-row h-full font-semibold text-xs items-center justify-start', - selectedFileKey !== undefined && selectedFileKey.s3 === file_info.full_key - ? 'bg-surface-hover' - : '' + 'w-full text-xs font-normal text-primary flex gap-2 items-center h-8 pr-1 cursor-pointer', + isSelected ? 'bg-surface-secondary' : 'hover:bg-surface-hover' )} + style={treeRowIndent(nestingLevel)} > - <div - class={`flex flex-row w-full gap-2 h-full items-center`} - style={`margin-left: ${(2 + nestingLevel) * 0.25}rem;`} - > - {#if file_info.type === 'folder'} - {#if folderState[file_info.full_key]?.loading} - <Loader2 size={16} class="animate-spin" /> - {:else if file_info.collapsed}<FolderClosed size={16} />{:else}<FolderOpen - size={16} - />{/if} - <div class="truncate text-ellipsis w-56"> - <!-- An object-store key may contain an empty segment, so `a//` is a real - folder whose name is ''. Label it rather than rendering a blank row. --> - {#if file_info.display_name === ''} - <span class="italic text-secondary">(empty name)</span> - {:else}{file_info.display_name}{/if} - {#if !lazyMode} - ({file_info.count}{count % 1000 === 0 && - lastKeyFolders[file_info.nestingLevel / 2] === file_info.display_name - ? '+' - : ''} item{file_info.count === 1 ? '' : 's'}) - {/if} - </div> + {#if isFolder} + {#if folderState[file_info.full_key]?.loading} + <Loader2 class="shrink-0 text-secondary animate-spin" size={14} /> {:else} - <FileIcon size={16} /> - <div class="truncate text-ellipsis w-56"> - {file_info.display_name} - </div> + <ChevronDown + class={twMerge( + 'shrink-0 text-secondary transition-transform', + file_info.collapsed && '-rotate-90' + )} + size={14} + /> {/if} - </div> - </div> + {:else} + <span class="shrink-0 w-3.5"></span> + {/if} + <RowIcon class="shrink-0" size={14} /> + <span class="truncate text-left"> + <!-- An object-store key may contain an empty segment, so `a//` is a real + folder whose name is ''. Label it rather than rendering a blank row. --> + {#if file_info.display_name === ''} + <span class="italic text-secondary">(empty name)</span> + {:else}{file_info.display_name}{/if} + </span> + <span class="grow"></span> + {#if isFolder && !lazyMode} + <span + class="shrink-0 text-2xs text-tertiary mr-2" + title="Items inside this folder" + > + {file_info.count}{count % 1000 === 0 && + lastKeyFolders[file_info.nestingLevel / 2] === file_info.display_name + ? '+' + : ''} + </span> + {/if} + </button> {/if} </div> {/snippet} </VirtualList> </div> <div - class="flex flex-col gap-2 text-2xs justify-center items-center text-secondary w-full border-t py-1" + class="flex items-center justify-between gap-2 min-h-8 px-3 py-1 border-t text-2xs text-tertiary" > {#if fileListLoading === true} - <div class="flex text-secondary mt-1 text-xs justify-center items-center w-full"> - <Loader2 size={12} class="animate-spin mr-1" /> Loading content + <div class="flex items-center gap-1.5"> + <Loader2 size={12} class="animate-spin" /> Loading... </div> {:else if lazyMode} <!-- Per-level listing: totals below the tree would be a count of what happens to be expanded, and each folder carries its own Load more row. --> <div>{displayedCount} item{displayedCount === 1 ? '' : 's'} shown</div> {:else} - <div> + <div class="min-w-0"> {displayedCount}{flatHasMore ? '+' : ''} {displayedCount !== count ? 'filtered ' : ''}items (including inside folders) </div> {#if flatHasMore} - <Button variant="default" size="xs2" on:click={() => loadNextFlatPage()}> + <Button variant="subtle" unifiedSize="xs" onClick={() => loadNextFlatPage()}> Load more </Button> {/if} {/if} </div> {/if} - </div> + </Pane> {/if} - <div class="flex flex-col h-full w-full min-h-0 overflow-hidden"> - {#if fileMetadata === undefined} - <div class="p-4"> - {#if fileInfoLoading} - <Section label="Loading..." /> - {:else if fileListUnavailable} - <Section label="No file to preview" /> - {:else} - <Section label="Select a file to preview" /> - {/if} - </div> - {:else} - <div class="px-3 py-2 flex flex-col gap-2"> - <div class="flex flex-row items-center justify-between gap-2"> - <h2 class="text-emphasis text-sm font-semibold break-all min-w-0"> - {((p) => (p.startsWith(rootPath) ? p.slice(rootPath.length) : p))( - fileMetadata.fileKey - )} - </h2> - {#if filePreview !== undefined && (!hideS3SpecificDetails || !readOnlyMode || allowDelete)} - <div class="flex gap-2 shrink-0"> - {#if !hideS3SpecificDetails} - {@const downloadApiPath = `/w/${ws}/job_helpers/download_s3_file?file_key=${encodeURIComponent(fileMetadata?.fileKey ?? '')}${storage ? `&storage=${storage}` : ''}${s3ResourcePath ? `&s3_resource_path=${encodeURIComponent(s3ResourcePath)}` : ''}`} - {@const downloadName = - fileMetadata?.fileKey.split('/').pop() ?? 'unnamed_download.file'} - {#if shouldDownloadViaClient()} - <Button - title="Download file from S3" - variant="default" - on:click={() => downloadViaClient(downloadApiPath, downloadName)} - startIcon={{ icon: Download }} - iconOnly={true} - /> - {:else} - <Button - title="Download file from S3" - variant="default" - href={`${base}/api${downloadApiPath}`} - download={downloadName} - startIcon={{ icon: Download }} - iconOnly={true} - /> - {/if} - {/if} - {#if !readOnlyMode} - <Button - title="Move file" - variant="default" - on:click={() => { - moveDestKey = fileMetadata?.fileKey ?? '' - moveModalOpen = true - }} - startIcon={{ icon: MoveRight }} - iconOnly={true} - /> - {/if} - {#if !readOnlyMode || allowDelete} - <Button - title="Delete file" - variant="default" - on:click={() => { - deletionModalOpen = true - }} - startIcon={{ icon: Trash }} - iconOnly={true} - /> - {/if} + <Pane class="flex flex-col min-h-0 overflow-hidden"> + <div + class="flex items-center gap-3 px-3 py-3 min-h-[3.75rem] shrink-0 border-b bg-surface-secondary" + > + {#if fileMetadata === undefined} + <div class="flex items-center gap-2 text-xs text-tertiary"> + {#if fileInfoLoading} + <Loader2 size={14} class="animate-spin" /> Loading... + {:else if fileListUnavailable} + No file to preview + {:else} + Select a file to preview + {/if} + </div> + {:else} + {@const displayedKey = fileMetadata.fileKey.startsWith(rootPath) + ? fileMetadata.fileKey.slice(rootPath.length) + : fileMetadata.fileKey} + {@const slash = displayedKey.lastIndexOf('/')} + {@const fileName = displayedKey.slice(slash + 1)} + {@const FileKindIcon = fileIconFor(fileName)} + {@const details = [ + fileMetadata.mimeType, + fileMetadata.sizeStr, + fileMetadata.lastModified && `Modified ${fileMetadata.lastModified}` + ].filter(Boolean)} + <div + class="shrink-0 flex items-center justify-center w-9 h-9 rounded-md border bg-surface text-secondary" + > + <FileKindIcon size={18} /> + </div> + <div class="flex flex-col gap-0.5 min-w-0 grow"> + <div class="flex items-center gap-1 min-w-0"> + <span class="truncate text-sm font-semibold text-emphasis" title={displayedKey}> + {#if slash >= 0}<span class="font-normal text-tertiary" + >{displayedKey.slice(0, slash + 1)}</span + >{/if}{fileName} + </span> + <CopyButton value={displayedKey} title="Copy file key" class="shrink-0" /> + </div> + {#if !hideS3SpecificDetails && details.length > 0} + <div class="flex flex-wrap items-center gap-x-1.5 text-xs text-secondary"> + {#each details as detail, i} + {#if i > 0}<span class="text-tertiary">·</span>{/if} + <span>{detail}</span> + {/each} </div> {/if} </div> - {#if !hideS3SpecificDetails} - <TableSimple - headers={['Last modified', 'Size', 'Type']} - data={[fileMetadata]} - keys={['lastModified', 'sizeStr', 'mimeType']} - /> + {#if tableSource} + <ToggleButtonGroup + noWFull + selected={viewMode} + onSelected={(v) => (viewMode = v)} + class="shrink-0" + > + {#snippet children({ item })} + <ToggleButton value="table" label="Table" icon={Table2} small {item} /> + <ToggleButton value="text" label="Text" icon={FileText} small {item} /> + {/snippet} + </ToggleButtonGroup> {/if} - </div> - {/if} + {#if filePreview?.contentType === 'Csv'} + <div class="flex items-center gap-4 shrink-0 text-xs text-secondary"> + <div class="flex items-center gap-2"> + <span>Separator</span> + <Select + size="sm" + class="w-16" + RightIcon={ChevronDown} + items={CSV_SEPARATORS} + bind:value={csvSeparatorChar} + placeholder={CSV_SEPARATORS.find((s) => s.value === detectedCsvSeparator) + ?.label ?? 'Auto'} + /> + </div> + <Toggle size="xs" bind:checked={csvHasHeader} options={{ right: 'Header row' }} /> + </div> + <div class="w-px h-6 border-l shrink-0"></div> + {/if} + {#if filePreview !== undefined && (!hideS3SpecificDetails || !readOnlyMode || allowDelete)} + <div class="flex gap-1 shrink-0"> + {#if !hideS3SpecificDetails} + {@const downloadApiPath = `/w/${ws}/job_helpers/download_s3_file?file_key=${encodeURIComponent(fileMetadata.fileKey)}${storage ? `&storage=${storage}` : ''}${s3ResourcePath ? `&s3_resource_path=${encodeURIComponent(s3ResourcePath)}` : ''}`} + {@const downloadName = fileName || 'unnamed_download.file'} + {#if shouldDownloadViaClient()} + <Button + title="Download" + variant="subtle" + unifiedSize="md" + onClick={() => downloadViaClient(downloadApiPath, downloadName)} + startIcon={{ icon: Download }} + iconOnly + /> + {:else} + <Button + title="Download" + variant="subtle" + unifiedSize="md" + href={`/api${downloadApiPath}`} + download={downloadName} + startIcon={{ icon: Download }} + iconOnly + /> + {/if} + {/if} + {#if !readOnlyMode} + <Button + title="Move" + variant="subtle" + unifiedSize="md" + onClick={() => { + moveDestKey = fileMetadata?.fileKey ?? '' + moveModalOpen = true + }} + startIcon={{ icon: MoveRight }} + iconOnly + /> + {/if} + {#if !readOnlyMode || allowDelete} + <Button + title="Delete" + variant="subtle" + unifiedSize="md" + destructive + onClick={() => { + deletionModalOpen = true + }} + startIcon={{ icon: Trash }} + iconOnly + /> + {/if} + </div> + {/if} + {/if} + </div> <!-- Visual preview extracted to a standalone S3FilePreview component so the asset detail pane (and other surfaces) can render the @@ -1356,17 +1524,40 @@ above for the download/move toolbar; S3FilePreview does an independent load — fine on this non-hot path, and avoids plumbing pre-loaded state through component boundaries. --> - <S3FilePreview - fileKey={fileMetadata?.fileKey} - {storage} - {s3ResourcePath} - workspace={ws} - {loadFilePreviewRequest} - {loadFileMetadataRequest} - class="h-full" - /> - </div> - </div> + {#if showTable} + <div class="flex-1 min-h-0 relative"> + {#if currentTable?.ops} + <!-- Lazy: the (logged) layout mounts this picker and DBTable reaches monaco. --> + {#await import('./DBTable.svelte')} + {@render tableLoading()} + {:then DBTable} + {#key currentTable.ops} + <DBTable.default dbTableOps={currentTable.ops} /> + {/key} + {/await} + {:else if tableOps.error} + <div class="p-3 text-xs text-red-600 dark:text-red-400 break-words"> + Could not read this file as a table: {tableOps.error.message} + </div> + {:else} + {@render tableLoading()} + {/if} + </div> + {:else} + <S3FilePreview + fileKey={fileMetadata?.fileKey} + {storage} + {s3ResourcePath} + workspace={ws} + {loadFilePreviewRequest} + {loadFileMetadataRequest} + class="flex-1 min-h-0" + csvOptions={{ separator: csvSeparatorChar, hasHeader: csvHasHeader }} + bodyClass="bg-transparent px-3" + /> + {/if} + </Pane> + </Splitpanes> {/if} <ConfirmationModal diff --git a/frontend/src/lib/components/S3FilePreview.svelte b/frontend/src/lib/components/S3FilePreview.svelte index 411592b936..4635d4f6c7 100644 --- a/frontend/src/lib/components/S3FilePreview.svelte +++ b/frontend/src/lib/components/S3FilePreview.svelte @@ -5,8 +5,10 @@ // renderings without dragging in the whole picker UI. // // The component owns its own metadata + preview loads — callers only - // need to hand it a `fileKey`. CSV separator/header are local state so - // the user can re-preview the same file with different parsing flags. + // need to hand it a `fileKey`. CSV separator/header are local state (unless + // the caller passes `csvOptions`) so the user can re-preview the same file + // with different parsing flags. + import { untrack } from 'svelte' import { FileX2, Loader2 } from 'lucide-svelte' import { HelpersService, @@ -46,6 +48,11 @@ // metadata out themselves (the picker already has its own). showMetadata?: boolean class?: string + /** CSV parsing options owned by the caller, which then renders its own controls: + * the preview hides its own and reloads when these change. */ + csvOptions?: { separator: string | undefined; hasHeader: boolean } + /** Merged onto the preview body, below the metadata strip. */ + bodyClass?: string // Bump this to force a re-fetch (metadata + preview). Used by the // asset detail pane after an upstream producer run completes — // without it, the "Asset not yet materialized" empty state stays @@ -62,6 +69,8 @@ loadFileMetadataRequest = HelpersService.loadFileMetadata, showMetadata = false, class: className = '', + bodyClass = '', + csvOptions = undefined, refreshKey }: Props = $props() @@ -179,8 +188,8 @@ fileKey: key, fileSizeInBytes: size, fileMimeType: mimeType, - csvSeparator: csvSeparatorChar, - csvHasHeader: csvHasHeader, + csvSeparator: csvOptions ? csvOptions.separator : csvSeparatorChar, + csvHasHeader: csvOptions?.hasHeader ?? csvHasHeader, readBytesFrom: 0, readBytesLength: 128 * 1024, storage, @@ -221,6 +230,16 @@ void reloadPreview(fileMetadata.fileKey, fileMetadata.size, fileMetadata.mimeType) } } + + // Skips the first run: the file load already fetches the preview with these options. + let lastCsvOptionsKey: string | undefined + $effect(() => { + const key = csvOptions ? `${csvOptions.separator}|${csvOptions.hasHeader}` : undefined + if (lastCsvOptionsKey !== undefined && key !== lastCsvOptionsKey) { + untrack(onCsvControlsChanged) + } + lastCsvOptionsKey = key + }) </script> <div class={twMerge('flex flex-col h-full w-full overflow-auto text-xs', className)}> @@ -231,7 +250,7 @@ {#if fileMetadata.lastModified}<span>{fileMetadata.lastModified}</span>{/if} </div> {/if} - <div class="flex-1 min-h-0 overflow-auto p-4 bg-surface-secondary"> + <div class={twMerge('flex-1 min-h-0 overflow-auto p-4 bg-surface-secondary', bodyClass)}> {#if !fileKey} <div class="text-tertiary text-xs">No file selected.</div> {:else if fileInfoLoading && !fileMetadata && !notFound && !loadError} @@ -291,32 +310,36 @@ <Loader2 size={12} class="animate-spin mr-1" /> File preview loading </div> {:else if fileMetadata !== undefined && filePreview !== undefined} - <div class="flex items-center text-primary mb-4"> - {#if filePreview.contentType === 'Unknown'} + {#if filePreview.contentType === 'Unknown'} + <div class="flex items-center text-primary mb-4"> Type of file not supported for preview. - {:else if filePreview.contentType === 'Csv'} - Previewing a {filePreview.contentType?.toLowerCase()} file. Separator character: - <div class="inline-flex w-12 ml-2 mr-2"> - <select class="h-8" bind:value={csvSeparatorChar} onchange={onCsvControlsChanged}> - <option value=",">,</option> - <option value=";">;</option> - <option value="\t">\t</option> - <option value="|">|</option> - </select> - </div> - Header row: - <div class="inline-flex item-center w-4 ml-2 mr-2"> - <input - type="checkbox" - class="h-5" - bind:checked={csvHasHeader} - onchange={onCsvControlsChanged} - /> - </div> - {:else} - Previewing a {filePreview.contentType?.toLowerCase()} file. - {/if} - </div> + </div> + {:else if !csvOptions} + <div class="flex items-center text-primary mb-4"> + {#if filePreview.contentType === 'Csv'} + Previewing a {filePreview.contentType?.toLowerCase()} file. Separator character: + <div class="inline-flex w-12 ml-2 mr-2"> + <select class="h-8" bind:value={csvSeparatorChar} onchange={onCsvControlsChanged}> + <option value=",">,</option> + <option value=";">;</option> + <option value="\t">\t</option> + <option value="|">|</option> + </select> + </div> + Header row: + <div class="inline-flex item-center w-4 ml-2 mr-2"> + <input + type="checkbox" + class="h-5" + bind:checked={csvHasHeader} + onchange={onCsvControlsChanged} + /> + </div> + {:else} + Previewing a {filePreview.contentType?.toLowerCase()} file. + {/if} + </div> + {/if} <pre class="grow whitespace-no-wrap break-words" >{#if !emptyString(filePreview.contentPreview)}{filePreview.contentPreview}{:else if filePreview.contentType !== undefined}Preview impossible.{/if}</pre > diff --git a/frontend/src/lib/components/SchemaForm.svelte b/frontend/src/lib/components/SchemaForm.svelte index d05c3cce72..d761101d76 100644 --- a/frontend/src/lib/components/SchemaForm.svelte +++ b/frontend/src/lib/components/SchemaForm.svelte @@ -300,7 +300,14 @@ <!-- {JSON.stringify(schema)} --> <div class="w-full {className} {flexWrap ? 'flex flex-row flex-wrap gap-x-6 ' : ''} {nestedClasses}" - use:dragHandleZone={dndConfig ?? { items: [], dragDisabled: true }} + use:dragHandleZone={dndConfig ?? { + items: [], + dragDisabled: true, + // A drag-disabled zone otherwise sets aria-disabled="true" on itself, which screen readers + // and Playwright apply to every field inside it. + autoAriaDisabled: true, + zoneTabIndex: -1 + }} onfinalize={bubble('finalize')} onconsider={bubble('consider')} > diff --git a/frontend/src/lib/components/ScriptBuilder.svelte b/frontend/src/lib/components/ScriptBuilder.svelte index ad869ed492..247382d6d4 100644 --- a/frontend/src/lib/components/ScriptBuilder.svelte +++ b/frontend/src/lib/components/ScriptBuilder.svelte @@ -72,7 +72,6 @@ Tag, X } from 'lucide-svelte' - import { base } from '$lib/base' import { useLocalStorageValue } from '$lib/svelte5Utils.svelte' import { parsePipelineAnnotations } from './assets/AssetGraph/parsePipelineAnnotations' import DropdownV2 from './DropdownV2.svelte' @@ -97,7 +96,7 @@ import EditorHeader from './EditorHeader.svelte' import PageHeaderContent from '$lib/components/PageHeaderContent.svelte' import PathEditPopover from '$lib/components/PathEditPopover.svelte' - import { pageHeader, PHONE_BAR } from '$lib/components/pageHeaderRegistry.svelte' + import { pageHeader } from '$lib/components/pageHeaderRegistry.svelte' import ScriptSettingsBadges from './ScriptSettingsBadges.svelte' import Badge from './common/badge/Badge.svelte' import Modal from './common/modal/Modal.svelte' @@ -128,8 +127,10 @@ import WacExportDrawer from './scripts/WacExportDrawer.svelte' import { UserDraft } from '$lib/userDraft.svelte' import { UserDraftDbSyncer } from '$lib/userDraftDbSyncer.svelte' - import { useTriggerLock } from '$lib/operatorWriteRights' + import { useEditRights, useTriggerLock } from '$lib/operatorWriteRights' + import { previewOnBehalfOf } from '$lib/utils/previewOnBehalfOf' const triggerLock = useTriggerLock() + const editRights = useEditRights() let { script = $bindable(), @@ -206,19 +207,14 @@ let pathSnapshot = $state<string | undefined>(undefined) let topbarWidth = $state(0) - // In the page header the buttons share the row with the breadcrumb, so they collapse sooner: - // the trail and the summary take ~560px before either truncates, and the full button group is - // ~515px — about 1100px between them, plus slack for a longer path than most. - const compactBelow = $derived(ownsPageHeader ? 1200 : 900) - const compactTopbar = $derived.by(() => { - const w = ownsPageHeader ? pageHeader.barWidth : topbarWidth - return w > 0 && w < compactBelow - }) - // A phone's bar holds the trail and one button. Diff and Settings join the menu that compact - // already shows, and Deploy stays out: it is what this page is for. - const phoneTopbar = $derived( - ownsPageHeader && pageHeader.barWidth > 0 && pageHeader.barWidth < PHONE_BAR + // In the page header the bar folds the buttons (`actionFolds` below), once its breadcrumb has + // given all it can; anywhere else this editor's own top bar is theirs alone. + const compactTopbar = $derived( + ownsPageHeader ? pageHeader.actionFold >= 1 : topbarWidth > 0 && topbarWidth < 900 ) + // The second fold holds the trail and one button. Diff and Settings join the menu that compact + // already shows, and Deploy stays out: it is what this page is for. + const phoneTopbar = $derived(ownsPageHeader && pageHeader.actionFold >= 2) // The workspace this editor operates on: deploy, save-draft, trigger loading // and the AutosaveIndicator all target it. Falls back to the full-page @@ -596,6 +592,7 @@ | 'powershell' | 'bunnative' | 'claudesandbox' + | 'pisandbox' | 'wac_python' | 'wac_typescript' | 'ci_test_bun' @@ -1384,7 +1381,7 @@ onCanceled={() => (perpetualRunsToConfirm = undefined)} /> -{#if !actingUser?.operator} +{#if editRights.roleCanAuthor('script')} <Drawer placement="right" bind:open={metadataOpen} @@ -1543,10 +1540,12 @@ (lang == script.language && template != 'bunnative' && template != 'docker' && - template != 'claudesandbox') || + template != 'claudesandbox' && + template != 'pisandbox') || (template == 'bunnative' && lang == 'bunnative') || (template == 'docker' && lang == 'docker') || - (template == 'claudesandbox' && lang == 'bun')} + ((template == 'claudesandbox' || template == 'pisandbox') && + lang == 'bun')} <Popover disablePopup={!enterpriseLangs.includes(lang) || !!$enterpriseLicense} > @@ -1597,6 +1596,21 @@ > Claude Sandbox </Button> + <Button + unifiedSize="xs" + variant="default" + startIcon={{ + icon: LanguageIcon, + props: { lang: 'pisandbox', width: 16, height: 16 } + } as ButtonType.Icon} + onclick={() => { + template = 'pisandbox' + script.language = 'bun' + initContent('bun', script.kind, template) + }} + > + Pi Sandbox + </Button> <span title="Workflow-as-Code"> <Button size="xs2" @@ -2298,6 +2312,7 @@ // route binds here and drops the `{#if}` around this editor in one flush, which // invalidates the band before this component is torn down. path: pathSnapshot ?? script?.path, + summary: script?.summary, summaryContent: scriptSummary, // Gated like the summary's own editor: a host that allows neither field keeps the // band's segment, which copies the path. @@ -2308,6 +2323,7 @@ }} afterName={scriptMarks} actions={scriptHeaderActions} + actionFolds={2} separator="none" /> {:else} @@ -2586,7 +2602,7 @@ -- materialize </code> to materialize its result, or build it in the - <a href="{base}/pipeline" class="text-blue-500 hover:underline">pipeline editor</a>. + <a href="/pipeline" class="text-blue-500 hover:underline">pipeline editor</a>. <a href="https://www.windmill.dev/docs/pipelines" target="_blank" @@ -2630,6 +2646,11 @@ {:else} <ScriptEditor {disableAi} + previewOnBehalfOf={previewOnBehalfOf( + actingUser, + script.on_behalf_of, + script.on_behalf_of_email + )} workspaceOverride={opWorkspace} sessionOpen={userDraftPath ? { diff --git a/frontend/src/lib/components/ScriptEditor.svelte b/frontend/src/lib/components/ScriptEditor.svelte index 1cabcf8265..880ffbaad6 100644 --- a/frontend/src/lib/components/ScriptEditor.svelte +++ b/frontend/src/lib/components/ScriptEditor.svelte @@ -87,7 +87,6 @@ import CaptureButton from './triggers/CaptureButton.svelte' import { setContext } from 'svelte' import HideButton from './apps/editor/settingsPanel/HideButton.svelte' - import { base } from '$lib/base' import DispatchEventsButton from '$lib/components/runs/DispatchEventsButton.svelte' import { SUPPORTED_CHAT_SCRIPT_LANGUAGES } from './copilot/chat/script/core' import { getStringError } from './copilot/chat/utils' @@ -140,6 +139,8 @@ code: string path: string | undefined lang: Preview['language'] + /** Identity the test runs as instead of the user (see `previewOnBehalfOf`). */ + previewOnBehalfOf?: string kind?: string | undefined autoKind?: string | undefined template?: @@ -150,6 +151,7 @@ | 'powershell' | 'bunnative' | 'claudesandbox' + | 'pisandbox' | 'wac_python' | 'wac_typescript' | 'ci_test_bun' @@ -240,6 +242,7 @@ code = $bindable(), path, lang, + previewOnBehalfOf, kind = undefined, autoKind = undefined, template = 'script', @@ -994,7 +997,8 @@ // A `__mod` helper is tested alone, so its siblings are left out. onModule ? undefined : modules, undefined, - timeout + timeout, + { onBehalfOf: previewOnBehalfOf } ) if (job) { onTestJob?.({ jobId: job }) @@ -2100,43 +2104,15 @@ </div> {/if} {#if customUi?.previewPanel?.hideArgs} - <!-- Compact preview layout used by the pipeline editor: - no args column (the script is known to take no - inputs), LogPanel takes the full width, with a - small Test/Cancel button at the top-left of the - preview band. The earlier `-translate-y-1/2` - "float onto the editor" version was clipped in - Firefox (transform + overflow: visible interaction - on the parent splitpane Pane), so the button is - now positioned inside the panel — `top-1` keeps - it visually pinned to the top edge without - relying on cross-browser overflow behaviour. --> - <div class="relative h-full pt-9 flex flex-col"> - {#if testJob?.id && testJob.type === 'CompletedJob' && opWs} - <!-- Right-side affordances when we're displaying a *completed* - job (either the user just ran a test, or the on-mount - last-run loader populated the panel). The job-id link - opens the full run page in a new tab; the dispatch - button mounts a popover that shows what downstream - jobs this run triggered (rendered only when the run - actually dispatched anything). --> - <div class="absolute top-1 right-2 z-10 flex items-center gap-2"> - <a - class="text-3xs text-blue-600 hover:underline font-mono" - href={`${base}/run/${testJob.id}?workspace=${opWs}`} - target="_blank" - rel="noopener noreferrer" - title="Open this run" - > - {testJob.id.slice(0, 8)}… ↗ - </a> - <DispatchEventsButton - workspace={testJob.workspace_id ?? opWs} - jobId={testJob.id} - /> - </div> - {/if} - <div class="absolute top-1 left-2 z-10"> + <!-- Compact preview layout used by the pipeline editor: no args + column (most pipeline scripts take no inputs) and a full-width + LogPanel. The controls sit in normal flow rather than floating + onto the editor band, which Firefox clipped (transform + + overflow: visible on the parent splitpane Pane). --> + <div class="h-full flex flex-col"> + <!-- Test sits at the top right, the last run's link under it. --> + <div class="shrink-0 flex flex-col items-end gap-1 px-2 pt-2 pb-1"> + <div> {#if testIsLoading} {@render cancelTestButton('sm', 'shadow-md')} {:else if (customUi?.previewPanel?.downstreamSubscribers ?? 0) > 0 || customUi?.previewPanel?.onBoundedRun} @@ -2270,6 +2246,31 @@ {@render runTestButton('sm', 'shadow-md')} {/if} </div> + {#if testJob?.id && testJob.type === 'CompletedJob' && opWs} + <!-- Right-side affordances when we're displaying a *completed* + job (either the user just ran a test, or the on-mount + last-run loader populated the panel). The job-id link + opens the full run page in a new tab; the dispatch + button mounts a popover that shows what downstream + jobs this run triggered (rendered only when the run + actually dispatched anything). --> + <div class="flex items-center gap-2"> + <a + class="text-3xs text-blue-600 hover:underline font-mono" + href={`/run/${testJob.id}?workspace=${opWs}`} + target="_blank" + rel="noopener noreferrer" + title="Open this run" + > + {testJob.id.slice(0, 8)}… ↗ + </a> + <DispatchEventsButton + workspace={testJob.workspace_id ?? opWs} + jobId={testJob.id} + /> + </div> + {/if} + </div> {#if customUi?.previewPanel?.argsAboveLogs && schema?.properties && Object.keys(schema.properties).length > 0} <div class="shrink-0 overflow-auto max-h-[45%] border-b border-gray-200 dark:border-gray-700 px-4 py-3" @@ -2743,7 +2744,7 @@ {#snippet popoverOverride()} <div class="text-sm"> Enable Windmill AI in the <a - href="{base}/workspace_settings?tab=ai" + href="/workspace_settings?tab=ai" target="_blank" class="inline-flex flex-row items-center gap-1" > diff --git a/frontend/src/lib/components/ScriptPicker.svelte b/frontend/src/lib/components/ScriptPicker.svelte index 781cb5155e..97ac81713d 100644 --- a/frontend/src/lib/components/ScriptPicker.svelte +++ b/frontend/src/lib/components/ScriptPicker.svelte @@ -1,7 +1,6 @@ <script lang="ts"> import { ScriptService, FlowService, type Script, AppService } from '$lib/gen' - import { base } from '$lib/base' import { createEventDispatcher, untrack } from 'svelte' import Select from './select/Select.svelte' @@ -198,7 +197,7 @@ target="_blank" variant="default" size="xs" - href="{base}/flows/edit/{scriptPath}{wsParam}">Edit</Button + href="/flows/edit/{scriptPath}{wsParam}">Edit</Button > {/if} {#if allowView} @@ -221,7 +220,7 @@ target="_blank" variant="default" size="xs" - href="{base}/apps/edit/{scriptPath}{wsParam}" + href="/apps/edit/{scriptPath}{wsParam}" > Edit </Button> @@ -232,7 +231,7 @@ size="xs" target="_blank" startIcon={{ icon: Code }} - href="{base}/apps/get/{scriptPath}{wsParam}" + href="/apps/get/{scriptPath}{wsParam}" > View </Button> @@ -246,7 +245,7 @@ target="_blank" variant="default" size="xs" - href="{base}/scripts/edit/{scriptPath}{wsParam}" + href="/scripts/edit/{scriptPath}{wsParam}" > Edit </Button> diff --git a/frontend/src/lib/components/SummaryPathDisplay.svelte b/frontend/src/lib/components/SummaryPathDisplay.svelte index a2487e1577..93a0a744a6 100644 --- a/frontend/src/lib/components/SummaryPathDisplay.svelte +++ b/frontend/src/lib/components/SummaryPathDisplay.svelte @@ -1,7 +1,7 @@ <script lang="ts"> import type { Snippet } from 'svelte' import { emptyString, isOwner } from '$lib/utils' - import { Alert, Button } from '$lib/components/common' + import { Alert, Button, CopyButton } from '$lib/components/common' import Popover from '$lib/components/meltComponents/Popover.svelte' import TextInput from '$lib/components/text_input/TextInput.svelte' import Path from '$lib/components/Path.svelte' @@ -31,6 +31,13 @@ /** What is being renamed. An agent is a resource, so the path field is scoped to one and * the write goes through the agent branch of the rename manager. */ kind?: 'flow' | 'script' | 'agent' + /** Saves instead of the API, for an item that exists only locally (a draft). + * Returns an error message to keep the popover open. */ + saveOverride?: (next: { + path: string + summary: string + labels: string[] | undefined + }) => string | undefined /** Header variant: no path line (the host shows it) and a lighter summary. */ compact?: boolean /** Rendered inside the trigger in place of the summary, for a host that hangs a second copy @@ -51,6 +58,7 @@ editable = false, onSaved, kind = 'flow', + saveOverride = undefined, compact = false, label, triggerClass = 'block min-w-0 max-w-full px-1 py-0.5 rounded text-left cursor-pointer hover:bg-surface-hover transition-colors', @@ -67,7 +75,9 @@ let popoverOpen = $state(false) // Resolved before the popover opens, not on opening it: the path field only exists for an owner, // and `openFocus` looks for it in the same flush the popover renders in. - const own = $derived(isOwner(path ?? '', actingUser, $operatingWorkspace)) + const own = $derived( + saveOverride !== undefined || isOwner(path ?? '', actingUser, $operatingWorkspace) + ) let onBehalfOfEmail = $state<string | undefined>(undefined) let summaryInput: ReturnType<typeof TextInput> | undefined = $state() let labelsDirty = $state(false) @@ -101,6 +111,17 @@ async function save(close: () => void) { const initialPath = path ?? '' const newPath = own ? editPath : initialPath + if (saveOverride) { + const error = saveOverride({ path: newPath, summary: editSummary, labels }) + if (error) { + sendUserToast(error, true) + return + } + labelsDirty = false + close() + onSaved?.(newPath) + return + } try { await updateItemPathAndSummary({ @@ -305,14 +326,62 @@ <!-- Nothing to open, but the host still drew this into a slot of its own: give back what it handed over rather than this component's own block, which belongs in a row it owns. --> {@render label()} +{:else if compact} + <!-- Nothing to edit, but the band truncates the summary and, on a short bar, drops the path: + the same click shows both whole, to read and to copy. --> + <Popover + class={triggerClass} + placement="bottom-start" + contentClasses="p-4" + triggerAttrs={{ + title: emptyString(summary) ? path : summary, + 'aria-label': 'Show summary and path' + }} + usePointerDownOutside + excludeSelectors=".drawer" + > + {#snippet trigger()} + <span class="block truncate text-xs font-medium text-emphasis"> + {emptyString(summary) ? (path ?? '') : summary} + </span> + {/snippet} + {#snippet content()} + <div class="flex flex-col gap-4 w-[420px] max-w-[calc(100vw-2rem)]"> + <div> + <div class="pb-1 text-xs font-semibold text-emphasis">Summary</div> + {#if emptyString(summary)} + <p class="text-xs text-tertiary italic">No summary</p> + {:else} + <p class="text-xs text-primary break-words">{summary}</p> + {/if} + </div> + <div> + <div class="pb-1 text-xs font-semibold text-emphasis">Path</div> + <div class="flex items-center gap-1"> + <span class="min-w-0 text-xs font-mono text-secondary break-all">{path}</span> + <CopyButton value={path ?? ''} title="Copy path" /> + </div> + </div> + {#if labels?.length || inheritedLabels?.length} + <div class="flex flex-wrap items-center gap-0.5"> + {#each labels ?? [] as labelText} + <Badge color="blue" verySmall class="px-1" title="Label: {labelText}" + >{labelText}</Badge + > + {/each} + <InheritedLabels labels={inheritedLabels} /> + </div> + {/if} + <p class="text-2xs text-tertiary">You can't edit this {kind}'s summary or path.</p> + </div> + {/snippet} + </Popover> {:else} - <div class="min-w-0 truncate flex items-center {compact ? '' : 'flex-col px-2'}"> - {#if !emptyString(summary) && !compact} + <div class="min-w-0 truncate flex items-center flex-col px-2"> + {#if !emptyString(summary)} <span class="text-[10px] leading-tight text-tertiary font-mono truncate">{path}</span> {/if} - <span - class="{compact ? 'text-xs font-medium' : 'text-sm font-semibold'} text-emphasis truncate" - > + <span class="text-sm font-semibold text-emphasis truncate"> {emptyString(summary) ? (path ?? '') : summary} </span> </div> diff --git a/frontend/src/lib/components/SuperadminSettingsInner.svelte b/frontend/src/lib/components/SuperadminSettingsInner.svelte index 0fd7991597..eb5559a2aa 100644 --- a/frontend/src/lib/components/SuperadminSettingsInner.svelte +++ b/frontend/src/lib/components/SuperadminSettingsInner.svelte @@ -8,7 +8,6 @@ import InviteGlobalUser from '$lib/components/InviteGlobalUser.svelte' import { Button } from '$lib/components/common' import { sendUserToast } from '$lib/toast' - import { base } from '$lib/base' import SearchItems from './SearchItems.svelte' import { page } from '$app/state' import { replaceState } from '$app/navigation' @@ -18,7 +17,7 @@ import { truncate } from '$lib/utils' import ToggleButtonGroup from './common/toggleButton-v2/ToggleButtonGroup.svelte' import ToggleButton from './common/toggleButton-v2/ToggleButton.svelte' - import { userStore, workspaceStore } from '$lib/stores' + import { enterpriseLicense, userStore, workspaceStore } from '$lib/stores' import { ArrowRightLeft, Ban, @@ -47,6 +46,8 @@ tabToAuthSubTab, categoryToTabMap, buildSearchableSettingItems, + listedNavigationGroups, + usesExternalOidcSigner, type SearchableSettingItem } from './instanceSettings' import TextInput from './text_input/TextInput.svelte' @@ -228,7 +229,14 @@ return instanceSettings?.buildFullDiff() ?? { original: '', modified: '' } } // --- Settings search --- - const searchableItems = buildSearchableSettingItems() + let externalOidcSigner = $state(false) + $effect(() => { + if ($enterpriseLicense) usesExternalOidcSigner().then((v) => (externalOidcSigner = v)) + }) + const navigationGroups = $derived( + listedNavigationGroups(instanceSettingsNavigationGroups, externalOidcSigner) + ) + const searchableItems = $derived(buildSearchableSettingItems(navigationGroups)) let scrollTimeout: ReturnType<typeof setTimeout> | undefined let highlightTimeout: ReturnType<typeof setTimeout> | undefined @@ -288,7 +296,7 @@ <Button variant="default" target="_blank" - href="{base}/?workspace=admins" + href="/?workspace=admins" endIcon={{ icon: ExternalLink }} > Admins workspace @@ -301,15 +309,11 @@ <!-- Sidebar Navigation --> <div class="w-52 shrink-0 h-full overflow-auto p-4 bg-surface flex flex-col"> <SettingsSearchInput {searchableItems} onSelect={handleSearchSelect} class="mb-3" /> - <SidebarNavigation - groups={instanceSettingsNavigationGroups} - selectedId={tab} - onNavigate={handleNavigate} - /> + <SidebarNavigation groups={navigationGroups} selectedId={tab} onNavigate={handleNavigate} /> {#if $workspaceStore !== 'admins'} <div class="mt-4 pt-2 border-t border-surface-hover"> <a - href="{base}/?workspace=admins" + href="/?workspace=admins" target="_blank" class="flex items-center gap-2 px-2 py-1.5 text-xs text-secondary hover:text-primary transition-colors" > @@ -372,7 +376,7 @@ </div> {/if} - <Tabs bind:selected={usersSubTab} class="mb-4"> + <Tabs bind:selected={usersSubTab} class="mb-4" wrapperClass="shrink-0"> <Tab value="users" label="Users" /> {#if extJwtTokens.length > 0} <Tab value="ext_jwt" label="External JWTs" /> @@ -623,7 +627,7 @@ in {#if workspace_id} <a - href="{base}/workspace_settings?tab=users&workspace={workspace_id}" + href="/workspace_settings?tab=users&workspace={workspace_id}" class="hover:underline" title={workspace_id} onclick={() => closeDrawer?.()} @@ -635,7 +639,7 @@ </span> {:else if groupRole} <a - href="{base}/groups" + href="/groups" class="text-2xs text-tertiary mt-0.5 ml-1 hover:underline" title={groupRoleTooltip} onclick={() => closeDrawer?.()} @@ -655,7 +659,7 @@ displayName: 'Manage in workspace', icon: Settings, action: () => closeDrawer?.(), - href: `${base}/workspace_settings?tab=users&workspace=${workspace_id}` + href: `/workspace_settings?tab=users&workspace=${workspace_id}` } ]} /> diff --git a/frontend/src/lib/components/TimelineBar.svelte b/frontend/src/lib/components/TimelineBar.svelte index 1d8e05008d..66d350a11b 100644 --- a/frontend/src/lib/components/TimelineBar.svelte +++ b/frontend/src/lib/components/TimelineBar.svelte @@ -1,6 +1,5 @@ <script lang="ts"> import { msToSec } from '$lib/utils' - import { base } from '$lib/base' import { ExternalLink } from 'lucide-svelte' import Popover from './Popover.svelte' @@ -59,7 +58,7 @@ {#if tooltip} <span>{tooltip}</span> {:else} - <a href="{base}/run/{id}" class="inline-flex items-center gap-1" target="_blank" + <a href="/run/{id}" class="inline-flex items-center gap-1" target="_blank" >{id} <ExternalLink size={14} /></a > {/if} diff --git a/frontend/src/lib/components/UpdateDevWorkspaceModal.svelte b/frontend/src/lib/components/UpdateDevWorkspaceModal.svelte index c53b1436c8..44fdd6465f 100644 --- a/frontend/src/lib/components/UpdateDevWorkspaceModal.svelte +++ b/frontend/src/lib/components/UpdateDevWorkspaceModal.svelte @@ -1,7 +1,6 @@ <script lang="ts"> import ConfirmationModal from '$lib/components/common/confirmationModal/ConfirmationModal.svelte' import { Alert } from '$lib/components/common' - import { base } from '$lib/base' import { goto } from '$lib/navigation' import { sendUserToast } from '$lib/toast' import { updateDevWorkspaceModal } from '$lib/utils/editInForkModal.svelte' @@ -80,7 +79,7 @@ // confirm button leads when the user can't deploy here, so the request still has somewhere to go. const compareHref = $derived( pending - ? `${base}/forks/compare?workspace_id=${encodeURIComponent(pending.devWorkspaceId)}` + + ? `/forks/compare?workspace_id=${encodeURIComponent(pending.devWorkspaceId)}` + `&mode=fork&dir=update` + `&${COMPARE_ITEMS_PARAM}=${encodeURIComponent(`${pending.itemType}:${pending.itemPath}`)}` : '' diff --git a/frontend/src/lib/components/VariableEditor.svelte b/frontend/src/lib/components/VariableEditor.svelte index be76185959..901bf119cc 100644 --- a/frontend/src/lib/components/VariableEditor.svelte +++ b/frontend/src/lib/components/VariableEditor.svelte @@ -13,7 +13,8 @@ import { VARIABLES_PATH } from './sessions/previewPaths' import Alert from './common/alert/Alert.svelte' import { sendUserToast } from '$lib/toast' - import { canWrite } from '$lib/utils' + import { canEditItem } from '$lib/editRights' + import { userWorkspaces } from '$lib/stores' import { Save } from 'lucide-svelte' import VariableForm from './VariableForm.svelte' import { invalidateWorkspacePaths } from './PathNameAutocomplete.svelte' @@ -137,8 +138,12 @@ if (!selected || !edit) return true const perms = extraPerms[selected] if (!perms || !acting.resolved(selected)) return undefined - return canWrite(editPath ?? '', perms, acting.in(selected)) + return canEditVariableIn(selected, perms) }) + function canEditVariableIn(ws: string, perms: Record<string, boolean>): boolean { + const settings = $userWorkspaces.find((w) => w.id === ws)?.operator_settings + return canEditItem('variable', editPath ?? '', perms, acting.in(ws), settings) + } const dirtyWorkspaces = $derived( Object.keys(states).filter((ws) => !draftValuesEqual(states[ws].draft, initialStates[ws])) ) @@ -301,7 +306,7 @@ const dirtyCanWrite = $derived( dirtyWorkspaces.every((ws) => { const perms = extraPerms[ws] - return !perms || canWrite(editPath ?? '', perms, acting.in(ws)) + return !perms || canEditVariableIn(ws, perms) }) ) diff --git a/frontend/src/lib/components/WorkerGroup.svelte b/frontend/src/lib/components/WorkerGroup.svelte index 3b399a5a1e..1f6b271602 100644 --- a/frontend/src/lib/components/WorkerGroup.svelte +++ b/frontend/src/lib/components/WorkerGroup.svelte @@ -55,6 +55,13 @@ import TagList from './TagList.svelte' import DedicatedWorkersSelector from './DedicatedWorkersSelector.svelte' import { computeHashedTag } from './dedicated_worker' + import { apiBaseUrl } from '$lib/apiBaseUrl.svelte' + import { + devWorkspaceListenSuffix, + devWorkspaceTagSuffix, + loadDevWorkspaceTagSuffix, + withDevSuffix + } from '$lib/devWorkspaceTags' import ObjectStoreConfigSettings, { type ObjectStoreConfig } from './ObjectStoreConfigSettings.svelte' @@ -105,6 +112,7 @@ native_mode?: boolean object_store_cache_config?: ObjectStoreConfig paused?: boolean + serves_dev_workspaces?: boolean } = $state({}) function loadNConfig() { @@ -213,6 +221,7 @@ native_mode?: boolean object_store_cache_config?: ObjectStoreConfig paused?: boolean + serves_dev_workspaces?: boolean } activeWorkers: number customTags: string[] | undefined @@ -318,7 +327,8 @@ 'priority_tags', 'additional_python_paths', 'pip_local_dependencies', - 'object_store_cache_config' + 'object_store_cache_config', + 'serves_dev_workspaces' ] as const function restartsWorkers(body: typeof nconfig): boolean { if (activeWorkers === 0) return false @@ -361,6 +371,15 @@ let drawer: Drawer | undefined = $state() let vcpus_memory = $derived(computeVCpuAndMemory(workers)) + let reportedTags = $derived( + [ + ...new Set( + workers.flatMap(([_, pings]) => + pings.filter((p) => (p.last_ping ?? Infinity) < 60).flatMap((p) => p.custom_tags ?? []) + ) + ) + ].sort() + ) let selected = $derived( nconfig?.dedicated_worker != undefined || nconfig?.dedicated_workers != undefined ? 'dedicated' @@ -380,6 +399,13 @@ !t.startsWith('flow-') ) ) + loadDevWorkspaceTagSuffix() + let devSuffix = $derived($devWorkspaceListenSuffix) + let servesDev = $derived( + config?.serves_dev_workspaces === true && + config?.dedicated_worker == undefined && + !config?.dedicated_workers?.length + ) let isAutoNativeMode = $derived(name === 'native') let isNativeModeEnabled = $derived(nconfig?.native_mode === true || isAutoNativeMode) $effect(() => { @@ -646,6 +672,63 @@ {/if} </Label> + {#if nconfig !== undefined} + {@const flagged = nconfig.serves_dev_workspaces === true} + {@const draftTags = nconfig.worker_tags ?? []} + {@const handSuffixed = draftTags.filter((t) => t.endsWith(devSuffix))} + <div class="mt-8"></div> + <Label label="Dev workspaces" eeOnly={!hasEnterpriseFeatures}> + <Toggle + size="sm" + options={{ + right: 'Serves dev workspaces and forks', + rightTooltip: + 'Runs jobs from dev workspaces and forks only. The group listens to each of its tags with the dev suffix, and no longer to the tags themselves.' + }} + checked={flagged} + on:change={(ev) => { + if (nconfig !== undefined) { + nconfig.serves_dev_workspaces = ev.detail ? true : undefined + } + }} + disabled={!canEditEEConfig} + /> + <p class="text-2xs text-secondary">Runs jobs from dev workspaces and forks only.</p> + {#if flagged} + <div class="flex flex-col gap-1 mt-1"> + <span class="text-2xs text-secondary">Tags this group listens to:</span> + {#if draftTags.length > 0} + <TagList + tags={[...new Set(draftTags.map((t) => withDevSuffix(t, devSuffix)))]} + class="flex-wrap" + /> + {:else} + <span class="text-2xs text-secondary"> + Add tags above: each is listened to as <code + >{withDevSuffix('tag', devSuffix)}</code + >. + </span> + {/if} + </div> + {#if $devWorkspaceTagSuffix === null} + <Alert size="xs" type="info" title="Dev workspace isolation is off"> + New jobs get the <code>{devSuffix}</code> suffix only while dev workspace isolation is + on (Workers page). Until then this group only runs jobs already queued on suffixed tags, + and never takes jobs of root workspaces. + </Alert> + {/if} + {:else if handSuffixed.length > 0} + <Alert size="xs" type="warning" title="This group would take dev workspace jobs"> + {handSuffixed.join(', ')} + {handSuffixed.length === 1 ? 'is a tag' : 'are tags'} of dev workspace and fork jobs. Listing + {handSuffixed.length === 1 ? 'it' : 'them'} here runs those jobs next to root workspace + jobs. Remove {handSuffixed.length === 1 ? 'it' : 'them'}, or flag this group as + serving dev workspaces instead. + </Alert> + {/if} + </Label> + {/if} + {#if nconfig?.worker_tags !== undefined && nconfig?.worker_tags.length > 0} <div class="mt-8"></div> <Label label="High-priority tags" eeOnly={!hasEnterpriseFeatures}> @@ -969,6 +1052,10 @@ <AutoscalingConfigEditor worker_tags={config?.worker_tags} + group_has_tags={nconfig.worker_tags !== undefined + ? nconfig.worker_tags.length > 0 + : (nconfig.dedicated_workers?.length ?? 0) > 0 || nconfig.dedicated_worker !== undefined} + reported_tags={reportedTags} bind:config={nconfig.autoscaling} disabled={!canEditEEConfig} eeOnly={!hasEnterpriseFeatures} @@ -1238,7 +1325,7 @@ <p class="text-xs text-tertiary">Requires a superadmin token.</p> <pre class="mt-1 p-2 bg-surface-secondary rounded text-xs overflow-x-auto whitespace-pre-wrap break-all" - >curl -X POST '{window.location.origin}/api/configs/update/worker__{name}' \ + >curl -X POST '{apiBaseUrl()}/api/configs/update/worker__{name}' \ -H 'Content-Type: application/json' \ -H 'Authorization: Bearer <token>' \ -d '{JSON.stringify(cleanWorkerGroupConfig(nconfig ?? {}), null, 2)}'</pre @@ -1363,6 +1450,17 @@ {#if isNativeMode} <Badge color="blue" small>Native</Badge> {/if} + {#if servesDev} + <Badge color="violet" small> + Dev + <Tooltip> + {#snippet text()} + Serves dev workspaces and forks only: listens to its tags suffixed with + <code>{devSuffix}</code>, never to the tags of root workspace jobs. + {/snippet} + </Tooltip> + </Badge> + {/if} {#if config?.paused === true} <Badge color="yellow" small> Paused @@ -1409,7 +1507,7 @@ </div> {/if} </div> - {#if !isAgent} + {#if !isAgent || config} <div class="flex gap-4 items-center justify-end flex-row"> {#if canEditConfig} {#if width > 1000} @@ -1520,7 +1618,13 @@ {#if config?.worker_tags && config.worker_tags.length > 0} <div class="flex flex-row items-start gap-2 w-full"> <div class="text-secondary text-xs mt-1">Tags:</div> - <TagList tags={config.worker_tags} maxVisible={25} class="flex-wrap" /> + <TagList + tags={servesDev + ? [...new Set(config.worker_tags.map((t) => withDevSuffix(t, devSuffix)))] + : config.worker_tags} + maxVisible={25} + class="flex-wrap" + /> </div> {:else if config?.dedicated_workers && config.dedicated_workers.length > 0} <div class="flex flex-row items-start gap-2 w-full min-w-0"> @@ -1553,7 +1657,12 @@ <div class="mt-4"> <Alert type="info" title="Agent Worker Group" size="xs"> {#snippet children()} - This group is formed with agent workers, there is no associated config. {#if $superadmin || $devopsRole} + {#if config} + This group is formed with agent workers, which ignore its config except for autoscaling. + {:else} + This group is formed with agent workers, there is no associated config. + {/if} + {#if $superadmin || $devopsRole} To modify the tags, generate a new <a href="https://www.windmill.dev/docs/core_concepts/agent_workers#quickstart" target="_blank" diff --git a/frontend/src/lib/components/WorkerTagSelect.svelte b/frontend/src/lib/components/WorkerTagSelect.svelte index 503c8f7f66..cc6b3ebb95 100644 --- a/frontend/src/lib/components/WorkerTagSelect.svelte +++ b/frontend/src/lib/components/WorkerTagSelect.svelte @@ -1,5 +1,5 @@ <script lang="ts"> - import { workerTags, workspaceStore } from '$lib/stores' + import { userWorkspaces, workerTags, workspaceStore } from '$lib/stores' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' import { WorkerService } from '$lib/gen' @@ -10,6 +10,13 @@ import { RotateCw } from 'lucide-svelte' import { sendUserToast } from '$lib/toast' import Popover from './Popover.svelte' + import { + devWorkspaceTagSuffix, + devWorkspaceSkipNonDevForks, + isIsolatedWorkspaceId, + loadDevWorkspaceTagSuffix, + withDevSuffix + } from '$lib/devWorkspaceTags' let { tag = $bindable(), @@ -113,10 +120,16 @@ return } if (open) { - tagsToWorkerExists = await WorkerService.existsWorkersWithTags({ - tags: items.filter((t) => !dynamicTagRegex.test(t)).join(','), + // Probed as jobs of this workspace land: suffixed in a dev workspace. + const probed = items.filter((t) => !dynamicTagRegex.test(t)) + const asRun = (t: string) => (devSuffix ? withDevSuffix(t, devSuffix) : t) + const exists = await WorkerService.existsWorkersWithTags({ + tags: probed.map(asRun).join(','), workspace: effectiveWorkspace }) + tagsToWorkerExists = Object.fromEntries( + probed.filter((t) => asRun(t) in exists).map((t) => [t, exists[asRun(t)]]) + ) lastCheck = Date.now() if (visible) { timeout = setTimeout(loadTagsToWorkerExists, 5000) @@ -145,6 +158,14 @@ }) let open = $state(false) + + loadDevWorkspaceTagSuffix() + let devSuffix = $derived( + $devWorkspaceTagSuffix && + isIsolatedWorkspaceId(effectiveWorkspace, $userWorkspaces, $devWorkspaceSkipNonDevForks) + ? $devWorkspaceTagSuffix + : undefined + ) </script> {#snippet startSnippet({ item })} @@ -186,13 +207,29 @@ {startSnippet} bottomSnippet={refreshAll} /> + {#if devSuffix && tag} + <Popover> + {#snippet text()} + This workspace is a dev workspace or a fork, so its jobs run on worker groups serving dev + workspaces, with every tag suffixed with <code>{devSuffix}</code>. + {/snippet} + <span class="text-2xs text-hint whitespace-nowrap"> + runs as <code>{withDevSuffix(tag, devSuffix)}</code> here + </span> + </Popover> + {/if} </div> {#snippet refreshAll()} <div class="flex items-center justify-between gap-2 border-t border-border-light"> <span class="max-w-64 px-4 py-1 text-2xs text-secondary"> - <code>$workspace</code>, <code>$args[…]</code> and <code>$flow_expr[…]</code> are filled in when - the job runs, and must land on an allowed tag + <code>$workspace</code>, <code>$args[…]</code> and <code>$flow_expr[…]</code> are filled in + when the job runs, and must land on an allowed tag + {#if devSuffix} + <br />In this dev workspace every tag runs suffixed with <code>{devSuffix}</code>, the + default one included: <code>gpu</code> runs as + <code>{withDevSuffix('gpu', devSuffix)}</code> + {/if} </span> <Button iconOnly diff --git a/frontend/src/lib/components/WorkflowTimeline.svelte b/frontend/src/lib/components/WorkflowTimeline.svelte index 868f215c20..4526281293 100644 --- a/frontend/src/lib/components/WorkflowTimeline.svelte +++ b/frontend/src/lib/components/WorkflowTimeline.svelte @@ -1,5 +1,4 @@ <script lang="ts"> - import { base } from '$lib/base' import { displayDate, msToSec, emptyString } from '$lib/utils' import { onDestroy } from 'svelte' import { getDbClockNow } from '$lib/forLater' @@ -315,7 +314,7 @@ <a target="_blank" class="inline-flex gap-2 items-baseline hover:underline whitespace-nowrap" - href="{base}/run/{k}" + href="/run/{k}" onclick={(e) => e.stopPropagation()} > {v.name ?? k} diff --git a/frontend/src/lib/components/aiEvals/EvalScorers.svelte b/frontend/src/lib/components/aiEvals/EvalScorers.svelte index d00e52d77e..e87745887b 100644 --- a/frontend/src/lib/components/aiEvals/EvalScorers.svelte +++ b/frontend/src/lib/components/aiEvals/EvalScorers.svelte @@ -21,7 +21,6 @@ Settings, Trash2 } from 'lucide-svelte' - import { base } from '$lib/base' import AddScorer from './AddScorer.svelte' import { kindLabel, parseThreshold, scorerLabel, type ScorerKind } from './evalUtils' @@ -304,8 +303,8 @@ <a class="flex items-center gap-1.5 text-xs min-w-0 hover:underline w-fit" href={settingsScorer.kind === 'agent' - ? `${base}/resources?path=${settingsScorer.path}&workspace=${workspace}` - : `${base}/scripts/get/${settingsScorer.path}?workspace=${workspace}`} + ? `/resources?path=${settingsScorer.path}&workspace=${workspace}` + : `/scripts/get/${settingsScorer.path}?workspace=${workspace}`} target="_blank" rel="noreferrer" title={`Open ${settingsScorer.path}`} diff --git a/frontend/src/lib/components/aiEvals/EvalsPane.svelte b/frontend/src/lib/components/aiEvals/EvalsPane.svelte index db765607e5..267d174f0f 100644 --- a/frontend/src/lib/components/aiEvals/EvalsPane.svelte +++ b/frontend/src/lib/components/aiEvals/EvalsPane.svelte @@ -1,5 +1,4 @@ <script lang="ts"> - import { base } from '$lib/base' import { Button } from '$lib/components/common' import Select from '$lib/components/select/Select.svelte' import DataTable from '$lib/components/table/DataTable.svelte' @@ -768,7 +767,7 @@ {#if experiment?.run_job_id} <a class="text-xs text-accent hover:underline inline-flex items-center gap-1 shrink-0 pb-2" - href={`${base}/run/${experiment.run_job_id}?workspace=${ws}`} + href={`/run/${experiment.run_job_id}?workspace=${ws}`} target="_blank" > Open the job @@ -962,7 +961,7 @@ {#if openRow.job_id} <a class="text-2xs text-accent hover:underline inline-flex items-center gap-1" - href={`${base}/run/${openRow.job_id}?workspace=${ws}`} + href={`/run/${openRow.job_id}?workspace=${ws}`} target="_blank" > Open the case job diff --git a/frontend/src/lib/components/apps/components/display/dbtable/utils.ts b/frontend/src/lib/components/apps/components/display/dbtable/utils.ts index 21371aa08b..ae3a82e97c 100644 --- a/frontend/src/lib/components/apps/components/display/dbtable/utils.ts +++ b/frontend/src/lib/components/apps/components/display/dbtable/utils.ts @@ -41,6 +41,8 @@ export type ColumnDef = { children?: ColumnDef[] // DBExplorer ignored?: boolean + /** False when the column cannot be filtered on, e.g. a nested value. */ + filterable?: boolean hideInsert?: boolean editable?: boolean overrideDefaultValue?: boolean diff --git a/frontend/src/lib/components/apps/components/helpers/RunnableComponent.svelte b/frontend/src/lib/components/apps/components/helpers/RunnableComponent.svelte index 41a72fd88b..ebea15de26 100644 --- a/frontend/src/lib/components/apps/components/helpers/RunnableComponent.svelte +++ b/frontend/src/lib/components/apps/components/helpers/RunnableComponent.svelte @@ -32,6 +32,8 @@ import { selectId } from '../../editor/appUtils' import { collectOneOfFields } from '../../editor/appUtilsCore' import { userStore } from '$lib/stores' + import { useOperatingUser } from '$lib/components/operatingWorkspace.svelte' + import { appPreviewOnBehalfOf } from '$lib/utils/previewOnBehalfOf' import { get } from 'svelte/store' import RefreshButton from '$lib/components/apps/components/helpers/RefreshButton.svelte' import { ctxRegex } from '../../utils' @@ -128,8 +130,10 @@ app, connectingInput, bgRuns, - recomputeAllContext + recomputeAllContext, + policy } = getContext<AppViewerContext>('AppViewerContext') + const operatingUser = useOperatingUser() const editorContext = getContext<AppEditorContext>('AppEditorContext') const iterContext = getContext<ListContext>('ListWrapperContext') @@ -530,7 +534,8 @@ force_viewer_one_of_fields: !isEditor ? undefined : undefinedIfEmpty(oneOfRunnableInputs), force_viewer_allow_user_resources: !isEditor ? undefined - : undefinedIfEmpty(allowUserResources) + : undefinedIfEmpty(allowUserResources), + on_behalf_of: isEditor ? appPreviewOnBehalfOf(operatingUser.current, policy) : undefined } return requestBody } diff --git a/frontend/src/lib/components/apps/components/helpers/eval.ts b/frontend/src/lib/components/apps/components/helpers/eval.ts index bacfb65b2d..0b6bdd55db 100644 --- a/frontend/src/lib/components/apps/components/helpers/eval.ts +++ b/frontend/src/lib/components/apps/components/helpers/eval.ts @@ -1,7 +1,6 @@ import type { World } from '../../rx' import { sendUserToast } from '$lib/toast' import { waitJob } from '$lib/components/waitJob' -import { base } from '$lib/base' import { appNavigateSameWindow } from '../../utils' import { OpenAPI } from '$lib/gen/core/OpenAPI' @@ -312,10 +311,10 @@ export async function eval_like( params.append('s3', input.s3 ?? '') if (input.storage) params.append('storage', input.storage) params.append('token', OpenAPI.TOKEN) - const s3href = `${base}/api/w/${workspaceId}/apps_u/download_s3_file/${appPath}?${params.toString()}` + const s3href = `/api/w/${workspaceId}/apps_u/download_s3_file/${appPath}?${params.toString()}` downloadFile(s3href, filename || input.s3) } else { - const s3href = `${base}/api/w/${workspaceId}/job_helpers/download_s3_file?file_key=${encodeURIComponent( + const s3href = `/api/w/${workspaceId}/job_helpers/download_s3_file?file_key=${encodeURIComponent( input?.s3 ?? '' )}${input?.storage ? `&storage=${input.storage}` : ''}` downloadFile(s3href, filename || input.s3) diff --git a/frontend/src/lib/components/apps/components/helpers/executeRunnable.ts b/frontend/src/lib/components/apps/components/helpers/executeRunnable.ts index a59f10b66b..5f11ac571f 100644 --- a/frontend/src/lib/components/apps/components/helpers/executeRunnable.ts +++ b/frontend/src/lib/components/apps/components/helpers/executeRunnable.ts @@ -1,4 +1,4 @@ -import { AppService, type ExecuteComponentData } from '$lib/gen' +import { AppService, type ExecuteComponentData, type ScriptModule } from '$lib/gen' import { defaultIfEmptyString } from '$lib/utils' import { isRunnableByName, isRunnableByPath, type Runnable } from '../../inputType' import type { InlineScript } from '../../sharedTypes' @@ -12,7 +12,8 @@ export async function executeRunnable( id: string, requestBody: ExecuteComponentData['requestBody'], inlineScriptOverride?: InlineScript, - queryParams?: Record<string, any> + queryParams?: Record<string, any>, + modules?: Record<string, ScriptModule> ) { let appPath = defaultIfEmptyString(path, `u/${username ?? 'unknown'}/newapp`) if (isRunnableByName(runnable)) { @@ -24,13 +25,17 @@ export async function executeRunnable( if (inlineScript.id !== undefined) { requestBody['id'] = inlineScript.id } + // A lock is not cleared when only an imported runnable is edited, so with + // modules the preview resolves dependencies afresh. + const previewModules = inlineScript.id === undefined ? modules : undefined requestBody['raw_code'] = { content: inlineScript.id === undefined ? inlineScript.content : '', language: inlineScript.language ?? '', path: appPath + '/' + id, - lock: inlineScript.id === undefined ? inlineScript.lock : undefined, + lock: inlineScript.id === undefined && !previewModules ? inlineScript.lock : undefined, cache_ttl: inlineScript.cache_ttl, - ...(inlineScript.tag ? { tag: inlineScript.tag } : {}) + ...(inlineScript.tag ? { tag: inlineScript.tag } : {}), + ...(previewModules ? { modules: previewModules } : {}) } } } else if (isRunnableByPath(runnable)) { diff --git a/frontend/src/lib/components/apps/editor/AppEditorHeader.svelte b/frontend/src/lib/components/apps/editor/AppEditorHeader.svelte index f07d596baa..e5613a71a1 100644 --- a/frontend/src/lib/components/apps/editor/AppEditorHeader.svelte +++ b/frontend/src/lib/components/apps/editor/AppEditorHeader.svelte @@ -54,7 +54,7 @@ import EditorHeader from '$lib/components/EditorHeader.svelte' import PageHeaderContent from '$lib/components/PageHeaderContent.svelte' import PathEditPopover from '$lib/components/PathEditPopover.svelte' - import { pageHeader, PHONE_BAR } from '$lib/components/pageHeaderRegistry.svelte' + import { pageHeader } from '$lib/components/pageHeaderRegistry.svelte' import AutosaveIndicator from '$lib/components/AutosaveIndicator.svelte' import { editPathFor } from '$lib/components/workspacePicker' import { invalidateWorkspacePaths } from '$lib/components/PathNameAutocomplete.svelte' @@ -261,36 +261,36 @@ // Top-bar responsive collapse — container width, not viewport. let topbarWidth = $state(0) - // In the page header the buttons share the row with the breadcrumb, so they shed the canvas - // toggles and fold Debug runs into the menu sooner: the whole group is ~840px and the trail - // with the summary takes ~430px of the same row. - // Measured on the band rather than estimated: with the canvas toggles shown the actions alone - // are 826-911px and the trail with the summary another ~500, so the row overflows the bar at - // every width up to about 1470 — 1350 was not high enough either. Below this the toggles stand - // down and the menu carries all three, which is what keeps them reachable rather than merely - // out of the way. - const compactBelow = $derived(ownsPageHeader ? 1500 : 720) - const compactTopbar = $derived.by(() => { - const w = ownsPageHeader ? pageHeader.barWidth : topbarWidth - return w > 0 && w < compactBelow - }) - // A phone's bar holds the trail and Deploy. Which panels are open, the export and the - // editor/preview switch join the menu compact already shows. - const phoneTopbar = $derived( - ownsPageHeader && pageHeader.barWidth > 0 && pageHeader.barWidth < PHONE_BAR + // In the page header the bar folds the buttons (`actionFolds` below), once its breadcrumb has + // given all it can; anywhere else this editor's own top bar is theirs alone. Folded, the canvas + // toggles stand down and the menu carries them and Debug runs, which keeps them reachable + // rather than merely out of the way. + const compactTopbar = $derived( + ownsPageHeader ? pageHeader.actionFold >= 1 : topbarWidth > 0 && topbarWidth < 720 ) + // The second fold holds the trail and Deploy. Which panels are open, the export and the + // editor/preview switch join the menu compact already shows. + const phoneTopbar = $derived(ownsPageHeader && pageHeader.actionFold >= 2) function closeSaveDrawer() { saveDrawerOpen = false } + // `parent_version` is the draft's stale-check base. Deployed, it would put a version + // id that changes on every deploy into git-synced files and version diffs. + function withoutDraftBase<T extends App | undefined>(a: T): T { + if (!a) return a + const { parent_version: _pv, ...rest } = a + return rest as T + } + async function createApp(path: string) { policy = await updatePolicy($app, policy) try { await AppService.createApp({ workspace: $workspaceStore!, requestBody: { - value: $app, + value: withoutDraftBase($app), path, summary: $summary, policy, @@ -307,7 +307,7 @@ summary: $summary, value: structuredClone($state.snapshot($app)), path: path, - policy: policy, + policy: $state.snapshot(policy), custom_path: customPath, labels: $state.snapshot(labels) } @@ -349,7 +349,7 @@ orderedJsonStringify( replaceFalseWithUndefined({ summary: $summary, - value: $app, + value: withoutDraftBase($app), path: newEditedPath || savedApp.path, policy, custom_path: customPath, @@ -392,6 +392,7 @@ // Strip off extra information deployedValue = replaceFalseWithUndefined({ ...deployedApp, + value: withoutDraftBase(deployedApp.value as App), id: undefined, created_at: undefined, created_by: undefined, @@ -406,7 +407,7 @@ workspace: $workspaceStore!, path: $appPath!, requestBody: { - value: $app!, + value: withoutDraftBase($app!), summary: $summary, policy, path: npath, @@ -424,7 +425,7 @@ summary: $summary, value: structuredClone($state.snapshot($app)), path: npath, - policy, + policy: $state.snapshot(policy), custom_path: customPath, labels: $state.snapshot(labels) } @@ -753,7 +754,7 @@ deployed: deployedValue ?? savedApp, current: { summary: $summary, - value: $app, + value: withoutDraftBase($app), path: newEditedPath || savedApp.path, policy, custom_path: customPath, @@ -847,7 +848,7 @@ bind:deployedValue currentValue={{ summary: $summary, - value: $app, + value: withoutDraftBase($app), path: newEditedPath || savedApp?.path, policy, custom_path: customPath, @@ -898,7 +899,7 @@ deployed: deployedValue ?? savedApp, current: { summary: $summary, - value: $app, + value: withoutDraftBase($app), path: newEditedPath || savedApp.path, policy, custom_path: customPath, @@ -1001,10 +1002,12 @@ // Frozen while the rename popover is open so the trail holds still as the user types. kind: 'app', path: pathSnapshot ?? (newEditedPath || $appPath || newPath || undefined), + summary: $summary, summaryContent: appSummary, pathTrigger: appPathTrigger }} actions={appHeaderActions} + actionFolds={2} contexts={headerContexts} separator="always" /> diff --git a/frontend/src/lib/components/apps/editor/AppEditorHeaderDeploy.svelte b/frontend/src/lib/components/apps/editor/AppEditorHeaderDeploy.svelte index d062247fa4..41e0c5c3f2 100644 --- a/frontend/src/lib/components/apps/editor/AppEditorHeaderDeploy.svelte +++ b/frontend/src/lib/components/apps/editor/AppEditorHeaderDeploy.svelte @@ -1,9 +1,10 @@ <script lang="ts"> - import { Alert } from '$lib/components/common' - import Badge from '$lib/components/common/badge/Badge.svelte' + import { Alert, Section } from '$lib/components/common' import Toggle from '$lib/components/Toggle.svelte' + import Badge from '$lib/components/Badge.svelte' import { enterpriseLicense, userStore } from '$lib/stores' - import { Loader2 } from 'lucide-svelte' + import { useOperatorBuilderApps } from '$lib/operatorWriteRights' + import { AlertTriangle, Loader2 } from 'lucide-svelte' import Tooltip from '$lib/components/Tooltip.svelte' @@ -15,7 +16,6 @@ import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte' import Path from '$lib/components/Path.svelte' import { computeSecretUrl } from './appDeploy.svelte' - import { base } from '$lib/base' import { isCloudHosted } from '$lib/cloud' import EEOnly from '$lib/components/EEOnly.svelte' import TextInput from '$lib/components/text_input/TextInput.svelte' @@ -24,7 +24,7 @@ type OnBehalfOfChoice } from '$lib/components/OnBehalfOfSelector.svelte' import { canUserBypassRuleKind, protectionRulesState } from '$lib/workspaceProtectionRules.svelte' - import { FRONTEND_SDK_SCOPES } from '$lib/components/raw_apps/sdkScopes' + import { FRONTEND_SDK_SCOPES, sdkScopesToConfirm } from '$lib/components/raw_apps/sdkScopes' import { logFeatureUsage } from '$lib/utils/featureUsage' import { useOperatingUser, @@ -34,6 +34,7 @@ const operatingWorkspaceStore = useOperatingWorkspace() const operatingUser = useOperatingUser() const actingUser = $derived(operatingUser.current) + const operatorBuilderApps = useOperatorBuilderApps() const WM_DEPLOYERS_GROUP = 'wm_deployers' @@ -157,6 +158,17 @@ let savedOnBehalfOf = $derived(savedApp?.policy?.on_behalf_of) let onBehalfOfChoice: OnBehalfOfChoice = $state(undefined) let customOnBehalfOfEmail: string = $state('') + let myOnBehalfOf = $derived(actingUser?.username ? `u/${actingUser.username}` : undefined) + // Without the right to preserve, the backend runs the redeployed app as the deployer whatever + // the policy says, as it does for "me". + let deployOnBehalfOf = $derived.by(() => { + if (!canPreserve || onBehalfOfChoice === 'me') return myOnBehalfOf + if (onBehalfOfChoice === 'custom') return policy.on_behalf_of + return savedOnBehalfOf + }) + let onBehalfOfWillChange = $derived( + !newApp && !!savedOnBehalfOf && !!deployOnBehalfOf && deployOnBehalfOf !== savedOnBehalfOf + ) let dirtyCustomPath = $state(false) let path: Path | undefined = $state(undefined) @@ -185,7 +197,7 @@ let secretUrl: string | undefined = $state(undefined) let secretUrlHref = $derived(secretUrl ? computeSecretUrl(secretUrl) : undefined) let fullCustomUrl = $derived( - `${window.location.origin}${base}/a/${ + `${window.location.origin}/a/${ isCloudHosted() || globalWorkspacedRoute ? opWs + '/' : '' }${customPath}` ) @@ -241,432 +253,456 @@ }) </script> -{#if !onLatest} - <Alert - title={headUnknown - ? 'Could not check the deployed version. ' - : "You're not on the latest app version. "} - type="warning" - > - {headUnknown - ? "Deploying may overwrite changes made by other users. Press 'Deploy' to see diff." - : "By deploying, you may overwrite changes made by other users. Press 'Deploy' to see diff."} - </Alert> - <div class="py-2"></div> -{/if} -<label for="summary" class="text-emphasis text-xs font-semibold">Summary</label> -<div class="w-full pt-1"> - <!-- svelte-ignore a11y_autofocus --> - <TextInput - inputProps={{ - id: 'summary', - autofocus: true, - placeholder: 'App summary', - onkeydown: (e) => { - e.stopPropagation() - }, - onkeyup: () => { - if (appPath == '' && summary?.length > 0 && !dirtyPath) { - path?.setName( - summary - .toLowerCase() - .replace(/[^a-z0-9_]/g, '_') - .replace(/-+/g, '_') - .replace(/^-|-$/g, '') - ) - } - } - }} - bind:value={summary} - /> -</div> -<div class="pt-3"></div> -<LabelsInput bind:labels class="-mt-4" /> -<div class="py-6"></div> -<label for="deploymentMsg" class="text-emphasis text-xs font-semibold">Deployment message</label> -<div class="w-full pt-1"> - <!-- svelte-ignore a11y_autofocus --> - <TextInput - inputProps={{ - id: 'deploymentMsg', - placeholder: 'Optional deployment message' - }} - bind:value={deploymentMsg} - /> -</div> -<div class="py-6"></div> -<label for="path" class="text-emphasis text-xs font-semibold">Path</label> -<Path - bind:this={path} - bind:dirty={dirtyPath} - bind:error={pathError} - bind:path={newEditedPath} - initialPath={newPath} - namePlaceholder="app" - kind="app" - autofocus={false} - workspaceOverride={operatingWorkspace} -/> +<div class="flex flex-col gap-8"> + {#if !onLatest} + <Alert + title={headUnknown + ? 'Could not check the deployed version. ' + : "You're not on the latest app version. "} + type="warning" + > + {headUnknown + ? "Deploying may overwrite changes made by other users. Press 'Deploy' to see diff." + : "By deploying, you may overwrite changes made by other users. Press 'Deploy' to see diff."} + </Alert> + {/if} -<div class="py-2"></div> -<Alert title="App executed on behalf of you"> - A viewer of the app will execute the runnables of the app on behalf of the publisher (you) - <Tooltip> - It ensures that all required resources/runnable visible for publisher but not for viewer at time - of creating the app would prevent the execution of the app. To guarantee tight security, a - policy is computed at time of deployment of the app which only allow the scripts/flows referred - to in the app to be called on behalf of. Furthermore, static parameters are not overridable. - Hence, users will only be able to use the app as intended by the publisher without risk for - leaking resources not used in the app. - </Tooltip> - {#if canPreserve} - <div class="mt-4"> - Because you are either an admin or part of the {WM_DEPLOYERS_GROUP} group, you can select another - user to run this app on behalf of. Once deployed the app will be run on behalf of - <OnBehalfOfSelector - targetWorkspace={opWs ?? ''} - targetValue={savedOnBehalfOfEmail} - selected={onBehalfOfChoice} - onSelect={(choice, details) => { - onBehalfOfChoice = choice - if (choice === 'me') { - policy.on_behalf_of_email = $userStore?.email - policy.on_behalf_of = `u/${$userStore?.username}` - customOnBehalfOfEmail = '' - preserveOnBehalfOf = false - } else if (choice === 'target') { - policy.on_behalf_of_email = savedOnBehalfOfEmail - policy.on_behalf_of = savedOnBehalfOf - customOnBehalfOfEmail = '' - preserveOnBehalfOf = true - } else if (choice === 'custom' && details) { - policy.on_behalf_of_email = details.email - policy.on_behalf_of = details.permissionedAs - customOnBehalfOfEmail = details.email - preserveOnBehalfOf = true + <div class="flex flex-col gap-6"> + <div class="flex flex-col gap-1"> + <label for="summary" class="text-emphasis text-xs font-semibold">Summary</label> + <!-- svelte-ignore a11y_autofocus --> + <TextInput + inputProps={{ + id: 'summary', + autofocus: true, + placeholder: 'App summary', + onkeydown: (e) => { + e.stopPropagation() + }, + onkeyup: () => { + if (appPath == '' && summary?.length > 0 && !dirtyPath) { + path?.setName( + summary + .toLowerCase() + .replace(/[^a-z0-9_]/g, '_') + .replace(/-+/g, '_') + .replace(/^-|-$/g, '') + ) + } } }} + bind:value={summary} + /> + <LabelsInput bind:labels /> + </div> + <div class="flex flex-col gap-1"> + <label for="deploymentMsg" class="text-emphasis text-xs font-semibold"> + Deployment message + </label> + <TextInput + inputProps={{ + id: 'deploymentMsg', + placeholder: 'Optional deployment message' + }} + bind:value={deploymentMsg} + /> + </div> + <div class="flex flex-col gap-1"> + <label for="path" class="text-emphasis text-xs font-semibold">Path</label> + <Path + bind:this={path} + bind:dirty={dirtyPath} + bind:error={pathError} + bind:path={newEditedPath} + initialPath={newPath} + namePlaceholder="app" kind="app" - {canPreserve} - customValue={customOnBehalfOfEmail} - isDeployment={false} + autofocus={false} + workspaceOverride={operatingWorkspace} /> </div> - {/if} -</Alert> - -<div class="mt-10"></div> - -<div class="flex items-center gap-2"> - <h2>Sandbox isolation</h2> - <Badge color="yellow">Alpha</Badge> -</div> -<div class="my-6"> - <Toggle - options={{ right: "Isolate the app from the viewer's browser session" }} - checked={policy.sandbox == true} - on:change={(e) => { - policy.sandbox = e.detail || undefined - // Counted where the toggle is flipped rather than where the policy is - // persisted: a not-yet-deployed app only mutates it locally, and skipping - // those would read as unused in the case where it is picked up front. - logFeatureUsage('app_sandbox', 'toggled', { - key: `${rawApp ? 'raw' : 'low_code'}:${e.detail ? 'on' : 'off'}` - }) - // Frontend API access exists only for a sandboxed app, so turning - // isolation off drops the declared scopes with it rather than leaving - // them set but inert. - if (!e.detail) { - policy.frontend_sdk_scopes = undefined - } - // A not-yet-deployed app has no row to PATCH — `setPublishState` (POST - // /apps/update) would 404. The flag rides along in the `policy` the first - // deploy sends (createApp), so here we only mutate it locally. Persist - // incrementally once the app exists. - if (savedApp && !newApp) { - setPublishState(e.detail ? 'Sandbox isolation enabled' : 'Sandbox isolation disabled') - } - }} - disabled={!savedApp} - /> - <div class="text-xs text-secondary mt-1"> - Controls what the app's browser-side code can reach in each viewer's browser — distinct from the - on-behalf-of model above (which sets who its runnables run as). Off by default, the app's code - uses the viewer's own session; enable it to confine the app to a narrowly-scoped token instead, - on every surface (public URL and in-workspace). Leave it off if the app needs full browser - features (IndexedDB, third-party auth/SDKs, OAuth redirects). </div> - {#if newApp} - <div class="text-xs text-tertiary mt-1">Takes effect when you first deploy this app.</div> - {/if} - {#if policy.sandbox == true} - <div class="mt-2"> - <Alert type="warning" title="Alpha feature" size="xs"> - Sandbox isolation is in alpha. After enabling, open the app from its public URL to confirm - it still works, and report any broken behavior. - </Alert> - </div> - {/if} -</div> -{#if rawApp && policy.sandbox == true} - <h2 class="text-xs font-semibold">Frontend API access</h2> - <div class="mb-6 mt-2"> - <div class="text-xs text-secondary mb-3"> - Let the app's frontend code call the Windmill API through the <code>windmill-client</code> - SDK, authenticated as <b>the viewer</b> (unlike runnables, which run on behalf of the - publisher). Each viewer is asked to approve the scopes below before the app runs. Grant only - what the app needs: its code — or an XSS bug in it — can use them as that viewer. Add - <code>windmill-client</code> to the app's dependencies to import it; it configures itself from - the token handed to the bundle. - </div> - {#each FRONTEND_SDK_SCOPES as scope (scope.value)} - <div class="mb-2"> - <Toggle - size="xs" - options={{ right: scope.label }} - checked={policy.frontend_sdk_scopes?.includes(scope.value) ?? false} - on:change={(e) => { - const current: string[] = policy.frontend_sdk_scopes ?? [] - const next = e.detail - ? [...current, scope.value] - : current.filter((s) => s !== scope.value) - // Keep the curated order so the consent banner and the stored - // consent compare stably across deploys. - const ordered = FRONTEND_SDK_SCOPES.map((s) => s.value).filter((s) => next.includes(s)) - policy.frontend_sdk_scopes = ordered.length > 0 ? ordered : undefined - // Same as sandbox: a not-yet-deployed app has no row to PATCH, so the - // scopes ride along in the first deploy's policy instead. - if (savedApp && !newApp) { - setPublishState('Frontend API access updated') + <Section + label="Run on behalf of" + tooltip={`The app's runnables run as this user whoever opens the app, so viewers need no access of their own. To keep that safe, the app can call only the runnables it was deployed with, and viewers cannot override their static inputs. Runnables still get the viewer's email in WM_END_USER_EMAIL${rawApp ? ', and inline ones can be set to read data tables and object storage as the viewer' : ''}.`} + > + <div class="flex flex-col items-start gap-1"> + <div class="flex items-center gap-1.5"> + <OnBehalfOfSelector + targetWorkspace={opWs ?? ''} + targetValue={savedOnBehalfOfEmail} + selected={onBehalfOfChoice} + onSelect={(choice, details) => { + onBehalfOfChoice = choice + if (choice === 'me') { + policy.on_behalf_of_email = $userStore?.email + policy.on_behalf_of = `u/${$userStore?.username}` + customOnBehalfOfEmail = '' + preserveOnBehalfOf = false + } else if (choice === 'target') { + policy.on_behalf_of_email = savedOnBehalfOfEmail + policy.on_behalf_of = savedOnBehalfOf + customOnBehalfOfEmail = '' + preserveOnBehalfOf = true + } else if (choice === 'custom' && details) { + policy.on_behalf_of_email = details.email + policy.on_behalf_of = details.permissionedAs + customOnBehalfOfEmail = details.email + preserveOnBehalfOf = true } }} - disabled={!savedApp} + kind="app" + {canPreserve} + customValue={customOnBehalfOfEmail} + isDeployment={false} + myPermissionedAs={myOnBehalfOf} + readOnlyWithoutPreserve /> - <div class="text-xs text-hint ml-9">{scope.description}</div> + {#if onBehalfOfWillChange} + <AlertTriangle class="w-3.5 h-3.5 text-yellow-500" /> + <span class="text-2xs text-yellow-600 dark:text-yellow-400" + >will change from <strong>{savedOnBehalfOf}</strong> on deploy</span + > + {/if} </div> - {/each} - {#if newApp} - <div class="text-xs text-tertiary mt-1">Takes effect when you first deploy this app.</div> - {/if} - {#if policy.frontend_sdk_scopes?.length} - <div class="mt-2"> - <Alert type="info" title="Redeploy to use the SDK from a sandboxed app" size="xs"> - A sandboxed app calls the API cross-origin, which older <code>windmill-client</code> versions - cannot do. An app bundled before this Windmill version fails with a CORS error until you deploy - it again, which re-bundles it against a current client. - </Alert> - </div> - {/if} - </div> -{/if} - -{#if !hideSecretUrl} - <h2>Access</h2> - - <div class="my-6"> - {#if rulesetsLoaded && !canSetAnonymous && policy.execution_mode != 'anonymous'} - <Alert type="warning" title="Restricted by a workspace protection rule" size="xs"> - Opening this app to anyone with the link is restricted to workspace admins and bypass users - by a workspace protection rule - </Alert> - <div class="mb-2"></div> - {/if} - {#if rulesetsLoaded && !canSetGuest && policy.execution_mode != 'guest' && guestsAvailable} - <Alert type="warning" title="Restricted by a workspace protection rule" size="xs"> - Opening this app to guests is restricted to workspace admins and bypass users by a workspace - protection rule - </Alert> - <div class="mb-2"></div> - {/if} - <div class="flex gap-2 items-center mb-2"> - <ToggleButtonGroup - selected={accessMode} - on:selected={(e) => onAccessModeChange(e.detail)} - disabled={!savedApp} - > - {#snippet children({ item })} - <ToggleButton - label="Members" - value="publisher" - tooltip="Workspace members with read access on this app." - {item} - /> - <ToggleButton - label="Guests" - value="guest" - disabled={policy.execution_mode != 'guest' && (!guestsAvailable || !canSetGuest)} - tooltip={!guestsAvailable - ? 'Not available on Windmill Cloud. Guests require a self-hosted instance or a dedicated Windmill Cloud deployment.' - : "Anyone your identity provider authenticates who has no Windmill account, plus workspace members. No membership, no seat up to the instance's allowance."} - {item} - /> - <ToggleButton - label="Public" - value="anonymous" - disabled={!canSetAnonymous && policy.execution_mode != 'anonymous'} - tooltip="Anyone with the secret URL. No login." - {item} - /> - {/snippet} - </ToggleButtonGroup> - </div> - <div class="text-xs text-secondary mb-3"> - {#if policy.execution_mode == 'anonymous'} - Anyone holding the secret URL below can open this app without signing in. - {:else if policy.execution_mode == 'guest'} - {#if !guestsAvailable} - Guests are not available on Windmill Cloud, so this app still admits members only. They - require a self-hosted instance or a dedicated Windmill Cloud deployment. - {:else if guestUsage && !guestUsage.instance_enabled} - A superadmin has turned guests off for this instance, so this app still admits members - only. - {:else if guestAccessEnabled === undefined} - Checking whether this workspace allows guests… - {:else if guestAccessEnabled === false} - Guests are turned off for this workspace, so this app still admits members only. A - workspace admin can turn them on in the workspace settings. + <div class="text-2xs text-secondary"> + {#if canPreserve} + Viewers run the app's runnables as this user. {:else} - Anyone your identity provider authenticates can open this app without a Windmill account. - They join no workspace. Members of this workspace can open it too. - {#if guestUsage} - {guestUsage.guest_count} of {guestUsage.free_allowance} free guests used across this instance - in the last {guestUsage.window_days} days; beyond that, {guestUsage.metered - ? 'every four guests count as one seat' - : 'new guests are refused until the count drops'}. - {/if} + Only workspace admins and members of {WM_DEPLOYERS_GROUP} can pick another user. {/if} - {:else} - Only workspace members with read access on this app can open it. - {/if} - </div> - {#if !savedApp || newApp} - <ClipboardPanel content={`Deploy this app once to get the public secret URL`} size="md" /> - {:else if secretUrlHref} - <div class="flex justify-end mb-1"> - <Toggle - size="xs" - checked={embedMode} - on:change={(e) => (embedMode = e.detail)} - options={{ left: 'URL', right: 'Embed' }} - /> </div> - <ClipboardPanel - content={embedMode ? toEmbedSnippet(secretUrlHref) : secretUrlHref} - size="md" - /> - {:else}<Loader2 class="animate-spin" /> - {/if} - <div class="text-xs text-secondary mt-1"> - {#if embedMode} - Paste this iframe snippet into another app. - {#if rawApp} - To embed it in a cross-origin isolated page, add <code>wm_coep=on</code> - <Tooltip - >Sets the cross-origin isolation headers (COEP) on the app, which such a page requires - of its iframes. The app then only loads cross-origin resources that send CORS or a - Cross-Origin-Resource-Policy header.</Tooltip - > to the URL. - {/if} - (if requiring login, top-level domain of embedding app must be the same as the one of Windmill) - {:else} - Share this url directly, or switch to <b>Embed</b> to get an iframe snippet. - {/if} </div> + </Section> - {#if embedMode && policy.execution_mode == 'guest' && guestAccessEnabled && guestJwtBase && guestsAvailable} - <div class="mt-4 border-t pt-3 flex flex-col gap-2"> - <div class="text-xs font-semibold text-emphasis"> - Embed for your own authenticated users (guest JWT) - </div> - <div class="text-xs text-secondary"> - To open this app for a user your own product already authenticates, mint a short-lived JWT - in your backend and append it to the app URL as <code>guest.<jwt></code>. Each token - is its own seatless guest, confined to this app — no shared secret and no Windmill - account, unlike the plain secret URL above. - </div> - <div class="text-xs text-secondary"> - Windmill verifies the token against the workspace's guest JWT key (Workspace settings → - Guests) — a PEM public key or a JWKS URL{#if !isCloudHosted()}, or the instance's - configured issuer (<code>JWT_EXT_JWKS_URL</code>) when no workspace key is set{/if}. Set - the <b>public</b> half there; in your backend, sign each token with the matching - <b>private</b> key using RS256/384/512, PS256/384/512 or ES256/384 (symmetric HS* is - refused), carrying <code>email</code>, <code>workspace_id</code> = <code>{opWs}</code>, - <code>app_path</code> = <code>{appPath}</code> and <code>exp</code> (at most 24h ahead). - </div> - <ClipboardPanel - content={toEmbedSnippet(`${guestJwtBase}/guest.YOUR_GUEST_JWT`)} - size="md" - /> - <div class="text-2xs text-secondary"> - Replace <code>YOUR_GUEST_JWT</code> with the token your backend signs per user. Past the instance's - free guest allowance a new guest email is refused (see the count above); guests already seen - in the window keep working. - </div> + <Section label="Sandbox isolation"> + <Toggle + options={{ + right: "Isolate the app from the viewer's browser session", + rightTooltip: + "Controls what the app's browser-side code can reach in each viewer's browser, separately from who its runnables run as. A sandboxed app gets a narrowly scoped token on every surface, public URL and in-workspace. On by default for new apps. Turn it off only if the app needs IndexedDB, third-party sign-in or OAuth redirects." + }} + checked={$operatorBuilderApps || policy.sandbox == true} + on:change={(e) => { + policy.sandbox = e.detail || undefined + // Counted where the toggle is flipped rather than where the policy is + // persisted: a not-yet-deployed app only mutates it locally, and skipping + // those would read as unused in the case where it is picked up front. + logFeatureUsage('app_sandbox', 'toggled', { + key: `${rawApp ? 'raw' : 'low_code'}:${e.detail ? 'on' : 'off'}` + }) + // Frontend API access exists only for a sandboxed app, so turning + // isolation off drops the declared scopes with it rather than leaving + // them set but inert. + if (!e.detail) { + policy.frontend_sdk_scopes = undefined + } + // A not-yet-deployed app has no row to PATCH — `setPublishState` (POST + // /apps/update) would 404. The flag rides along in the `policy` the first + // deploy sends (createApp), so here we only mutate it locally. Persist + // incrementally once the app exists. + if (savedApp && !newApp) { + setPublishState(e.detail ? 'Sandbox isolation enabled' : 'Sandbox isolation disabled') + } + }} + disabled={!savedApp || $operatorBuilderApps} + /> + {#if $operatorBuilderApps || newApp} + <div class="text-2xs text-secondary mt-1"> + {#if $operatorBuilderApps} + Required for apps built by operators, and cannot be turned off. + {/if} + {#if newApp} + Takes effect when you first deploy this app. + {/if} </div> {/if} - - <div class="mt-4"> - {#if !(actingUser?.is_admin || actingUser?.is_super_admin)} - <Alert type="warning" title="Admin only" size="xs"> - Custom path can only be set by workspace admins + {#if !$operatorBuilderApps && policy.sandbox != true} + <div class="mt-3"> + <Alert type="warning" title="Not isolated" size="xs"> + The app's frontend code runs with each viewer's full Windmill permissions. A future + version will ask viewers to approve this. Keep isolation off only if the app needs it. </Alert> - <div class="mb-2"></div> - {/if} - <!-- svelte-ignore block_empty --> - {#if !$enterpriseLicense} - <EEOnly /> - {/if} - <Toggle - on:change={({ detail }) => { - customPath = detail ? '' : undefined - if (customPath === undefined) { - customPathError = '' - } - }} - checked={customPath !== undefined} - options={{ - right: 'Use a custom URL' - }} - disabled={!$enterpriseLicense || !(actingUser?.is_admin || actingUser?.is_super_admin)} - /> + </div> + {/if} - {#if customPath !== undefined} - <div class="text-secondary text-sm flex items-center gap-1 w-full justify-between"> - <div>Custom path</div> - </div> - <input - disabled={!(actingUser?.is_admin || actingUser?.is_super_admin)} - type="text" - autocomplete="off" - bind:value={customPath} - class={customPathError === '' - ? '' - : 'border border-red-700 bg-red-100 border-opacity-30 focus:border-red-700 focus:border-opacity-30 focus-visible:ring-red-700 focus-visible:ring-opacity-25 focus-visible:border-red-700'} - oninput={() => { - dirtyCustomPath = true - }} - /> - <div class="text-secondary text-sm flex items-center gap-1 mt-2 w-full justify-between"> - <div>Custom public URL</div> - </div> - <ClipboardPanel - content={embedMode ? toEmbedSnippet(fullCustomUrl) : fullCustomUrl} - size="md" - /> + {#if rawApp && policy.sandbox == true} + <div class="mt-6"> + <Section + label="Frontend API access" + small + collapsable + tooltip="Each viewer approves these scopes before the app runs. The app's code, or an XSS bug in it, can use them as that viewer." + > + {#snippet badge()} + {#if sdkScopesToConfirm(policy.frontend_sdk_scopes ?? []).length} + <div class="flex grow min-w-0 flex-wrap gap-1 ps-2"> + {#each FRONTEND_SDK_SCOPES.filter( (s) => policy.frontend_sdk_scopes.includes(s.value) ) as scope (scope.value)} + <Badge twBgColor="bg-surface-sunken" twTextColor="text-primary" + >{scope.label}</Badge + > + {/each} + </div> + {/if} + {/snippet} + <div class="text-xs text-secondary mb-3"> + Let the app's frontend call the Windmill API as <b>the viewer</b> through the + <code>windmill-client</code> SDK, which it lists as a dependency. Grant only what the app + needs. + </div> + <div class="flex flex-col gap-2"> + {#each FRONTEND_SDK_SCOPES as scope (scope.value)} + <div> + <Toggle + size="xs" + options={{ right: scope.label }} + checked={policy.frontend_sdk_scopes?.includes(scope.value) ?? false} + on:change={(e) => { + const current: string[] = policy.frontend_sdk_scopes ?? [] + const next = e.detail + ? [...current, scope.value] + : current.filter((s) => s !== scope.value) + // Keep the curated order so the consent banner and the stored + // consent compare stably across deploys. A leftover implicit scope is + // not in the list, so it drops here rather than keep minting a token + // for an app whose toggles all read off. + const ordered = FRONTEND_SDK_SCOPES.map((s) => s.value).filter((s) => + next.includes(s) + ) + policy.frontend_sdk_scopes = ordered.length > 0 ? ordered : undefined + // Same as sandbox: a not-yet-deployed app has no row to PATCH, so the + // scopes ride along in the first deploy's policy instead. + if (savedApp && !newApp) { + setPublishState('Frontend API access updated') + } + }} + disabled={!savedApp} + /> + <div class="text-2xs text-hint ml-9">{scope.description}</div> + </div> + {/each} + </div> + {#if sdkScopesToConfirm(policy.frontend_sdk_scopes ?? []).length} + <div class="mt-3"> + <Alert type="info" title="Redeploy to use the SDK from a sandboxed app" size="xs"> + A sandboxed app calls the API cross-origin, which older <code>windmill-client</code> + versions cannot do. An app bundled before this Windmill version fails with a CORS error + until you deploy it again, which re-bundles it against a current client. + </Alert> + </div> + {/if} + </Section> + </div> + {/if} + </Section> - <div class="text-red-600 dark:text-red-400 text-2xs mt-1.5" - >{dirtyCustomPath ? customPathError : ''} + {#if !hideSecretUrl} + <Section label="Access"> + <div class="flex flex-col gap-2"> + {#if rulesetsLoaded && !canSetAnonymous && policy.execution_mode != 'anonymous'} + <Alert type="warning" title="Restricted by a workspace protection rule" size="xs"> + Opening this app to anyone with the link is restricted to workspace admins and bypass + users by a workspace protection rule + </Alert> + {/if} + {#if rulesetsLoaded && !canSetGuest && policy.execution_mode != 'guest' && guestsAvailable} + <Alert type="warning" title="Restricted by a workspace protection rule" size="xs"> + Opening this app to guests is restricted to workspace admins and bypass users by a + workspace protection rule + </Alert> + {/if} + <div> + <ToggleButtonGroup + selected={accessMode} + on:selected={(e) => onAccessModeChange(e.detail)} + disabled={!savedApp} + > + {#snippet children({ item })} + <ToggleButton + label="Members" + value="publisher" + tooltip="Workspace members with read access on this app." + {item} + /> + <ToggleButton + label="Guests" + value="guest" + disabled={policy.execution_mode != 'guest' && (!guestsAvailable || !canSetGuest)} + tooltip={!guestsAvailable + ? 'Not available on Windmill Cloud. Guests require a self-hosted instance or a dedicated Windmill Cloud deployment.' + : "Anyone your identity provider authenticates who has no Windmill account, plus workspace members. No membership, no seat up to the instance's allowance."} + {item} + /> + <ToggleButton + label="Public" + value="anonymous" + disabled={!canSetAnonymous && policy.execution_mode != 'anonymous'} + tooltip="Anyone with the secret URL. No login." + {item} + /> + {/snippet} + </ToggleButtonGroup> + </div> + <div class="text-xs text-secondary"> + {#if policy.execution_mode == 'anonymous'} + Anyone holding the secret URL below can open this app without signing in. + {:else if policy.execution_mode == 'guest'} + {#if !guestsAvailable} + Guests are not available on Windmill Cloud, so this app still admits members only. + They require a self-hosted instance or a dedicated Windmill Cloud deployment. + {:else if guestUsage && !guestUsage.instance_enabled} + A superadmin has turned guests off for this instance, so this app still admits members + only. + {:else if guestAccessEnabled === undefined} + Checking whether this workspace allows guests… + {:else if guestAccessEnabled === false} + Guests are turned off for this workspace, so this app still admits members only. A + workspace admin can turn them on in the workspace settings. + {:else} + Anyone your identity provider authenticates can open this app without a Windmill + account. They join no workspace. Members of this workspace can open it too. + {#if guestUsage} + {guestUsage.guest_count} of {guestUsage.free_allowance} free guests used across this + instance in the last {guestUsage.window_days} days; beyond that, {guestUsage.metered + ? 'every four guests count as one seat' + : 'new guests are refused until the count drops'}. + {/if} + {/if} + {:else} + Only workspace members with read access on this app can open it. + {/if} + </div> + </div> + + <div class="flex flex-col gap-1 mt-6"> + {#if !savedApp || newApp} + <ClipboardPanel content={`Deploy this app once to get the public secret URL`} size="md" /> + {:else if secretUrlHref} + <div class="flex justify-end"> + <Toggle + size="xs" + checked={embedMode} + on:change={(e) => (embedMode = e.detail)} + options={{ left: 'URL', right: 'Embed' }} + /> + </div> + <ClipboardPanel + content={embedMode ? toEmbedSnippet(secretUrlHref) : secretUrlHref} + size="md" + /> + {:else}<Loader2 class="animate-spin" /> + {/if} + <div class="text-2xs text-secondary"> + {#if embedMode} + Paste this iframe snippet into another app. + {#if rawApp} + To embed it in a cross-origin isolated page, add <code>wm_coep=on</code> + <Tooltip + >Sets the cross-origin isolation headers (COEP) on the app, which such a page + requires of its iframes. The app then only loads cross-origin resources that send + CORS or a Cross-Origin-Resource-Policy header.</Tooltip + > to the URL. + {/if} + (if requiring login, top-level domain of embedding app must be the same as the one of Windmill) + {:else} + Share this URL directly, or switch to <b>Embed</b> to get an iframe snippet. Only the latest + deployed version is served. + {/if} + </div> + </div> + + {#if embedMode && policy.execution_mode == 'guest' && guestAccessEnabled && guestJwtBase && guestsAvailable} + <div class="mt-6 flex flex-col gap-2"> + <div class="text-xs font-semibold text-emphasis"> + Embed for your own authenticated users (guest JWT) + </div> + <div class="text-xs text-secondary"> + To open this app for a user your own product already authenticates, mint a short-lived + JWT in your backend and append it to the app URL as <code>guest.<jwt></code>. Each + token is its own seatless guest, confined to this app. Unlike the plain secret URL + above, there is no shared secret and no Windmill account. + </div> + <div class="text-xs text-secondary"> + Windmill verifies the token against the workspace's guest JWT key (Workspace settings → + Guests): a PEM public key or a JWKS URL{#if !isCloudHosted()}, or the instance's + configured issuer (<code>JWT_EXT_JWKS_URL</code>) when no workspace key is set{/if}. + Set the <b>public</b> half there; in your backend, sign each token with the matching + <b>private</b> key using RS256/384/512, PS256/384/512 or ES256/384 (symmetric HS* is + refused), carrying <code>email</code>, <code>workspace_id</code> = <code>{opWs}</code>, + <code>app_path</code> = <code>{appPath}</code> and <code>exp</code> (at most 24h ahead). + </div> + <ClipboardPanel + content={toEmbedSnippet(`${guestJwtBase}/guest.YOUR_GUEST_JWT`)} + size="md" + /> + <div class="text-2xs text-secondary"> + Replace <code>YOUR_GUEST_JWT</code> with the token your backend signs per user. Past the + instance's free guest allowance a new guest email is refused (see the count above); guests + already seen in the window keep working. + </div> </div> {/if} - </div> - </div> - <Alert type="info" title="Only latest deployed app is publicly available"> - You will still need to deploy the app to make visible the latest changes - </Alert> - <a - href="https://www.windmill.dev/docs/advanced/external_auth_with_jwt#embed-public-apps-using-your-own-authentification" - class="mt-4 text-2xs">Embed this app in your own product to be used by your own users</a - > -{/if} + <div class="flex flex-col gap-2 mt-6"> + {#if !(actingUser?.is_admin || actingUser?.is_super_admin)} + <Alert type="warning" title="Admin only" size="xs"> + Custom path can only be set by workspace admins + </Alert> + {/if} + <div class="flex items-center gap-2"> + <Toggle + on:change={({ detail }) => { + customPath = detail ? '' : undefined + if (customPath === undefined) { + customPathError = '' + } + }} + checked={customPath !== undefined} + options={{ + right: 'Use a custom URL' + }} + disabled={!$enterpriseLicense || !(actingUser?.is_admin || actingUser?.is_super_admin)} + /> + {#if !$enterpriseLicense} + <EEOnly /> + {/if} + </div> + + {#if customPath !== undefined} + <div class="flex flex-col gap-1"> + <label for="customPath" class="text-emphasis text-xs font-semibold">Custom path</label> + <TextInput + inputProps={{ + id: 'customPath', + autocomplete: 'off', + disabled: !(actingUser?.is_admin || actingUser?.is_super_admin), + oninput: () => { + dirtyCustomPath = true + } + }} + bind:value={customPath} + error={dirtyCustomPath ? customPathError : undefined} + /> + {#if dirtyCustomPath && customPathError} + <div class="text-2xs text-red-600 dark:text-red-400">{customPathError}</div> + {/if} + </div> + <div class="flex flex-col gap-1"> + <div class="text-emphasis text-xs font-semibold">Custom public URL</div> + <ClipboardPanel + content={embedMode ? toEmbedSnippet(fullCustomUrl) : fullCustomUrl} + size="md" + /> + </div> + {/if} + </div> + + <a + href="https://www.windmill.dev/docs/advanced/external_auth_with_jwt#embed-public-apps-using-your-own-authentification" + class="block mt-6 text-2xs" + >Embed this app in your own product to be used by your own users</a + > + </Section> + {/if} +</div> diff --git a/frontend/src/lib/components/apps/editor/AppReportsDrawerInner.svelte b/frontend/src/lib/components/apps/editor/AppReportsDrawerInner.svelte index d77deb6579..672d8dd6e6 100644 --- a/frontend/src/lib/components/apps/editor/AppReportsDrawerInner.svelte +++ b/frontend/src/lib/components/apps/editor/AppReportsDrawerInner.svelte @@ -15,7 +15,6 @@ WorkspaceService } from '$lib/gen' import { workspaceStore } from '$lib/stores' - import { base } from '$lib/base' import { emptyString, formatCron, sendUserToast, tryEvery } from '$lib/utils' import SchemaForm from '$lib/components/SchemaForm.svelte' import Button from '$lib/components/common/button/Button.svelte' @@ -644,7 +643,7 @@ <p class="text-clip grow min-w-0"> The workspace needs to be connected to Slack to use this feature. You can <a target="_blank" - href="{base}/workspace_settings?tab=slack">configure it here</a + href="/workspace_settings?tab=slack">configure it here</a >. </p> <Button diff --git a/frontend/src/lib/components/apps/editor/InWorkspaceAppViewer.svelte b/frontend/src/lib/components/apps/editor/InWorkspaceAppViewer.svelte index cb56b37498..0d4fb03704 100644 --- a/frontend/src/lib/components/apps/editor/InWorkspaceAppViewer.svelte +++ b/frontend/src/lib/components/apps/editor/InWorkspaceAppViewer.svelte @@ -9,7 +9,6 @@ * untrusted markup/JS must not run with the member's full session — hence the * scoped embed token / opaque isolation. */ - import { base } from '$lib/base' import { sendUserToast } from '$lib/toast' import PublicApp from '$lib/components/apps/editor/PublicApp.svelte' import PublicAppFrame from '$lib/components/apps/editor/PublicAppFrame.svelte' @@ -19,16 +18,13 @@ import type { Item } from '$lib/utils' import { Button } from '$lib/components/common' import { AppService, OpenAPI } from '$lib/gen' - import { userStore, type UserExt } from '$lib/stores' - import { canWrite } from '$lib/utils' + import { userStore, workspaceStore, type UserExt } from '$lib/stores' import { getUserExt } from '$lib/user' import { ExternalLink, Pen } from 'lucide-svelte' import { page } from '$app/state' import { isMenuHidden } from '$lib/components/sessions/sessionMode.svelte' - import { - setOperatingWorkspace, - useOperatingUser - } from '$lib/components/operatingWorkspace.svelte' + import { setOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + import { useEditRights } from '$lib/operatorWriteRights' let { workspace, @@ -58,7 +54,6 @@ // The app, its permission check and everything this viewer renders belong to `workspace`, // which on a session preview tab is the session's and not the one the nav points at. setOperatingWorkspace(() => workspace) - const operatingUser = useOperatingUser() /** This workspace's membership for the viewer, which is what the app's `ctx.username` / * `ctx.groups` must describe — they sit beside `ctx.workspace` in the same object. */ @@ -72,21 +67,25 @@ let appPerms = $state<{ path: string; extraPerms: Record<string, boolean> } | undefined>( undefined ) - const canWriteApp = $derived( - !!appPerms && canWrite(appPerms.path, appPerms.extraPerms, operatingUser.current) - ) /** Raw vs low-code, read from the app itself rather than from the route: * both kinds render here and either route serves either kind (links to a raw * app point at /apps/get all over the app), so only the app can say which * editor the Edit button must open. */ let isRawApp = $state(false) + const editRights = useEditRights() + const canWriteApp = $derived( + !!appPerms && + editRights.canEditItem(isRawApp ? 'raw_app' : 'app', appPerms.path, appPerms.extraPerms) + ) /** The app's execution mode, from the same lite read as the permissions and for the same * reason: a sandboxed low-code app loads inside the opaque iframe, so `app` here stays * undefined and cannot say whether the app answers at a public url. `policy.execution_mode` is * where the lite payload carries it; the flat field beside it is the apps *list* row's * spelling (ListableApp, which is what AppRow reads). */ let executionMode = $state<string | undefined>(undefined) - let editHref = $derived(`${base}/${isRawApp ? 'apps_raw' : 'apps'}/edit/${path}?nodraft=true`) + /** From the lite read too: a sandboxed low-code app never fills `app`. */ + let summary = $state<string | undefined>(undefined) + let editHref = $derived(`/${isRawApp ? 'apps_raw' : 'apps'}/edit/${path}?nodraft=true`) let refresh: (() => void) | undefined // The opaque iframe loads the dedicated cookieless, chrome-less viewer route. @@ -96,7 +95,7 @@ // page's URL (wm_embed_hash relay), and re-deriving the iframe src from them // would reload the app on its every navigation. const initialSearchHash = page.url.search + page.url.hash - let viewerUrl = $derived(`${base}/app_embed/${workspace}/${path}${initialSearchHash}`) + let viewerUrl = $derived(`/app_embed/${workspace}/${path}${initialSearchHash}`) const hideEditBtn = page.url.searchParams.get('hideEditBtn') === 'true' const hideRefreshBar = page.url.searchParams.get('hideRefreshBar') === 'true' @@ -126,8 +125,8 @@ // Viewer side — used for the inline renderings (raw, and unsandboxed low-code); // the sandboxed low-code case loads inside the opaque /app_embed iframe instead. - // getAppByPath returns bundle_secret + runnables for raw apps, which - // PublicApp -> RawAppPreview needs. + // getAppLiteByPath returns the runnables (with their ids) that + // PublicApp -> RawAppPreview needs for raw apps. async function loadApp() { // Kept local and handed to PublicApp rather than written to `userStore`: this is the // membership in `workspace`, and a session preview tab shows a workspace the rest of @@ -137,8 +136,10 @@ // populated `userStore` for the workspace the page *is* on. appUser = await getUserExt(workspace) try { - const loaded: any = await AppService.getAppByPath({ workspace, path }) - // Raw apps need the bundle secret to load their bundle. getAppByPath + // The lite value: its inline scripts carry the ids of their deployed rows, the only + // code a deployed app runs (with its lock, and a raw app's imported runnables). + const loaded: any = await AppService.getAppLiteByPath({ workspace, path }) + // Raw apps need the bundle secret to load their bundle. getAppLiteByPath // doesn't compute it (unlike the public handlers), so fetch it here — the // same call the previous raw viewer used — and hand it to PublicApp -> // RawAppPreview via bundle_secret. @@ -177,8 +178,10 @@ appPerms = { path: lite?.path ?? path, extraPerms: lite?.extra_perms ?? {} } isRawApp = !!lite?.raw_app executionMode = lite?.policy?.execution_mode ?? lite?.execution_mode + summary = lite?.summary || undefined } catch (_) { appPerms = undefined + summary = undefined } } @@ -202,7 +205,7 @@ } // Built from this viewer's workspace rather than the navigation one, like everything // else here: the two differ inside a session's preview panel. - const url = `${window.location.origin}${base}/public/${workspace}/${secret}` + const url = `${window.location.origin}/public/${workspace}/${secret}` if (tab) tab.location.href = url else sendUserToast('Allow pop-ups for this site to open the app’s public url', true) } catch (e: any) { @@ -251,7 +254,7 @@ <PublicApp {app} {workspace} - user={appUser ?? $userStore} + user={appUser ?? (workspace === $workspaceStore ? $userStore : undefined)} {notExists} {noPermission} jwtError={false} @@ -268,7 +271,7 @@ no item, and the breadcrumb would fall back to the section name "Apps". --> {#if ownsPageHeader} <PageHeaderContent - item={{ kind: 'app', path }} + item={{ kind: 'app', path, summary }} actions={showEdit && !menuHidden ? editAction : undefined} separator="always" /> diff --git a/frontend/src/lib/components/apps/editor/PublicAppAccess.svelte b/frontend/src/lib/components/apps/editor/PublicAppAccess.svelte index 9a993b4972..5e1d80b893 100644 --- a/frontend/src/lib/components/apps/editor/PublicAppAccess.svelte +++ b/frontend/src/lib/components/apps/editor/PublicAppAccess.svelte @@ -1,5 +1,4 @@ <script lang="ts"> - import { base } from '$app/paths' import { page } from '$app/state' import Login from '$lib/components/Login.svelte' import Alert from '$lib/components/common/alert/Alert.svelte' @@ -44,7 +43,7 @@ {#if notExists} <div class="px-4 mt-20" ><Alert type="error" title="Not found" - >There was an error loading the app, is the url correct? <a href={base}>Go to Windmill</a> + >There was an error loading the app, is the url correct? <a href="/">Go to Windmill</a> </Alert></div > {:else} diff --git a/frontend/src/lib/components/apps/editor/PublicAppFrame.svelte b/frontend/src/lib/components/apps/editor/PublicAppFrame.svelte index dbb9b4b88b..4c391c0336 100644 --- a/frontend/src/lib/components/apps/editor/PublicAppFrame.svelte +++ b/frontend/src/lib/components/apps/editor/PublicAppFrame.svelte @@ -27,7 +27,6 @@ import { page } from '$app/state' import { onDestroy, onMount, setContext, type Snippet } from 'svelte' import Skeleton from '$lib/components/common/skeleton/Skeleton.svelte' - import { base } from '$app/paths' import { goto } from '$app/navigation' import { WINDMILL_RESERVED_QUERY_PARAMS } from '$lib/utils/queryParams' import { EMBED_NAV_CONTEXT_KEY, type EmbedNav } from '../types' @@ -195,21 +194,38 @@ // Top-level navigation relay (WIN-2006): in-app links to other apps (navbar // "app" items) must navigate the top page — navigating inside the opaque // iframe would load the SPA cookieless. Consumed by PublicApp via gotoFn. - setContext<EmbedNav | undefined>( - EMBED_NAV_CONTEXT_KEY, - isViewer - ? { - navigateTop: (href: string) => { - try { - window.parent.postMessage( - { type: 'wm_embed_navigate', href }, - expectedEmbedderOrigin ?? '*' - ) - } catch (_) {} - } - } - : undefined - ) + function navigateTop(href: string) { + try { + window.parent.postMessage({ type: 'wm_embed_navigate', href }, expectedEmbedderOrigin ?? '*') + } catch (_) {} + } + setContext<EmbedNav | undefined>(EMBED_NAV_CONTEXT_KEY, isViewer ? { navigateTop } : undefined) + + // Plain links (markdown, HTML components) would otherwise load inside the + // cookieless frame, or put an external site in it. Bound on <body> so the link's own + // handlers run first and can cancel it, and before SvelteKit's router on <html>, + // which skips a prevented click. A link to this same page only changes ?query/#hash, + // which the hash relay mirrors, so it stays in the frame. + function relayLinkClick(e: MouseEvent) { + if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) + return + // Attributes, not properties: on an SVG <a> those are SVGAnimatedString. + const a = (e.target as Element | null)?.closest?.('a[href]') + const target = a?.getAttribute('target') + if ( + !a || + a.hasAttribute('download') || + (target && !['_self', '_top', '_parent'].includes(target)) + ) + return + const url = new URL(a.getAttribute('href')!, document.baseURI) + // The embedder only relays http(s); mailto:, tel: and the like work in the frame. + if (url.protocol !== 'http:' && url.protocol !== 'https:') return + const sameOrigin = url.origin === window.location.origin + if (sameOrigin && url.pathname === window.location.pathname) return + e.preventDefault() + navigateTop(sameOrigin ? url.pathname + url.search + url.hash : url.href) + } function installHashRelay() { origPushState = history.pushState origReplaceState = history.replaceState @@ -569,6 +585,7 @@ loadAppPreview().catch(() => {}) window.addEventListener('message', handleViewerMessage) installHashRelay() + document.body.addEventListener('click', relayLinkClick) // Announce readiness so the embedder sends us the token. window.parent.postMessage({ type: 'wm_embed_ready' }, expectedEmbedderOrigin ?? '*') // This page is only ever loaded as the embedder's opaque iframe, which @@ -590,7 +607,10 @@ if (!BROWSER) return window.removeEventListener('message', handleViewerMessage) window.removeEventListener('message', handleEmbedderMessage) - if (isViewer) uninstallHashRelay() + if (isViewer) { + uninstallHashRelay() + document.body.removeEventListener('click', relayLinkClick) + } }) </script> @@ -647,7 +667,7 @@ <div class="px-4 mt-20"> <Alert type="error" title="Not found"> There was an error loading the app, is the url correct? - <a href={base}>Go to Windmill</a> + <a href="/">Go to Windmill</a> </Alert> </div> {:else if status === 'sdkPrompt'} diff --git a/frontend/src/lib/components/apps/editor/appDeploy.svelte.ts b/frontend/src/lib/components/apps/editor/appDeploy.svelte.ts index f799cb864a..5c22e3f475 100644 --- a/frontend/src/lib/components/apps/editor/appDeploy.svelte.ts +++ b/frontend/src/lib/components/apps/editor/appDeploy.svelte.ts @@ -1,7 +1,6 @@ -import { base } from '$lib/base' import { workspaceStore } from '$lib/stores' import { get } from 'svelte/store' export function computeSecretUrl(secretUrl: string) { - return `${window.location.origin}${base}/public/${get(workspaceStore)}/${secretUrl}` + return `${window.location.origin}/public/${get(workspaceStore)}/${secretUrl}` } diff --git a/frontend/src/lib/components/apps/editor/commonAppUtils.ts b/frontend/src/lib/components/apps/editor/commonAppUtils.ts index 564a94e9b1..b384fafce5 100644 --- a/frontend/src/lib/components/apps/editor/commonAppUtils.ts +++ b/frontend/src/lib/components/apps/editor/commonAppUtils.ts @@ -17,6 +17,8 @@ export type TriggerableV2 = { delete_after_secs?: number sensitive_inputs?: string[] tag?: string + /** Data table connections naming no role are made as the app's viewer. Inline runnables only. */ + viewer_data_access?: boolean } export async function hash(message) { diff --git a/frontend/src/lib/components/apps/editor/inlineScriptsPanel/EmptyInlineScript.svelte b/frontend/src/lib/components/apps/editor/inlineScriptsPanel/EmptyInlineScript.svelte index a4bed4affb..1d3d46fc35 100644 --- a/frontend/src/lib/components/apps/editor/inlineScriptsPanel/EmptyInlineScript.svelte +++ b/frontend/src/lib/components/apps/editor/inlineScriptsPanel/EmptyInlineScript.svelte @@ -15,6 +15,7 @@ import WorkspaceScriptList from '../settingsPanel/mainInput/WorkspaceScriptList.svelte' import RunnableSelector from '../settingsPanel/mainInput/RunnableSelector.svelte' import { defaultScripts } from '$lib/stores' + import { useOperatorBuilderApps } from '$lib/operatorWriteRights' import DefaultScripts from '$lib/components/DefaultScripts.svelte' import type { Preview } from '$lib/gen' import type { InlineScript } from '../../sharedTypes' @@ -38,6 +39,7 @@ let picker: Drawer | undefined = $state(undefined) const dispatch = createEventDispatcher() + const operatorBuilderApps = useOperatorBuilderApps() async function inferInlineScriptSchema( language: Preview['language'], @@ -104,7 +106,9 @@ <Tabs bind:selected={tab}> <Tab value="workspacescripts" label="Workspace Scripts" icon={Building} /> - <Tab value="hubscripts" label="Hub Scripts" icon={Globe2} /> + {#if !$operatorBuilderApps} + <Tab value="hubscripts" label="Hub Scripts" icon={Globe2} /> + {/if} </Tabs> <div class="my-2"></div> <div class="flex flex-col gap-y-16"> @@ -123,21 +127,25 @@ <div class="flex flex-col px-4 gap-2 text-sm" id="app-editor-empty-runnable"> <div class="mt-2 flex justify-between gap-4" id="app-editor-runnable-header"> - <div class="font-bold items-baseline truncate">Choose a language</div> + <div class="font-bold items-baseline truncate"> + {$operatorBuilderApps ? 'Choose a script or flow' : 'Choose a language'} + </div> <div class="flex gap-2"> {#if showScriptPicker} <RunnableSelector {unusedInlineScripts} {rawApps} on:pick hideCreateScript /> {/if} - <Button - on:click={() => picker?.openDrawer()} - size="xs" - variant="border" - color="light" - startIcon={{ icon: GitFork }} - btnClasses="truncate" - > - Fork other script - </Button> + {#if !$operatorBuilderApps} + <Button + on:click={() => picker?.openDrawer()} + size="xs" + variant="border" + color="light" + startIcon={{ icon: GitFork }} + btnClasses="truncate" + > + Fork other script + </Button> + {/if} <Button on:click={() => dispatch('delete')} @@ -151,7 +159,9 @@ </div> </div> - <div class="flex flex-row w-full gap-8"> + <!-- Operators with builder rights compose runnables that already exist: the language pickers + below all author code, which the backend refuses from them. --> + <div class="flex flex-row w-full gap-8" class:hidden={$operatorBuilderApps}> <div id="app-editor-backend-runnables"> <div class="mb-1 text-sm font-semibold flex gap-4">Backend <DefaultScripts /> </div> diff --git a/frontend/src/lib/components/apps/editor/inlineScriptsPanel/InlineScriptEditor.svelte b/frontend/src/lib/components/apps/editor/inlineScriptsPanel/InlineScriptEditor.svelte index b1af1c20f7..0f62f0b4cd 100644 --- a/frontend/src/lib/components/apps/editor/inlineScriptsPanel/InlineScriptEditor.svelte +++ b/frontend/src/lib/components/apps/editor/inlineScriptsPanel/InlineScriptEditor.svelte @@ -6,7 +6,8 @@ import type { Preview } from '$lib/gen' import { createEventDispatcher, getContext, onMount, untrack } from 'svelte' import type { AppViewerContext } from '../../types' - import { Maximize2, Trash2 } from 'lucide-svelte' + import { Maximize2, Paintbrush, Trash2 } from 'lucide-svelte' + import { getModifierKey } from '$lib/utils' import InlineScriptEditorDrawer from './InlineScriptEditorDrawer.svelte' import { inferArgs, parseOutputs } from '$lib/infer' import type { Schema } from '$lib/common' @@ -305,18 +306,17 @@ {/if} <Button - variant="default" + title={`Format (${getModifierKey()}S)`} + aria-label="Format" + variant="subtle" unifiedSize="sm" on:click={async () => { editor?.format() simpleEditor?.format() }} - shortCut={{ - key: 'S' - }} - > - Format - </Button> + endIcon={{ icon: Paintbrush }} + iconOnly + /> <RunButton bind:runLoading {id} inlineScript={!transformer ? inlineScript : undefined} /> </div> </div> diff --git a/frontend/src/lib/components/apps/editor/inlineScriptsPanel/InlineScriptRunnableByPath.svelte b/frontend/src/lib/components/apps/editor/inlineScriptsPanel/InlineScriptRunnableByPath.svelte index 293d83b4ae..45dbe82c14 100644 --- a/frontend/src/lib/components/apps/editor/inlineScriptsPanel/InlineScriptRunnableByPath.svelte +++ b/frontend/src/lib/components/apps/editor/inlineScriptsPanel/InlineScriptRunnableByPath.svelte @@ -3,7 +3,6 @@ const bubble = createBubbler() import { Button, Drawer, DrawerContent } from '$lib/components/common' - import { base } from '$lib/base' import FlowGraphViewer from '$lib/components/FlowGraphViewer.svelte' import Skeleton from '$lib/components/common/skeleton/Skeleton.svelte' import FlowModuleScript from '$lib/components/flows/content/FlowModuleScript.svelte' @@ -19,6 +18,7 @@ CtxAppInput } from '../../inputType' import type { AppViewerContext } from '../../types' + import { useOperatorBuilderApps } from '$lib/operatorWriteRights' import { createEventDispatcher } from 'svelte' import { deepEqual } from 'fast-equals' import { computeFields } from './utils' @@ -37,6 +37,7 @@ import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' const operatingWorkspace = useOperatingWorkspace() + const operatorBuilderApps = useOperatorBuilderApps() interface Props { runnable: RunnableByPath @@ -325,7 +326,7 @@ startIcon={{ icon: GitFork }} endIcon={{ icon: ExternalLink }} target="_blank" - href="{base}/flows/add?hub={hubFlowId}" + href="/flows/add?hub={hubFlowId}" > Fork </Button> @@ -346,7 +347,7 @@ startIcon={{ icon: Eye }} endIcon={{ icon: ExternalLink }} target="_blank" - href="{base}/flows/get/{runnable.path}?workspace={$operatingWorkspace}" + href="/flows/get/{runnable.path}?workspace={$operatingWorkspace}" > Details </Button> @@ -362,16 +363,18 @@ > Edit </Button> - <Button - size="xs" - variant="default" - startIcon={{ icon: GitFork }} - on:click={() => { - fork(runnable.path) - }} - > - Fork - </Button> + {#if !$operatorBuilderApps} + <Button + size="xs" + variant="default" + startIcon={{ icon: GitFork }} + on:click={() => { + fork(runnable.path) + }} + > + Fork + </Button> + {/if} {/if} <Popover floatingConfig={{ diff --git a/frontend/src/lib/components/apps/editor/settingsPanel/mainInput/RunnableSelector.svelte b/frontend/src/lib/components/apps/editor/settingsPanel/mainInput/RunnableSelector.svelte index 08b8ac6219..44f2adb9ac 100644 --- a/frontend/src/lib/components/apps/editor/settingsPanel/mainInput/RunnableSelector.svelte +++ b/frontend/src/lib/components/apps/editor/settingsPanel/mainInput/RunnableSelector.svelte @@ -12,8 +12,10 @@ import { emptySchema } from '$lib/utils' import { loadSchema } from '$lib/infer' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + import { useOperatorBuilderApps } from '$lib/operatorWriteRights' const operatingWorkspace = useOperatingWorkspace() + const operatorBuilderApps = useOperatorBuilderApps() import { buildPathRunnableSelection } from './runnableSelectorUtils' type TabType = 'hubscripts' | 'hubflows' | 'workspacescripts' | 'workspaceflows' | 'inlinescripts' @@ -163,10 +165,12 @@ <Tab value="workspacescripts" label="Workspace Scripts" icon={Building} /> {/if} <Tab value="workspaceflows" label="Workspace Flows" icon={Building} /> - {#if !onlyFlow} - <Tab value="hubscripts" label="Hub Scripts" icon={Globe2} /> + {#if !$operatorBuilderApps} + {#if !onlyFlow} + <Tab value="hubscripts" label="Hub Scripts" icon={Globe2} /> + {/if} + <Tab value="hubflows" label="Hub Flows" icon={Globe2} /> {/if} - <Tab value="hubflows" label="Hub Flows" icon={Globe2} /> </Tabs> <div class="my-2"></div> <div class="flex flex-col gap-y-16"> diff --git a/frontend/src/lib/components/assets/AssetGraph/AddDataSourceMenu.svelte b/frontend/src/lib/components/assets/AssetGraph/AddDataSourceMenu.svelte new file mode 100644 index 0000000000..49a222148b --- /dev/null +++ b/frontend/src/lib/components/assets/AssetGraph/AddDataSourceMenu.svelte @@ -0,0 +1,150 @@ +<!-- +@component +The menu that adds a pipeline script started by a data source (a schedule, a +webhook, a queue…): the add node's, and the canvas's right-click one. +--> +<script lang="ts"> + import type { Snippet } from 'svelte' + import PipelineInsertMenu, { + type PipelineInsertOptions, + type PipelineInsertPick + } from './PipelineInsertMenu.svelte' + import { + Clock, + Webhook, + Mail, + Zap, + Radio, + MessageSquare, + Database, + Send, + CloudCog, + Upload + } from 'lucide-svelte' + import type { ScriptLang } from '$lib/gen' + import type { NativeTriggerKind } from './types' + import { PIPELINE_LANGUAGES } from './pipelineLanguages' + import type { PipelineOutputKind } from './pipelineTemplates' + + interface Props { + onAddPipelineScript: ( + language: ScriptLang, + path: string, + source: { kind: NativeTriggerKind; path: string | undefined }, + outputKind: PipelineOutputKind, + aiPrompt?: string, + options?: PipelineInsertOptions + ) => void + pathPrefix: string + defaultPathSuffix: string + trigger: Snippet<[{ open: boolean }]> + /** Opens the menu each time it changes. */ + openSignal?: number + } + let { + onAddPipelineScript, + pathPrefix, + defaultPathSuffix, + trigger, + openSignal + }: Props = $props() + + function handlePick(pick: PipelineInsertPick) { + if (!pick.language || !pick.path) return + // Native trigger annotation is marker-only — the binding lives on the + // trigger row's own `script_path`, which is created separately. + onAddPipelineScript( + pick.language as ScriptLang, + pick.path, + { kind: pick.kindId as NativeTriggerKind, path: undefined }, + (pick.outputKind ?? 'none') as PipelineOutputKind, + pick.aiPrompt, + { schedule: pick.schedule, outputAsset: pick.outputAsset } + ) + } +</script> + +<PipelineInsertMenu + kinds={[ + { + id: 'data_upload', + label: 'On data upload', + description: 'UI-first: run by uploading a file via the S3 picker', + icon: Upload + }, + { + id: 'schedule', + label: 'On schedule', + description: 'Triggered by a schedule you create', + icon: Clock + }, + { + id: 'webhook', + label: 'On webhook', + description: 'Triggered by an HTTP webhook', + icon: Webhook + }, + { + id: 'email', + configuredAfterCreate: true, + label: 'On email', + description: 'Triggered by incoming email', + icon: Mail + }, + { + id: 'kafka', + configuredAfterCreate: true, + label: 'On Kafka', + description: 'Triggered by a Kafka message', + icon: Zap + }, + { + id: 'mqtt', + configuredAfterCreate: true, + label: 'On MQTT', + description: 'Triggered by an MQTT message', + icon: Radio + }, + { + id: 'amqp', + configuredAfterCreate: true, + label: 'On AMQP', + description: 'Triggered by an AMQP (RabbitMQ) message', + icon: Radio + }, + { + id: 'nats', + configuredAfterCreate: true, + label: 'On NATS', + description: 'Triggered by a NATS message', + icon: MessageSquare + }, + { + id: 'postgres', + configuredAfterCreate: true, + label: 'On Postgres', + description: 'Triggered by a Postgres event', + icon: Database + }, + { + id: 'sqs', + configuredAfterCreate: true, + label: 'On SQS', + description: 'Triggered by an SQS message', + icon: Send + }, + { + id: 'gcp', + configuredAfterCreate: true, + label: 'On GCP Pub/Sub', + description: 'Triggered by a Pub/Sub message', + icon: CloudCog + } + ]} + languages={PIPELINE_LANGUAGES as any} + {pathPrefix} + {defaultPathSuffix} + onPick={handlePick} + {openSignal} + {trigger} +/> diff --git a/frontend/src/lib/components/assets/AssetGraph/AddDownstreamMenu.svelte b/frontend/src/lib/components/assets/AssetGraph/AddDownstreamMenu.svelte new file mode 100644 index 0000000000..2a54fe11d4 --- /dev/null +++ b/frontend/src/lib/components/assets/AssetGraph/AddDownstreamMenu.svelte @@ -0,0 +1,73 @@ +<!-- +@component +The menu adding a pipeline script downstream of an asset: opened from the asset's +"+", or where that "+" was dropped on the blank canvas. +--> +<script lang="ts" module> + import type { ScriptLang } from '$lib/gen' + import type { AssetKind } from '$lib/components/assets/lib' + import type { PipelineInsertOptions } from './PipelineInsertMenu.svelte' + import type { PipelineOutputKind } from './pipelineTemplates' + + export type AddScriptForAsset = ( + asset: { kind: AssetKind; path: string }, + language: ScriptLang, + scriptPath: string, + outputKind: PipelineOutputKind, + aiPrompt?: string, + options?: PipelineInsertOptions + ) => void +</script> + +<script lang="ts"> + import { Code2 } from 'lucide-svelte' + import type { Snippet } from 'svelte' + import PipelineInsertMenu, { type PipelineInsertPick } from './PipelineInsertMenu.svelte' + import { PIPELINE_LANGUAGES } from './pipelineLanguages' + + let { + asset, + onAddScript, + pathPrefix = '', + defaultPathSuffix = '', + openSignal, + trigger + }: { + asset: { kind: AssetKind; path: string } + onAddScript: AddScriptForAsset + pathPrefix?: string + defaultPathSuffix?: string + openSignal?: number + trigger: Snippet<[{ open: boolean }]> + } = $props() + + function handlePick(pick: PipelineInsertPick) { + if (pick.kindId === 'pipeline_script' && pick.language && pick.path) { + onAddScript( + asset, + pick.language as ScriptLang, + pick.path, + (pick.outputKind ?? 'none') as PipelineOutputKind, + pick.aiPrompt, + { outputAsset: pick.outputAsset } + ) + } + } +</script> + +<PipelineInsertMenu + kinds={[ + { + id: 'pipeline_script', + label: 'Add downstream pipeline script', + description: 'Triggered when this asset changes', + icon: Code2 + } + ]} + languages={PIPELINE_LANGUAGES as any} + {pathPrefix} + {defaultPathSuffix} + {openSignal} + onPick={handlePick} + {trigger} +/> diff --git a/frontend/src/lib/components/assets/AssetGraph/AddDownstreamPill.svelte b/frontend/src/lib/components/assets/AssetGraph/AddDownstreamPill.svelte new file mode 100644 index 0000000000..8ebd24455c --- /dev/null +++ b/frontend/src/lib/components/assets/AssetGraph/AddDownstreamPill.svelte @@ -0,0 +1,23 @@ +<!-- +@component +The "+" on an asset's bottom edge: a circle at rest, widened into a labelled pill +while its menu is open or while it is being dragged. The label animates its +max-width (width can't transition to auto) and never wraps. +--> +<script lang="ts"> + import { Plus } from 'lucide-svelte' + + let { expanded }: { expanded: boolean } = $props() +</script> + +<span + class="group/add h-6 min-w-6 rounded-full flex items-center justify-center bg-surface border border-gray-400 dark:border-gray-600 text-secondary hover:text-primary hover:border-gray-500 shadow-sm leading-none overflow-hidden transition-[padding] duration-200 ease-out data-[open=true]:pl-1" + data-open={expanded} +> + <Plus size={16} strokeWidth={2.5} class="shrink-0" /> + <span + class="max-w-0 opacity-0 whitespace-nowrap text-3xs font-normal transition-[max-width,opacity,margin] duration-200 ease-out group-data-[open=true]/add:max-w-32 group-data-[open=true]/add:opacity-100 group-data-[open=true]/add:ml-1 group-data-[open=true]/add:mr-2" + > + Add downstream step + </span> +</span> diff --git a/frontend/src/lib/components/assets/AssetGraph/AddNode.svelte b/frontend/src/lib/components/assets/AssetGraph/AddNode.svelte index 880abb685a..57a31e34d8 100644 --- a/frontend/src/lib/components/assets/AssetGraph/AddNode.svelte +++ b/frontend/src/lib/components/assets/AssetGraph/AddNode.svelte @@ -1,145 +1,36 @@ <script lang="ts"> - import PipelineInsertMenu, { type PipelineInsertPick } from './PipelineInsertMenu.svelte' - import { - Plus, - Clock, - Webhook, - Mail, - Zap, - Radio, - MessageSquare, - Database, - Send, - CloudCog, - Upload - } from 'lucide-svelte' - import type { ScriptLang } from '$lib/gen' - import type { NativeTriggerKind } from './types' - import { PIPELINE_LANGUAGES } from './pipelineLanguages' - import type { PipelineOutputKind } from './pipelineTemplates' - - // Each left-column kind is just "pipeline script triggered by <trigger - // source>". id === the SCRIPT_TRIGGER_KIND value, so the handler can - // dispatch on it uniformly. Asset-triggered scripts are not in this - // menu; those live under the per-asset + inside the graph. - type KindId = NativeTriggerKind + import AddDataSourceMenu from './AddDataSourceMenu.svelte' + import { Plus } from 'lucide-svelte' + import { NODE } from '$lib/components/graph/util' interface Props { - data: { - onAddPipelineScript: ( - language: ScriptLang, - path: string, - source: { kind: NativeTriggerKind; path: string | undefined }, - outputKind: PipelineOutputKind, - aiPrompt?: string - ) => void - pathPrefix: string - defaultPathSuffix: string - } + data: Pick< + import('svelte').ComponentProps<typeof AddDataSourceMenu>, + 'onAddPipelineScript' | 'pathPrefix' | 'defaultPathSuffix' + > } let { data }: Props = $props() - - function handlePick(pick: PipelineInsertPick) { - if (!pick.language || !pick.path) return - const kindId = pick.kindId as KindId - const outputKind = (pick.outputKind ?? 'none') as PipelineOutputKind - // Native trigger annotation is marker-only — the binding lives on - // the trigger row's own `script_path`, which the user creates - // separately. Seed with `path: undefined`. - data.onAddPipelineScript( - pick.language as ScriptLang, - pick.path, - { kind: kindId, path: undefined }, - outputKind, - pick.aiPrompt - ) - } </script> -<PipelineInsertMenu - kinds={[ - { - id: 'data_upload', - label: 'On data upload', - description: 'UI-first: run by uploading a file via the S3 picker', - icon: Upload - }, - { - id: 'schedule', - label: 'On schedule', - description: 'Triggered by a schedule you create', - icon: Clock - }, - { - id: 'webhook', - label: 'On webhook', - description: 'Triggered by an HTTP webhook', - icon: Webhook - }, - { - id: 'email', - label: 'On email', - description: 'Triggered by incoming email', - icon: Mail - }, - { - id: 'kafka', - label: 'On Kafka', - description: 'Triggered by a Kafka message', - icon: Zap - }, - { - id: 'mqtt', - label: 'On MQTT', - description: 'Triggered by an MQTT message', - icon: Radio - }, - { - id: 'amqp', - label: 'On AMQP', - description: 'Triggered by an AMQP (RabbitMQ) message', - icon: Radio - }, - { - id: 'nats', - label: 'On NATS', - description: 'Triggered by a NATS message', - icon: MessageSquare - }, - { - id: 'postgres', - label: 'On Postgres', - description: 'Triggered by a Postgres event', - icon: Database - }, - { - id: 'sqs', - label: 'On SQS', - description: 'Triggered by an SQS message', - icon: Send - }, - { - id: 'gcp', - label: 'On GCP Pub/Sub', - description: 'Triggered by a Pub/Sub message', - icon: CloudCog - } - ]} - languages={PIPELINE_LANGUAGES as any} - pathPrefix={data.pathPrefix} - defaultPathSuffix={data.defaultPathSuffix} - onPick={handlePick} -> - {#snippet trigger()} - <!-- Quiet insert affordance, mirroring the flow editor's inline + - buttons (bg-surface + gray border + secondary text) — a filled - accent circle outweighed every real node on the canvas. --> - <button - type="button" - class="w-8 h-8 rounded-full flex items-center justify-center bg-surface border border-gray-400 dark:border-gray-600 text-secondary shadow-sm hover:bg-surface-hover transition-colors cursor-pointer" - title="Add to pipeline" - > - <Plus size={16} /> - </button> - {/snippet} -</PipelineInsertMenu> +<!-- The layout gives this node a full node-width slot; centering the pill in + it lines it up with the nodes below whatever its label's width. --> +<div class="flex justify-center" style="width: {NODE.width}px;"> + <AddDataSourceMenu + onAddPipelineScript={data.onAddPipelineScript} + pathPrefix={data.pathPrefix} + defaultPathSuffix={data.defaultPathSuffix} + > + {#snippet trigger()} + <!-- Quiet insert affordance, mirroring the flow editor's inline + + buttons (bg-surface + gray border + secondary text) — a filled + accent pill would outweigh every real node on the canvas. --> + <button + type="button" + class="h-8 px-3 rounded-full flex items-center gap-1.5 whitespace-nowrap bg-surface border border-gray-400 dark:border-gray-600 text-xs font-normal text-secondary shadow-sm hover:bg-surface-hover transition-colors cursor-pointer" + > + <Plus size={16} class="shrink-0" /> + Add data source + </button> + {/snippet} + </AddDataSourceMenu> +</div> diff --git a/frontend/src/lib/components/assets/AssetGraph/AssetGraphCanvas.svelte b/frontend/src/lib/components/assets/AssetGraph/AssetGraphCanvas.svelte index 27f6ce6be7..87b085593c 100644 --- a/frontend/src/lib/components/assets/AssetGraph/AssetGraphCanvas.svelte +++ b/frontend/src/lib/components/assets/AssetGraph/AssetGraphCanvas.svelte @@ -1,8 +1,11 @@ <script lang="ts"> import '@xyflow/svelte/dist/base.css' + import { randomUUID } from '$lib/utils/uuid' + import { onMount } from 'svelte' import { SvelteFlow, Controls, + Panel, MiniMap, ConnectionLineType, type Node, @@ -13,13 +16,47 @@ import RunnableNode from './RunnableNode.svelte' import TriggerNode, { type TriggerNodeKind } from './TriggerNode.svelte' import AddNode from './AddNode.svelte' + import AddDataSourceMenu from './AddDataSourceMenu.svelte' + import PipelineInsertMenu, { type PipelineInsertSchedule } from './PipelineInsertMenu.svelte' + import AddDownstreamMenu from './AddDownstreamMenu.svelte' + import AddDownstreamPill from './AddDownstreamPill.svelte' import DataTestNode from './DataTestNode.svelte' import AssetGraphEdge from './AssetGraphEdge.svelte' import PanToNode from './PanToNode.svelte' import InitialFitView from './InitialFitView.svelte' - import { layoutAssetGraph } from './assetGraphLayout' + import { + layoutAssetGraph, + PIPELINE_NODE_EXTRA_ROW, + PIPELINE_NODE_HEADER, + PIPELINE_NODE_HEADER_CARD_PAD + } from './assetGraphLayout' + import { + assetsOnlyView, + upstreamDeletion, + withoutPassiveReads, + type AssetUpstream, + type AssetUpstreamDelete + } from './assetsOnlyView' + import { assetsOnlyNodeWidth } from './assetNodeWidth' + import { describeEdge } from './edgeDescription' + import { onDirectiveTargets } from './onDirectiveTargets' + import { listenChangeText, stopListeningChangeText } from './pipelineAnnotationEdits' + import { Button } from '$lib/components/common' + import type { NodeFix, NodeFixSpec } from './NodeFixButton.svelte' + import { isAssetsOnlyFolder, setAssetsOnlyFolder } from './assetsOnlyFolders' + import { formatAssetKind, formatShortAssetPath } from '$lib/components/assets/lib' + import { TRIGGER_NODE_STYLE } from './TriggerNode.svelte' + import { describeSchedule } from '$lib/utils/describeCron' + import Toggle from '$lib/components/Toggle.svelte' + import { fly } from 'svelte/transition' + import { Clock, Plus } from 'lucide-svelte' + import { + getContextMenuContainerClass, + CONTEXT_MENU_ITEM_BASE_CLASS, + CONTEXT_MENU_ITEM_HOVER_CLASS + } from '$lib/components/common/contextmenu/contextMenuStyles' import { computeMutedReadKeys, dbtAssociations } from './resolveGraph' - import { buildDownstreamMap } from './graphTraversal' + import { buildDownstreamMap, hoverLineage, transitivelyImpliedEdges } from './graphTraversal' import { buildLineageDownstreamMap } from './boundedCascade' import type { AssetGraphResponse, @@ -31,16 +68,15 @@ import type { AssetKind } from '$lib/gen' import { NODE } from '$lib/components/graph/util' - // Width of the + node's rendered DOM element. Sugiyama allocates a full - // NODE.width slot for every node, so the small round button ends up - // left-aligned in its slot. We compensate by shifting the + node right - // by half the difference so its visual center matches the slot center. - const ADD_NODE_WIDTH = 40 - interface Props { graph: AssetGraphResponse selection?: AssetGraphSelection | undefined - onselect?: (selection: AssetGraphSelection | undefined) => void + /** `open` marks a selection asked to be shown (a script's open button), as + * opposed to a click on a node, which only selects it. */ + onselect?: ( + selection: AssetGraphSelection | undefined, + opts?: { open?: boolean } + ) => void // Called when the user clicks the per-asset + button (consumer-script // entry). Kept optional so the canvas stays usable outside the // pipeline editor. @@ -49,7 +85,8 @@ language: import('$lib/gen').ScriptLang, scriptPath: string, outputKind: import('./pipelineTemplates').PipelineOutputKind, - aiPrompt?: string + aiPrompt?: string, + options?: import('./PipelineInsertMenu.svelte').PipelineInsertOptions ) => void // Pipeline-wide + node shown at the top of the graph. Picking any // kind from the menu invokes this one callback with the chosen @@ -65,7 +102,8 @@ path: string | undefined }, outputKind: import('./pipelineTemplates').PipelineOutputKind, - aiPrompt?: string + aiPrompt?: string, + options?: import('./PipelineInsertMenu.svelte').PipelineInsertOptions ) => void // Folder-scoped prefix shown as a read-only chip in the insert menu // path input (e.g. `f/{folder}/`). Shared across top + and per-asset +. @@ -194,6 +232,32 @@ * canvas is embedded inline inside a scrollable container, so a wheel * gesture over it scrolls the container instead of being captured. */ scrollZoom?: boolean + /** Offer the "Show scripts and triggers" switch; off folds scripts and triggers into the + * assets they produce. */ + assetsOnlyToggle?: boolean + /** The pipeline's `<workspace>/<folder>`, when the toggle's state should be + * remembered for it. */ + assetsOnlyFolder?: string + /** Deletes what produces an asset in the assets-only view: its script, and its + * trigger when set. The canvas only offers what no other asset shares. */ + onDeleteAssetUpstream?: (target: AssetUpstreamDelete) => void + /** Canvas node id → what is wrong with it and how to fix it (the Fix pill). */ + nodeFixes?: ReadonlyMap<string, NodeFixSpec> + /** "Archive" for someone who can only archive the script the delete removes. */ + assetDeleteVerb?: 'Delete' | 'Archive' + /** Makes scripts run after each write to an asset: a script's (or, in the + * assets-only view, an asset's producers') top dot dragged onto that asset. + * `reads` says whether each script already reads it. */ + onAddAssetTrigger?: (a: { + scripts: Array<{ script: string; reads: boolean }> + asset: { kind: AssetKind; path: string } + }) => void + /** Makes scripts run after each write to an asset they read, or stop. `reads` + * decides whether stopping also mutes the asset. */ + onEdgeAction?: (a: { + action: 'listen' | 'stop' + targets: Array<{ script: string; asset: { kind: AssetKind; path: string }; reads: boolean }> + }) => void } let { graph, @@ -226,9 +290,347 @@ highlightActiveRun = false, recomputedAssetIds, assetRunStatus, - scrollZoom = true + scrollZoom = true, + assetsOnlyToggle = false, + assetsOnlyFolder, + onDeleteAssetUpstream, + nodeFixes, + assetDeleteVerb = 'Delete', + onEdgeAction, + onAddAssetTrigger }: Props = $props() + // Two drags write `// on`: a script's top dot onto an asset, and an asset's "+" + // onto a script. Only the nodes the drop can subscribe without a loop stay lit. + // The "+" can also be dropped on the blank canvas, opening its add menu there. + let onDrag = $state< + | { + sourceId: string + from: { x: number; y: number } + to: { x: number; y: number } + eligible: Set<string> + over: string | undefined + /** Dragging an asset's "+", whose blank-canvas drop adds a step. */ + feed: boolean + blank: boolean + } + | undefined + >(undefined) + // Hit-tested on the boxes rather than with elementFromPoint: svelte-flow can + // make nodes click-through while the pointer is held down. + const within = (el: Element, x: number, y: number) => { + const r = el.getBoundingClientRect() + return x >= r.left && x <= r.right && y >= r.top && y <= r.bottom + } + let flowEl: HTMLElement | undefined = $state() + const nodeUnder = (x: number, y: number) => + Array.from(flowEl?.querySelectorAll('.svelte-flow__node') ?? []) + .find((el) => within(el, x, y)) + ?.getAttribute('data-id') ?? undefined + const overBlank = (x: number, y: number) => + !!flowEl && + within(flowEl, x, y) && + !Array.from( + flowEl.querySelectorAll('.svelte-flow__panel, .svelte-flow__controls, .svelte-flow__minimap') + ).some((el) => within(el, x, y)) + const readsAsset = (assetId: string, scriptId: string) => + model.edges.some((x) => x.kind === 'lineage-read' && x.source === assetId && x.target === scriptId) + const assetOf = (assetId: string) => { + const a = model.nodes.find((n) => n.id === assetId)?.data + return a ? { kind: a.asset_kind as AssetKind, path: a.path as string } : undefined + } + function subscribe(assetId: string, scripts: string[]) { + const asset = assetOf(assetId) + if (!asset) return + onAddAssetTrigger?.({ + asset, + scripts: scripts.map((id) => ({ + script: id.replace(/^script:/, ''), + reads: readsAsset(assetId, id) + })) + }) + } + /** `threshold`: pixels the pointer must travel before it counts as a drag, so a + * plain click on the handle still clicks. */ + function trackDrag( + e: PointerEvent, + start: { sourceId: string; feed: boolean; eligible: () => Set<string>; threshold: number }, + drop: (target: string | undefined, at: { x: number; y: number }, blank: boolean) => void + ) { + const from = { x: e.clientX, y: e.clientY } + let started = false + const begin = () => { + started = true + onDrag = { + sourceId: start.sourceId, + from, + to: from, + eligible: start.eligible(), + over: undefined, + feed: start.feed, + blank: false + } + } + if (start.threshold === 0) begin() + const move = (ev: PointerEvent) => { + if (!started) { + if (Math.hypot(ev.clientX - from.x, ev.clientY - from.y) < start.threshold) return + begin() + } + if (!onDrag) return + onDrag.to = { x: ev.clientX, y: ev.clientY } + onDrag.over = nodeUnder(ev.clientX, ev.clientY) + onDrag.blank = !onDrag.over && overBlank(ev.clientX, ev.clientY) + } + // A drag that ends without a release (pointer cancelled, window left) drops + // nothing, and must not leave its line following the cursor. + const teardown = () => { + window.removeEventListener('pointermove', move) + window.removeEventListener('pointerup', up) + window.removeEventListener('pointercancel', cancel) + window.removeEventListener('blur', cancel) + document.removeEventListener('visibilitychange', cancel) + } + const cancel = () => { + teardown() + onDrag = undefined + } + const up = (ev: PointerEvent) => { + teardown() + const drag = onDrag + onDrag = undefined + if (!started || !drag) return + // The release is not a click on whatever it lands on. + const swallow = (c: MouseEvent) => { + c.stopPropagation() + c.preventDefault() + } + window.addEventListener('click', swallow, { capture: true, once: true }) + setTimeout(() => window.removeEventListener('click', swallow, { capture: true }), 0) + const target = nodeUnder(ev.clientX, ev.clientY) + const at = { x: ev.clientX, y: ev.clientY } + drop(target && drag.eligible.has(target) ? target : undefined, at, !target && drag.blank) + } + window.addEventListener('pointermove', move) + window.addEventListener('pointerup', up) + window.addEventListener('pointercancel', cancel) + window.addEventListener('blur', cancel) + document.addEventListener('visibilitychange', cancel) + } + function startOnDrag(sourceId: string, scripts: string[], e: PointerEvent) { + if (!onAddAssetTrigger || scripts.length === 0) return + trackDrag( + e, + { + sourceId, + feed: false, + threshold: 0, + eligible: () => { + const sets = scripts.map((id) => onDirectiveTargets(model.nodes, model.edges, id)) + return new Set([...sets[0]].filter((a) => sets.every((t) => t.has(a)))) + } + }, + (target) => { + if (target) subscribe(target, scripts) + } + ) + } + // Where a "+" dropped on the blank canvas opened its add menu. + let feedMenu = $state< + | { at: { x: number; y: number }; asset: { kind: AssetKind; path: string }; data: any } + | undefined + >(undefined) + let feedMenuSignal = $state(0) + function startFeedDrag(assetId: string, data: any, e: PointerEvent) { + trackDrag( + e, + { + sourceId: assetId, + feed: true, + threshold: 5, + // A drop target is a node whose scripts can all subscribe to the asset. + eligible: () => { + if (!onAddAssetTrigger) return new Set() + const targets = new Map<string, Set<string>>() + const can = (id: string) => { + if (!targets.has(id)) targets.set(id, onDirectiveTargets(model.nodes, model.edges, id)) + return targets.get(id)!.has(assetId) + } + return new Set( + view.nodes + .filter((n) => { + const scripts = dragScripts(n) + return n.id !== assetId && scripts.length > 0 && scripts.every(can) + }) + .map((n) => n.id) + ) + } + }, + (target, at, blank) => { + const node = target ? view.nodes.find((n) => n.id === target) : undefined + if (node) subscribe(assetId, dragScripts(node)) + else if (blank) { + const asset = assetOf(assetId) + if (!asset) return + feedMenu = { at, asset, data } + feedMenuSignal++ + } + } + ) + } + // Pipeline scripts a node's top dot drags for: the script itself, or, in the + // assets-only view, the scripts building the asset. + function dragScripts(n: { id: string; type: string; data: any }): string[] { + const ids = + n.type === 'runnable' ? [n.id] : n.type === 'asset' ? ((n.data.foldedIds ?? []) as string[]) : [] + return ids.filter((id) => { + const d = model.nodes.find((x) => x.id === id)?.data + return d?.runnable_kind === 'script' && d.in_pipeline + }) + } + + let assetsOnly = $state(false) + // Before the first paint: the default view is assets-only, and a plain effect + // would flash the full graph first. + $effect.pre(() => { + if (assetsOnlyFolder != undefined) assetsOnly = isAssetsOnlyFolder(assetsOnlyFolder) + }) + + // Right-click on the empty canvas: a menu at the pointer whose entry opens the + // add-data-source menu there too. + let paneMenu = $state<{ x: number; y: number } | undefined>(undefined) + + // Hovering an edge names the relationship it draws, after a short pause so + // sweeping the pointer across the canvas doesn't flash popovers. + let hoveredEdge = $state<{ id: string; x: number; y: number } | undefined>(undefined) + let edgeHoverTimer: ReturnType<typeof setTimeout> | undefined + function onEdgeEnter({ edge, event }: { edge: Edge; event: PointerEvent }) { + clearTimeout(edgeHoverTimer) + const at = { id: edge.id, x: event.clientX, y: event.clientY } + edgeHoverTimer = setTimeout(() => (hoveredEdge = at), 300) + } + // Leaving the edge closes the popover after a moment, so the pointer can reach + // its buttons; entering the popover keeps it. + function onEdgeLeave() { + clearTimeout(edgeHoverTimer) + edgeHoverTimer = setTimeout(() => (hoveredEdge = undefined), 200) + } + // What the hovered edge lets you change: a plain read can become a trigger, and + // an asset trigger can be dropped. Both rewrite the script's `// on` header. + // What the hovered edge lets you change: a script that only reads the upstream + // asset can rerun on each write to it, and one it triggers can stop. On an + // assets-only edge, those are the scripts folded into it; both rewrite `// on`. + type EdgeTarget = { script: string; asset: { kind: AssetKind; path: string }; reads: boolean } + let hoveredEdgeActions = $derived.by(() => { + const e = hoveredEdge && onEdgeAction && view.edges.find((x) => x.id === hoveredEdge!.id) + if (!e) return [] + const assetData = view.nodes.find((n) => n.id === e.source)?.data + if (!assetData?.asset_kind) return [] + const asset = { kind: assetData.asset_kind as AssetKind, path: assetData.path as string } + const scriptIds = + e.kind === 'asset-flow' + ? (e.via ?? []) + : e.kind === 'lineage-read' || e.kind === 'trigger-asset' + ? [e.target] + : [] + const listen: EdgeTarget[] = [] + const stop: EdgeTarget[] = [] + for (const id of scriptIds) { + const script = model.nodes.find((n) => n.id === id)?.data + if (script?.runnable_kind !== 'script' || !script.in_pipeline) continue + const has = (kind: string) => + model.edges.some((x) => x.kind === kind && x.source === e.source && x.target === id) + const target = { script: script.path as string, asset, reads: has('lineage-read') } + if (has('trigger-asset')) stop.push(target) + // A script rerunning on its own writes would loop: offered only for inputs. + else if ( + target.reads && + !model.edges.some( + (x) => x.kind === 'lineage-write' && x.source === id && x.target === e.source + ) + ) + listen.push(target) + } + const where = (ts: EdgeTarget[]) => + ts.length === 1 ? ts[0].script : `${ts.length} scripts: ${ts.map((t) => t.script).join(', ')}` + const out: Array<{ label: string; detail: string; run: () => void }> = [] + if (listen.length) { + out.push({ + label: 'Rerun on each write', + detail: `${listenChangeText(asset, true)} in ${where(listen)}; only the annotation header changes. Saved as a draft.`, + run: () => onEdgeAction?.({ action: 'listen', targets: listen }) + }) + } + if (stop.length) { + out.push({ + label: 'Stop rerunning on writes', + detail: `${stopListeningChangeText( + asset, + stop.some((t) => t.reads) + )} in ${where(stop)}; only the annotation header changes. Saved as a draft.`, + run: () => onEdgeAction?.({ action: 'stop', targets: stop }) + }) + } + return out + }) + let hoveredEdgeText = $derived.by(() => { + const e = hoveredEdge && view.edges.find((x) => x.id === hoveredEdge!.id) + if (!e) return undefined + const byId = new Map(view.nodes.map((n) => [n.id, n])) + const nameOf = (id: string) => { + const n = byId.get(id) + if (!n) return id.replace(/^[^:]+:/, '') + if (n.type === 'asset') + return formatShortAssetPath({ kind: n.data.asset_kind, path: n.data.path }) + if (n.type === 'no-asset') return n.data.noAssetName + if (n.type === 'trigger') return n.data.summary || n.data.ref + return n.data.summary || n.data.path + } + return describeEdge(e, nameOf, (id) => byId.get(id)?.data) + }) + let addMenuAt = $state<{ x: number; y: number }>({ x: 0, y: 0 }) + let addMenuSignal = $state(0) + + // The schedule wizard a Fix action opens for an existing script, at the pill. + let scheduleWizard = $state< + | { + script: string + onSchedule: (s: PipelineInsertSchedule) => void + at: { x: number; y: number } + } + | undefined + >(undefined) + let scheduleWizardSignal = $state(0) + + function toFix(spec: NodeFixSpec | undefined): NodeFix | undefined { + if (!spec) return undefined + return { + explainer: spec.explainer, + actions: spec.actions.map((a) => ({ + label: a.label, + detail: a.detail, + run: (anchor) => { + if (a.scheduleFor) { + scheduleWizard = { ...a.scheduleFor, at: anchor } + scheduleWizardSignal++ + } else a.run?.() + } + })) + } + } + function handleContextMenu(e: MouseEvent) { + const t = e.target as HTMLElement | null + // A node's own actions menu opens on right-click; the browser's never does, + // on nodes without one either. + if (t?.closest('.svelte-flow__node')) { + e.preventDefault() + return + } + if (!onAddPipelineScript || boundPick || !t?.closest('.svelte-flow__pane')) return + e.preventDefault() + paneMenu = { x: e.clientX, y: e.clientY } + } + // `${kind}:${path}` ids for the hovered / pinned runs (both script and flow // variants, since the run row's kind isn't known here). const runIds = (paths: string[] | undefined): Set<string> => @@ -256,7 +658,12 @@ | 'macro' | 'test-dependency' | 'dbt-ref' + // Assets-only view: an asset → an asset computed from it, through the + // script that is folded away. + | 'asset-flow' unsaved?: boolean + // Assets-only `asset-flow`: a write to the source reruns a folded script. + reactive?: boolean // Muted read edge: a ducklake/s3 input read every run whose (default) // auto cascade trigger is suppressed by `// mute` / `// mute all`. // Rendered with a bell-off badge — auto-wiring is the norm, so we mark @@ -276,6 +683,8 @@ // whole lib when pulled in via `// use`) — rendered as a ƒ badge. macro_names?: string[] via_use?: boolean + // Assets-only edges: the scripts folded between the two assets. + via?: string[] } // Graph-id of the script the user just launched (zero-latency hint), @@ -290,7 +699,7 @@ function build(g: AssetGraphResponse) { const nodes: Array<{ id: string - type: 'asset' | 'runnable' | 'trigger' | 'add' | 'data-test' + type: 'asset' | 'runnable' | 'trigger' | 'add' | 'data-test' | 'no-asset' data: any }> = [] const edges: BuiltEdge[] = [] @@ -427,8 +836,10 @@ path: a.path, fork_materialization: a.fork_materialization, derived_from: a.derived_from, + error: a.error, dbt: a.dbt, onAddScript: onAddScriptForAsset, + neverWritten: a.never_written, pathPrefix, defaultPathSuffix, producers: producersByAsset.get(`${a.kind}:${a.path}`) ?? [], @@ -454,11 +865,14 @@ const owner = model.dbtOwnerByAsset.get(assetId) const [kind, ...rest] = owner?.split(':') ?? [] if (kind && rest.length) { - onselect?.({ - kind: 'runnable', - runnable_kind: kind as 'script' | 'flow', - path: rest.join(':') - }) + onselect?.( + { + kind: 'runnable', + runnable_kind: kind as 'script' | 'flow', + path: rest.join(':') + }, + { open: true } + ) } } } @@ -466,14 +880,6 @@ } }) } - // Set of `script_path` values for runnables that are still drafts (no - // DB row yet). Trigger nodes use this to swap "Click to create" for - // "Click to create (after draft save)" so the user knows the create - // button is blocked until the script is deployed. - const unsavedRunnablePaths = new Set<string>() - for (const r of g.runnables) { - if (r.unsaved) unsavedRunnablePaths.add(r.path) - } // Producer → its `// data_test` checks, keyed by runnable id, so the // write-edge to the materialized asset can carry the test badge: the // edge *is* the transformation, and the tests assert on what it produces. @@ -526,6 +932,9 @@ data: { runnable_kind: r.usage_kind, path: r.path, + summary: r.summary, + language: r.language, + error: r.error, in_pipeline: r.in_pipeline ?? false, partition_kind: r.partition_kind, freshness: r.freshness, @@ -724,6 +1133,10 @@ kind: TriggerNodeKind ref: string missing: boolean + draft: boolean + schedule?: string + timezone?: string + summary?: string // First target script (drives the per-script create/edit flows). runnable_path?: string // Every target script: a single (kind, ref) — e.g. one schedule — @@ -739,7 +1152,11 @@ ref: string, unsaved: boolean, missing: boolean, - runnable_path?: string + draft: boolean, + runnable_path?: string, + schedule?: string, + timezone?: string, + summary?: string ) { const prev = triggerSourceNodes.get(id) if (!prev) { @@ -748,6 +1165,10 @@ kind, ref, missing, + draft, + schedule, + timezone, + summary, runnable_path, runnable_paths: runnable_path ? [runnable_path] : [] }) @@ -796,13 +1217,17 @@ ref, !!t.unsaved, isMissing, + t.draft === true, // Always thread the target script so the trigger node can // reach back to it — drives both the missing-trigger "create" // flow and the attached-trigger "edit" flow's script-path // lock. Previously only set for missing, which silently // disabled `canEdit` (and the resulting click affordance) // on every attached native trigger. - t.runnable_path + t.runnable_path, + t.schedule, + t.timezone, + t.summary ) edges.push({ id: `trig-${t.trigger_kind}:${sourceId}->${runnableId}`, @@ -830,10 +1255,12 @@ ref: info.ref, unsaved: info.allUnsaved, missing: info.missing, + draft: info.draft, + schedule: info.schedule, + timezone: info.timezone, + summary: info.summary, runnable_path: info.runnable_path, - runnable_unsaved: info.runnable_path - ? unsavedRunnablePaths.has(info.runnable_path) - : false, + runnable_paths: info.runnable_paths, // data_upload nodes go green once a file is staged for their // target script (see readyDataUploadPaths / page dataUploadArgs). ready: info.runnable_path @@ -881,11 +1308,383 @@ let model = $derived(build(graph)) + // The trigger chip last clicked in the assets-only view, by trigger node id: it + // opens a drawer rather than a selection, so it is highlighted until the next pick. + let activeTriggerId = $state<string | undefined>(undefined) + $effect(() => { + void selection + activeTriggerId = undefined + }) + + /** The chip naming what runs an asset's producer, and the editor it opens: the + * same routes the trigger's own node takes. */ + function triggerChip( + t: (AssetUpstream & { multiple: false })['trigger'], + scriptPath: string + ): { + label: string + /** Nothing to show: the edges into the node already say it runs on writes. */ + hidden?: boolean + kind?: string + nodeId?: string + missing?: boolean + draft?: boolean + onOpen?: () => void + } { + if (!t) return { label: 'Manual' } + if (t.kind === 'asset') return { label: '', hidden: true } + const kind = t.kind as NativeTriggerKind + const style = TRIGGER_NODE_STYLE[kind] + const label = + t.kind === 'schedule' && t.data?.schedule + ? (describeSchedule(t.data.schedule, t.data.timezone) ?? `Schedule (${t.data.schedule})`) + : (style?.label ?? t.kind) + const rowless = kind === 'webhook' || kind === 'data_upload' + const missing = !!t.data?.missing && !rowless + const open = + kind === 'webhook' + ? onOpenWebhook && (() => onOpenWebhook(scriptPath)) + : kind === 'data_upload' + ? onOpenDataUpload && (() => onOpenDataUpload(scriptPath)) + : missing + ? onCreateMissingTrigger && (() => onCreateMissingTrigger(kind, scriptPath)) + : t.data?.ref && onEditTrigger + ? () => onEditTrigger(kind, t.data.ref, scriptPath) + : undefined + return { + label, + kind, + nodeId: t.nodeId, + missing, + draft: t.data?.draft, + onOpen: open + ? () => { + activeTriggerId = t.nodeId + open() + } + : undefined + } + } + + // Scripts and triggers fold into the assets they produce: each asset carries + // its producer's run state, language and trigger instead of drawing them. + function assetsOnlyModel(m: typeof model): typeof model { + const v = assetsOnlyView(m.nodes, m.edges) + const runnables = new Map(m.nodes.filter((n) => n.type === 'runnable').map((n) => [n.id, n])) + // What an asset card shows in this view: its producer's chips, its width, + // and what deleting it removes. `data` is an asset's, or the "No asset" node's. + const fold = (data: any, u: AssetUpstream | undefined) => { + const r = u && !u.multiple ? runnables.get(u.runnableId)?.data : undefined + // A dbt model is built by its project, whose writes the canvas does not + // draw; its dbt chip already names it. + const upstream = !u + ? data.dbt && data.dbt.resource_type !== 'source' + ? undefined + : { none: true as const } + : u.multiple || !r + ? { + multiple: true as const, + scripts: (u.multiple ? u.runnableIds : []) + .map((id) => runnables.get(id)?.data) + .filter((d) => d != undefined) + .map((d) => ({ + runnableId: `${d.runnable_kind}:${d.path}`, + path: d.path as string, + summary: d.summary as string | undefined, + language: d.language, + unsaved: d.unsaved as boolean | undefined, + onOpen: () => + onselect?.( + { kind: 'runnable', runnable_kind: d.runnable_kind, path: d.path }, + { open: true } + ) + })), + // Every script's own triggers; asset triggers show as edges instead. + triggers: (u.multiple ? u.runnableIds : []) + .flatMap((id) => { + const d = runnables.get(id)?.data + if (!d) return [] + return m.edges + .filter((e) => e.kind === 'trigger-native' && e.target === id) + .map((e) => m.nodes.find((n) => n.id === e.source)) + .filter((t) => t != undefined) + .map((t) => ({ + ...triggerChip( + { nodeId: t.id, kind: t.data.kind, data: t.data }, + d.path as string + ), + script: d.path as string + })) + }) + .filter((t) => !t.hidden) + } + : { + runnableId: u.runnableId, + path: r.path, + summary: r.summary, + language: r.language, + unsaved: r.unsaved, + runState: r.runState, + trigger: triggerChip(u.trigger, r.path), + onOpen: () => + onselect?.( + { kind: 'runnable', runnable_kind: r.runnable_kind, path: r.path }, + { open: true } + ) + } + const toDelete = + onDeleteAssetUpstream && u && !u.multiple && r + ? upstreamDeletion(u, r, v.upstream) + : undefined + // The scripts and triggers folded into this node, whose errors it reports. + const scriptIds = u ? (u.multiple ? u.runnableIds : [u.runnableId]) : [] + const foldedIds = [ + ...scriptIds, + ...m.edges + .filter((e) => e.kind === 'trigger-native' && scriptIds.includes(e.target)) + .map((e) => e.source) + ] + const foldedErrors = foldedIds.filter((id) => nodeFixes?.has(id)).length + const asset = { kind: data.asset_kind, path: data.path } + // Chips this estimate does not model keep the regular width. + const width = + upstream && !data.dbt && !data.fork_materialization && !data.derived_from && !data.runStatus + ? assetsOnlyNodeWidth({ + kind: data.noAsset ? 'No asset' : formatAssetKind(asset), + title: data.noAsset ? data.noAssetName : formatShortAssetPath(asset), + chip: foldedErrors + ? `${foldedErrors} errors · Fix` + : 'none' in upstream + ? 'External source' + : 'multiple' in upstream + ? (upstream.triggers?.length ?? 0) > 1 + ? 'Multiple triggers' + : (upstream.triggers?.length ?? 0) === 1 + ? (upstream.triggers?.[0]?.label ?? '') + : '' + : upstream.trigger.hidden + ? '' + : `${upstream.trigger.label}${upstream.trigger.draft ? ' · draft' : ''}`, + chipIcon: foldedErrors > 0, + // Room for the chip's trailing icon: a pencil, or the chevron of a + // several-trigger menu (about as wide). + chipEdit: + !foldedErrors && + ('multiple' in upstream + ? (upstream.triggers?.length ?? 0) > 1 || + (!!upstream.triggers?.[0]?.onOpen && !upstream.triggers?.[0]?.missing) + : 'trigger' in upstream && + !!upstream.trigger?.onOpen && + !upstream.trigger.missing), + header: + 'runnableId' in upstream + ? { + label: upstream.summary || upstream.path, + icons: 1, + draft: !!upstream.unsaved + } + : 'scripts' in upstream && upstream.scripts?.length + ? upstream.scripts.length === 1 + ? { + label: upstream.scripts[0].summary || upstream.scripts[0].path, + icons: 1, + draft: !!upstream.scripts[0].unsaved + } + : { label: `${upstream.scripts.length} scripts`, icons: 2, chevron: true } + : undefined + }) + : undefined + return { + ...data, + upstream, + width, + foldedIds, + ...(toDelete + ? { + upstreamDelete: toDelete, + deleteVerb: assetDeleteVerb, + onDeleteUpstream: (t: AssetUpstreamDelete) => onDeleteAssetUpstream?.(t) + } + : onDeleteAssetUpstream && u + ? { + // No combined delete, but each script it folds can still go on its + // own: in this view its node's menu is the only way to reach it. + scriptDeletes: (u.multiple ? u.runnableIds : [u.runnableId]) + .map((id) => runnables.get(id)?.data) + .filter((d) => d?.runnable_kind === 'script') + .map((d) => ({ path: d.path as string, unsaved: !!d.unsaved })), + // Its scripts' own triggers: a row that starts only them, which + // webhooks and data uploads (no row) and missing ones are not. + triggerDeletes: scriptIds.flatMap((id) => { + const runnable = runnables.get(id)?.data + // A flow is not deleted from here, and neither are its triggers. + if (runnable?.runnable_kind !== 'script') return [] + const scriptPath = runnable.path + return m.edges + .filter((e) => e.kind === 'trigger-native' && e.target === id) + .map((e) => m.nodes.find((n) => n.id === e.source)?.data) + .filter( + (t) => + t && + t.kind !== 'webhook' && + t.kind !== 'data_upload' && + t.ref && + !t.missing && + ((t.runnable_paths ?? []) as string[]).every((p) => p === scriptPath) + ) + .map((t) => ({ + kind: t.kind as NativeTriggerKind, + path: t.ref as string, + draft: !!t.draft + })) + }), + deleteVerb: assetDeleteVerb, + onDeleteUpstream: (t: AssetUpstreamDelete) => onDeleteAssetUpstream?.(t), + // The No-asset card stands for its scripts; an asset is built by them. + deleteBlocked: data.noAsset + ? !u.multiple + ? 'it stands for a flow' + : u.runnableIds.length > 1 + ? 'it stands for several scripts' + : 'its script has several triggers' + : !u.multiple + ? r?.runnable_kind === 'flow' + ? 'a flow builds it' + : 'its script builds other assets too' + : u.runnableIds.length > 1 + ? 'several scripts build it' + : 'its script has several triggers' + } + : {}) + } + } + const nodes = m.nodes + .filter((n) => n.id === ADD_NODE_ID || v.nodeIds.has(n.id)) + .map((n) => (n.type === 'asset' ? { ...n, data: fold(n.data, v.upstream.get(n.id)) } : n)) + for (const id of v.noAssetNodeIds) { + const u = v.upstream.get(id) + const scriptId = u && !u.multiple ? u.runnableId : u?.runnableIds[0] + const data = fold( + { noAsset: true, noAssetName: scriptId?.split('/').pop() ?? 'script' }, + u + ) + // Run only by writes to what it reads, the edges into it already say how + // it starts: the script's banner alone. Another trigger, or an error to + // fix, needs the card's chip row. + const bannerOnly = + !!u && + !u.multiple && + u.trigger?.kind === 'asset' && + !(data.foldedIds as string[]).some((f) => nodeFixes?.has(f)) + nodes.push({ id, type: 'no-asset', data: bannerOnly ? { ...data, bannerOnly } : data }) + } + const edges: BuiltEdge[] = v.edges.map((e) => ({ ...e, kind: e.kind as BuiltEdge['kind'] })) + if (nodes.some((n) => n.id === ADD_NODE_ID)) { + const hasIncoming = new Set(edges.map((e) => e.target)) + for (const n of nodes) { + if (n.id !== ADD_NODE_ID && !hasIncoming.has(n.id)) { + edges.push({ + id: `add-anchor:${n.id}`, + source: ADD_NODE_ID, + target: n.id, + kind: 'add-anchor' + }) + } + } + } + return { ...m, nodes, edges } + } + // Reads that start nothing (lookups, reference tables) are often most of a + // graph's edges; hiding them leaves what makes the pipeline run. Remembered + // across pipelines. + const SHOW_PASSIVE_READS_KEY = 'pipeline-show-passive-reads' + let showPassiveReads = $state(true) + try { + showPassiveReads = localStorage.getItem(SHOW_PASSIVE_READS_KEY) !== 'false' + } catch {} + let withoutPassive = $derived(withoutPassiveReads(model.nodes, model.edges)) + // Only where the toggle is shown: the preference is global, and a graph + // without the toggle would have no way to show the reads again. + let shownModel = $derived( + !assetsOnlyToggle || showPassiveReads || withoutPassive.dropped === 0 + ? model + : { ...model, nodes: withoutPassive.nodes, edges: withoutPassive.edges } + ) + let view = $derived(assetsOnly ? assetsOnlyModel(shownModel) : shownModel) + // dbt association, surfaced by emphasis instead of edges. Hovering a model's // dbt badge lights up the project node that materializes it; hovering the // project node lights up every model it owns. Clicking the badge selects the // project node, so the association survives the pointer leaving. let dbtHoverId = $state<string | undefined>(undefined) + + // Hovering a node keeps its lineage — everything upstream and downstream of + // it, recursively — at full strength and fades the rest. Off while a bounded + // pick or a subscribe drag owns the graph's dimming. + let hoveredNodeId = $state<string | undefined>(undefined) + // A click re-renders the graph under the cursor (the selection rebuilds the + // nodes, the details pane resizes or covers the canvas), which fires bursts of + // leave/enter. The fade waits for the pointer to settle on a node, outlives a + // brief leave, and stays off on a node just clicked until another is hovered. + let hoverTimer: ReturnType<typeof setTimeout> | undefined + let clickedNodeId: string | undefined + function onNodePointerEnter(id: string) { + clearTimeout(hoverTimer) + if (id === clickedNodeId) return + clickedNodeId = undefined + hoverTimer = setTimeout(() => (hoveredNodeId = id), 120) + } + function onNodePointerLeave() { + clearTimeout(hoverTimer) + hoverTimer = setTimeout(() => (hoveredNodeId = undefined), 80) + } + $effect(() => () => clearTimeout(hoverTimer)) + let lineage = $derived( + hoveredNodeId && hoveredNodeId !== ADD_NODE_ID && !boundPick && !onDrag + ? hoverLineage( + view.edges.filter((e) => e.kind !== 'add-anchor'), + hoveredNodeId + ) + : undefined + ) + // The fade goes through a stylesheet keyed on node and edge ids, never through + // the graph's node or edge objects: new node objects make the flow re-measure + // them and rebuild every edge they touch, and a rebuilt element jumps to its + // new opacity instead of easing there. + const canvasId = randomUUID() + let lineageFadeCss = $derived.by(() => { + if (!lineage) return '' + const scope = `[data-asset-canvas="${canvasId}"]` + const nodes = view.nodes + .filter((n) => outsideLineage(n.id)) + .map((n) => `${scope} .svelte-flow__node[data-id="${CSS.escape(n.id)}"]`) + const edges = view.edges + .filter((e) => e.kind !== 'add-anchor' && !lineage!.hasEdge(e)) + .map((e) => `${scope} .svelte-flow__edge[data-id="${CSS.escape(e.id)}"]`) + return [ + nodes.length ? `${nodes.join(',')}{opacity:0.5}` : '', + edges.length ? `${edges.join(',')}{opacity:0.35}` : '' + ].join('') + }) + // Assets-only: a trigger edge A → C that A → B → … → C already implies says + // nothing new, so it recedes; the chain carries the cascade. + let impliedTriggerEdges = $derived( + assetsOnly + ? transitivelyImpliedEdges(view.edges.filter((e) => e.kind === 'asset-flow' && e.reactive)) + : new Set<string>() + ) + let lineageSheet = $state<HTMLStyleElement | undefined>(undefined) + onMount(() => { + const sheet = document.createElement('style') + document.head.appendChild(sheet) + lineageSheet = sheet + return () => sheet.remove() + }) + $effect(() => { + if (lineageSheet) lineageSheet.textContent = lineageFadeCss + }) + const outsideLineage = (id: string) => + !!lineage && id !== ADD_NODE_ID && !lineage.upstream.has(id) && !lineage.downstream.has(id) let dbtEmphasisIds = $derived.by(() => { if (!dbtHoverId) return new Set<string>() const owned = model.dbtWritesByOwner.get(dbtHoverId) @@ -922,14 +1721,14 @@ // input; the rendered edges are untouched (both arrows still drawn). let writeEdgePairs = $derived( new Set( - model.edges.filter((e) => e.kind === 'lineage-write').map((e) => `${e.source}\n${e.target}`) + view.edges.filter((e) => e.kind === 'lineage-write').map((e) => `${e.source}\n${e.target}`) ) ) let layoutInput = $derived({ - nodes: model.nodes - .map((n) => ({ id: n.id, data: n.data })) + nodes: view.nodes + .map((n) => ({ id: n.id, data: n.data, width: n.data?.width as number | undefined })) .sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)), - edges: model.edges + edges: view.edges .filter( (e) => !( @@ -950,7 +1749,18 @@ : 1 ) }) - let layoutPositions = $derived(layoutAssetGraph(layoutInput, ADD_NODE_ID)) + let layoutPositions = $derived( + layoutAssetGraph( + layoutInput, + ADD_NODE_ID, + assetsOnly + ? PIPELINE_NODE_EXTRA_ROW + PIPELINE_NODE_HEADER + PIPELINE_NODE_HEADER_CARD_PAD + : 0 + ) + ) + + /** Assets-only asset cards size to their text; every other node is `NODE.width`. */ + const nodeWidth = (n: { data?: any }): number => n.data?.width ?? NODE.width let positionedNodes = $derived.by(() => { // Compute bbox width from layout; shift every x so the graph is @@ -965,11 +1775,8 @@ } const bboxWidth = isFinite(minX) ? maxX - minX : 0 const xCenter = paneWidth / 2 - bboxWidth / 2 - return model.nodes.map<Node>((n) => { + return view.nodes.map<Node>((n) => { const p = layoutPositions.get(n.id) ?? { x: 0, y: 0 } - // Compensate for the + node being narrower than its layout slot - // so it visually centers over the node(s) below. - const xShift = n.id === ADD_NODE_ID ? (NODE.width - ADD_NODE_WIDTH) / 2 : 0 // Activity-panel emphasis (purely visual rings, kept off `selected` // which swaps the details pane). Hover wins over pin so the cursor // always tracks. @@ -998,12 +1805,73 @@ else if (!boundPick.eligible.has(n.id)) boundClass = 'wm-bound-dim' } const dbtClass = dbtEmphasisIds.has(n.id) ? 'wm-dbt-linked' : undefined + const dragClass = !onDrag + ? undefined + : onDrag.eligible.has(n.id) + ? onDrag.over === n.id + ? 'wm-drag-over' + : undefined + : n.id === onDrag.sourceId + ? undefined + : 'wm-drag-dim' + // The chips' selected look rides on the positioned nodes, so a selection + // never re-runs the layout. + const up = n.type === 'asset' || n.type === 'no-asset' ? n.data.upstream : undefined + const fix = toFix(nodeFixes?.get(n.id)) + const withUpstream = up?.scripts + ? { + ...n.data, + upstream: { + ...up, + selected: up.scripts.some( + (sc: { runnableId: string }) => sc.runnableId === selectedId + ), + triggers: (up.triggers ?? []).map((t: { nodeId?: string }) => ({ + ...t, + selected: !!t.nodeId && t.nodeId === activeTriggerId + })) + } + } + : up?.runnableId !== undefined + ? { + ...n.data, + upstream: { + ...up, + selected: up.runnableId === selectedId, + trigger: { + ...up.trigger, + selected: !!up.trigger.nodeId && up.trigger.nodeId === activeTriggerId + } + } + } + : n.data + const foldedFixes = ((n.data.foldedIds ?? []) as string[]) + .map((id) => toFix(nodeFixes?.get(id))) + .filter((f) => f != undefined) + const scriptsToDrag = onAddAssetTrigger ? dragScripts(n) : [] + // Assets-only: a folded script with an error reddens the header naming it. + const scriptError = ((n.data.foldedIds ?? []) as string[]).some( + (id) => id.startsWith('script:') && nodeFixes?.has(id) + ) + const data = { + ...withUpstream, + ...(scriptError ? { scriptError } : {}), + ...(fix ? { fix } : {}), + ...(foldedFixes.length ? { foldedFixes } : {}), + ...(scriptsToDrag.length + ? { onStartOnDrag: (e: PointerEvent) => startOnDrag(n.id, scriptsToDrag, e) } + : {}), + ...(n.type === 'asset' && onAddScriptForAsset + ? { onStartFeedDrag: (e: PointerEvent) => startFeedDrag(n.id, n.data, e) } + : {}) + } return { id: n.id, type: n.type, - position: { x: p.x + xCenter + xShift, y: p.y + 40 }, - data: n.data, - class: boundClass ?? dbtClass ?? runClass ?? assetClass, + // The layout places centers; a node's position is its top-left corner. + position: { x: p.x - nodeWidth(n) / 2 + xCenter, y: p.y + 40 }, + data, + class: dragClass ?? boundClass ?? dbtClass ?? runClass ?? assetClass, selected: n.id === selectedId, // All nodes non-draggable: the layout is sugiyama-computed, // dragging would fight the reactive re-layout. Selection is @@ -1013,7 +1881,7 @@ // on its inner box so the edit/create button still receives // clicks despite svelte-flow's wrapper-level pointer-events: none. draggable: false, - selectable: n.id !== ADD_NODE_ID && n.type !== 'trigger' + selectable: n.id !== ADD_NODE_ID && n.type !== 'trigger' && n.type !== 'no-asset' } }) }) @@ -1039,7 +1907,7 @@ let assetEmphasis = $derived.by<Map<string, 'input' | 'output'>>(() => { const m = new Map<string, 'input' | 'output'>() if (emphasizedRunIdSet.size === 0) return m - for (const e of model.edges) { + for (const e of view.edges) { if (e.kind === 'lineage-write' && emphasizedRunIdSet.has(e.source)) { m.set(e.target, 'output') } else if ( @@ -1058,15 +1926,20 @@ let nodeCenters = $derived( positionedNodes .filter((n) => n.id !== ADD_NODE_ID) - .map((n) => ({ id: n.id, cx: n.position.x + NODE.width / 2, cy: n.position.y })) + .map((n) => ({ + id: n.id, + cx: n.position.x + nodeWidth(n) / 2, + cy: n.position.y, + halfW: nodeWidth(n) / 2 + })) ) - // Detour lane for an edge whose straight run would pass over an unrelated - // node (the failure the same-column gutter can't see). For each node - // strictly between the endpoints' rows, sample the straight line at that - // row; if the node sits under it, route around the obstacle on the side the - // edge is already heading. Returns the outermost lane x clearing every + // Detour lane for an edge whose run would pass over an unrelated node. An + // edge spanning rows bends inside the first gap below its source and then + // runs straight down the *target's* column (see AssetGraphEdge), so every + // node strictly between the endpoints' rows is tested against the target's + // x, not against a source→target line. A crossed node is routed around on + // the side the target lies. Returns the outermost lane x clearing every // crossed node, or undefined when the corridor is clear. O(nodes) per edge. - const HALF_W = NODE.width / 2 const ROUTE_PAD = NODE.gap.horizontal / 2 function detourForEdge(sourceId: string, targetId: string): number | undefined { const s = nodeCenters.find((n) => n.id === sourceId) @@ -1078,11 +1951,10 @@ if (n.id === sourceId || n.id === targetId) continue // strictly between the two rows if ((n.cy - s.cy) / dyTot <= 0.01 || (n.cy - s.cy) / dyTot >= 0.99) continue - const edgeX = s.cx + (t.cx - s.cx) * ((n.cy - s.cy) / dyTot) - if (Math.abs(edgeX - n.cx) >= HALF_W + 8) continue + if (Math.abs(t.cx - n.cx) >= n.halfW + 8) continue // Crossed: a lane just outside this node, toward the target side. const side = t.cx >= n.cx ? 1 : -1 - const candidate = n.cx + side * (HALF_W + ROUTE_PAD) + const candidate = n.cx + side * (n.halfW + ROUTE_PAD) // Keep the outermost lane so one detour clears every obstacle. if (lane == undefined || Math.abs(candidate - s.cx) > Math.abs(lane - s.cx)) lane = candidate } @@ -1090,7 +1962,7 @@ } let flowEdges = $derived.by(() => - model.edges + view.edges // Anchor edges are layout-only. .filter((e) => e.kind !== 'add-anchor') .map<Edge>((e) => { @@ -1118,30 +1990,42 @@ // the "happening now" signal. switch (e.kind) { case 'lineage-write': - style = 'stroke: rgb(59 130 246); stroke-width: 2px;' + style = 'stroke: rgb(59 130 246); stroke-width: 1.25px;' animated = flowAnimated markerColor = 'rgb(59 130 246)' break + case 'asset-flow': + // Assets-only: a write upstream reruns what builds the target + // (solid, like a trigger), or the target only reads it (dashed gray). + if (e.reactive) { + style = `stroke: rgb(59 130 246); stroke-width: 1.5px;${impliedTriggerEdges.has(e.id) ? ' opacity: 0.35;' : ''}` + markerColor = 'rgb(59 130 246)' + } else { + style = 'stroke: rgb(156 163 175); stroke-width: 1px;' + strokeDasharray = '4 3' + markerColor = 'rgb(156 163 175)' + } + break case 'lineage-read': - style = 'stroke: rgb(156 163 175); stroke-width: 1.25px;' + style = 'stroke: rgb(156 163 175); stroke-width: 1px;' animated = flowAnimated break case 'data-test': // Asset → its custom-test script: dashed, muted, no run // animation (the test isn't a producing step). - style = 'stroke: rgb(156 163 175); stroke-width: 1.25px;' + style = 'stroke: rgb(156 163 175); stroke-width: 1px;' strokeDasharray = '4 3' markerColor = 'rgb(156 163 175)' break case 'trigger-asset': - style = 'stroke: rgb(107 114 128); stroke-width: 2px;' + style = 'stroke: rgb(107 114 128); stroke-width: 1.25px;' animated = flowAnimated markerColor = 'rgb(107 114 128)' label = 'triggers' labelStyle = 'fill: rgb(107 114 128); font-size: 10px; font-weight: 600;' break case 'trigger-native': - style = 'stroke: rgb(107 114 128); stroke-width: 2px;' + style = 'stroke: rgb(107 114 128); stroke-width: 1.25px;' strokeDasharray = '6 3' markerColor = 'rgb(107 114 128)' label = 'triggers' @@ -1151,7 +2035,7 @@ // Library → consumer: violet dashed, visually apart from both // lineage (blue/gray solid) and trigger (gray dashed) families — // it's a code dependency, not data flow or execution. - style = 'stroke: rgb(139 92 246); stroke-width: 1.25px;' + style = 'stroke: rgb(139 92 246); stroke-width: 1px;' strokeDasharray = '5 3' markerColor = 'rgb(139 92 246)' label = e.via_use ? 'uses lib' : 'macros' @@ -1161,7 +2045,7 @@ // Producer → tested script: amber dashed ordering link. Not // data flow (blue/gray) nor execution trigger (gray "triggers") // — it only says "the test needs this asset to exist first". - style = 'stroke: rgb(217 119 6); stroke-width: 1.25px;' + style = 'stroke: rgb(217 119 6); stroke-width: 1px;' strokeDasharray = '5 3' markerColor = 'rgb(217 119 6)' label = 'test needs' @@ -1171,7 +2055,7 @@ // model → model inside one dbt project. Orange, matching the // dbt badges, and dashed because the edge is dbt's own lineage // rather than a Windmill read/write the cascade acts on. - style = 'stroke: rgb(234 88 12); stroke-width: 1.25px;' + style = 'stroke: rgb(234 88 12); stroke-width: 1px;' strokeDasharray = '4 3' markerColor = 'rgb(234 88 12)' label = 'ref' @@ -1208,7 +2092,7 @@ // (red dashed dimmed — fresh draft annotation that also has // no matching row, which is the common case). if (e.missing) { - style = 'stroke: rgb(239 68 68); stroke-width: 2px;' + style = 'stroke: rgb(239 68 68); stroke-width: 1.25px;' strokeDasharray = '3 3' markerColor = 'rgb(239 68 68)' label = 'missing trigger' @@ -1246,8 +2130,8 @@ style, markerEnd: { type: MarkerType.ArrowClosed, - width: 14, - height: 14, + width: 12, + height: 12, color: markerColor } } @@ -1265,6 +2149,7 @@ const nodeTypes = { asset: AssetNode as any, + 'no-asset': AssetNode as any, runnable: RunnableNode as any, trigger: TriggerNode as any, add: AddNode as any, @@ -1276,6 +2161,9 @@ } function handleNodeClick({ node }: { node: Node }) { + clearTimeout(hoverTimer) + hoveredNodeId = undefined + clickedNodeId = node.id // Bounded-run pick mode intercepts clicks: an eligible (downstream) // node toggles as an end bound; the start, dimmed nodes, and // triggers/+ are inert. Selection (details pane) is suppressed so the @@ -1319,12 +2207,20 @@ ) { return } + activeTriggerId = undefined onselect(undefined) } </script> <!-- svelte-ignore a11y_click_events_have_key_events, a11y_no_static_element_interactions --> -<div class="w-full h-full relative" bind:clientWidth={paneWidth} onclickcapture={handleBackgroundClick}> +<div + class="w-full h-full relative" + data-asset-canvas={canvasId} + bind:this={flowEl} + bind:clientWidth={paneWidth} + onclickcapture={handleBackgroundClick} + oncontextmenu={handleContextMenu} +> <SvelteFlow {nodes} {edges} @@ -1342,12 +2238,42 @@ defaultEdgeOptions={{ type: 'asset' }} proOptions={{ hideAttribution: true }} onnodeclick={handleNodeClick} + onnodepointerenter={({ node }) => onNodePointerEnter(node.id)} + onnodepointerleave={onNodePointerLeave} + onedgepointerenter={onEdgeEnter} + onedgepointerleave={onEdgeLeave} --background-color={false} > <div class="absolute inset-0 !bg-surface-secondary h-full"></div> - <InitialFitView {nodes} fitKey={viewportFitKey} /> + <InitialFitView {nodes} fitKey={`${viewportFitKey}:${assetsOnly}`} /> <PanToNode targetId={panToNodeId} {nodes} /> <Controls position="top-right" orientation="horizontal" showLock={false} class="!mr-10" /> + {#if assetsOnlyToggle} + <Panel position="top-left" class="!m-3 flex flex-col gap-1.5"> + <Toggle + checked={!assetsOnly} + size="xs" + options={{ right: 'Show scripts and triggers' }} + on:change={(e) => { + assetsOnly = !e.detail + if (assetsOnlyFolder != undefined) setAssetsOnlyFolder(assetsOnlyFolder, assetsOnly) + }} + /> + {#if withoutPassive.dropped > 0} + <Toggle + checked={showPassiveReads} + size="xs" + options={{ right: "Show reads that don't trigger runs" }} + on:change={(e) => { + showPassiveReads = e.detail + try { + localStorage.setItem(SHOW_PASSIVE_READS_KEY, String(e.detail)) + } catch {} + }} + /> + {/if} + </Panel> + {/if} {#if showMinimap} <!-- Node hues mirror the canvas: blue asset cards, amber triggers, bordered neutral script cards. Visible strokes + rounded corners + @@ -1379,21 +2305,173 @@ </SvelteFlow> </div> +<svelte:window + onpointerdown={(e) => { + if (paneMenu && !(e.target as HTMLElement | null)?.closest('[data-pane-menu]')) + paneMenu = undefined + }} + onkeydown={(e) => { + if (e.key === 'Escape') paneMenu = undefined + }} +/> + +{#if paneMenu} + <div + class="fixed {getContextMenuContainerClass()}" + style="left: {paneMenu.x}px; top: {paneMenu.y}px;" + transition:fly={{ duration: 150, y: -10 }} + role="menu" + data-pane-menu + > + <button + type="button" + role="menuitem" + class="{CONTEXT_MENU_ITEM_BASE_CLASS} {CONTEXT_MENU_ITEM_HOVER_CLASS} gap-2 w-full text-left" + onclick={() => { + if (paneMenu) addMenuAt = paneMenu + paneMenu = undefined + addMenuSignal++ + }} + > + <Plus size={14} /> + Add data source + </button> + </div> +{/if} + +{#if onDrag} + <svg class="fixed inset-0 w-screen h-screen pointer-events-none z-50" aria-hidden="true"> + <line + x1={onDrag.from.x} + y1={onDrag.from.y} + x2={onDrag.to.x} + y2={onDrag.to.y} + class="stroke-blue-500" + stroke-width="1.5" + stroke-dasharray="4 3" + /> + {#if !(onDrag.feed && onDrag.blank)} + <circle cx={onDrag.to.x} cy={onDrag.to.y} r="3" class="fill-blue-500" /> + {/if} + </svg> + {#if onDrag.feed && onDrag.blank} + <div + class="fixed z-50 pointer-events-none -translate-x-1/2 -translate-y-1/2" + style="left: {onDrag.to.x}px; top: {onDrag.to.y}px;" + > + <AddDownstreamPill expanded /> + </div> + {/if} +{/if} + +{#if feedMenu && onAddScriptForAsset} + <div + class="fixed z-10 -translate-x-1/2 -translate-y-1/2" + style="left: {feedMenu.at.x}px; top: {feedMenu.at.y}px;" + > + <AddDownstreamMenu + asset={feedMenu.asset} + onAddScript={onAddScriptForAsset} + pathPrefix={feedMenu.data.pathPrefix ?? pathPrefix} + defaultPathSuffix={feedMenu.data.defaultPathSuffix ?? defaultPathSuffix} + openSignal={feedMenuSignal} + > + {#snippet trigger({ open })} + {#if open} + <AddDownstreamPill expanded /> + {/if} + {/snippet} + </AddDownstreamMenu> + </div> +{/if} + +{#if hoveredEdge && hoveredEdgeText} + {@const d = hoveredEdgeText} + {@const actions = hoveredEdgeActions} + <!-- svelte-ignore a11y_no_static_element_interactions --> + <div + class="fixed z-50 max-w-80 rounded-md border bg-surface px-2.5 py-1.5 text-xs text-primary shadow-md" + style="left: {hoveredEdge.x + 12}px; top: {hoveredEdge.y + 12}px;" + transition:fly={{ duration: 120, y: -4 }} + role="tooltip" + onmouseenter={() => clearTimeout(edgeHoverTimer)} + onmouseleave={onEdgeLeave} + > + <span class="font-semibold text-emphasis">{d.subject}</span> + {d.phrase} + {#if d.object}<span class="font-semibold text-emphasis">{d.object}</span>{/if} + {#if d.note}<div class="mt-0.5 text-2xs text-secondary">{d.note}</div>{/if} + {#each actions as action (action.label)} + <div class="mt-2 flex flex-col gap-0.5"> + <Button + variant="default" + unifiedSize="sm" + onclick={() => { + // Closing the popover drops `actions`: run what this one held. + const run = action.run + hoveredEdge = undefined + run() + }} + > + {action.label} + </Button> + <span class="text-2xs text-secondary">{action.detail}</span> + </div> + {/each} + </div> +{/if} + +{#if scheduleWizard} + <div class="fixed w-0 h-0" style="left: {scheduleWizard.at.x}px; top: {scheduleWizard.at.y}px;"> + <PipelineInsertMenu + kinds={[{ id: 'schedule', label: 'On schedule', description: '', icon: Clock }]} + onPick={() => {}} + openSignal={scheduleWizardSignal} + scheduleFor={scheduleWizard.script} + onSchedule={(s) => scheduleWizard?.onSchedule(s)} + > + {#snippet trigger()} + <span class="block w-0 h-0" aria-hidden="true"></span> + {/snippet} + </PipelineInsertMenu> + </div> +{/if} + +{#if onAddPipelineScript} + <div class="fixed w-0 h-0" style="left: {addMenuAt.x}px; top: {addMenuAt.y}px;"> + <AddDataSourceMenu + {onAddPipelineScript} + {pathPrefix} + {defaultPathSuffix} + openSignal={addMenuSignal} + > + {#snippet trigger()} + <span class="block w-0 h-0" aria-hidden="true"></span> + {/snippet} + </AddDataSourceMenu> + </div> +{/if} + <style lang="postcss"> :global(.svelte-flow__handle) { opacity: 0; } + /* Dragging a script's dot: what it cannot subscribe to recedes. */ + :global(.svelte-flow__node.wm-drag-dim) { + opacity: 0.25; + transition: opacity 120ms; + } + :global(.svelte-flow__node.wm-drag-over .drop-shadow-sm) { + @apply ring-2 ring-blue-500 rounded-md; + } :global(.svelte-flow__controls-button) { @apply bg-surface border-0; } :global(.svelte-flow__controls-button:hover) { @apply bg-surface-hover; } - :global(.svelte-flow__node.selected .drop-shadow-sm) { - @apply outline outline-2 outline-blue-500; - } /* Activity-panel emphasis — soft, monochromatic, less prominent than the - blue details selection above. Hover is a thin neutral ring (transient); + node's own selected state. Hover is a thin neutral ring (transient); pinning an expanded run is a soft-blue ring. */ /* A dbt project node and the models it materializes, related by badge rather than by edges — hovering either lights up the whole set. */ @@ -1427,6 +2505,11 @@ :global(.svelte-flow__node.wm-bound-end .drop-shadow-sm) { @apply outline outline-[3px] outline-amber-500; } + /* Hovering a node fades what is not in its lineage (see lineageFadeCss). */ + :global(.svelte-flow__node), + :global(.svelte-flow__edge) { + transition: opacity 120ms; + } :global(.svelte-flow__node.wm-bound-dim) { @apply opacity-30; } diff --git a/frontend/src/lib/components/assets/AssetGraph/AssetGraphDetailsPane.svelte b/frontend/src/lib/components/assets/AssetGraph/AssetGraphDetailsPane.svelte index 6050c2d1cd..4577a11915 100644 --- a/frontend/src/lib/components/assets/AssetGraph/AssetGraphDetailsPane.svelte +++ b/frontend/src/lib/components/assets/AssetGraph/AssetGraphDetailsPane.svelte @@ -2,7 +2,6 @@ import { ScriptService, type Script, type ScriptLang } from '$lib/gen' import { untrack } from 'svelte' import { resource } from 'runed' - import { base } from '$lib/base' import Button from '$lib/components/common/button/Button.svelte' import ScriptEditor from '$lib/components/ScriptEditor.svelte' import AssetGenericIcon from '$lib/components/icons/AssetGenericIcon.svelte' @@ -20,10 +19,17 @@ SquareFunction, Trash2, X, - Pencil + Pencil, + ChevronDown, + Zap } from 'lucide-svelte' - import Popover from '$lib/components/meltComponents/Popover.svelte' - import { tick } from 'svelte' + import DropdownV2 from '$lib/components/DropdownV2.svelte' + import { + upstreamScriptItems, + upstreamTriggerItems, + type UpstreamScript, + type UpstreamTriggerAction + } from './upstreamScriptItems' import { inferArgs } from '$lib/infer' import { emptySchema, sendUserToast } from '$lib/utils' import type { Schema } from '$lib/common' @@ -41,6 +47,7 @@ import { extractDraftMacros } from './resolveGraph' import { assetColumnNodes, type ColumnLineageGraph } from './columnLineageGraph' import SummaryPathDisplay from '$lib/components/SummaryPathDisplay.svelte' + import Badge from '$lib/components/common/badge/Badge.svelte' import S3FilePreview from '$lib/components/S3FilePreview.svelte' import DataTablePreview from './DataTablePreview.svelte' import DucklakeAssetPanel from './DucklakeAssetPanel.svelte' @@ -117,7 +124,9 @@ // (`onDraftPersist`). `onDraftPersist` stays the authoritative commit on // navigate-away; this is the continuous feed that keeps the draft's // server copy current while the user is still typing. - onContentChange?: (scriptPath: string | undefined, content: string) => void + // `base`: the deployed copy being edited, so the parent can autosave unsaved + // edits to it before they are promoted to a draft. Unset for a draft. + onContentChange?: (scriptPath: string | undefined, content: string, base?: Script) => void // Fires when the user navigates away from a draft (selects another // node, closes the pane, etc.) — the parent must persist the new // content + write outputs into its drafts Map. Without this, @@ -133,7 +142,8 @@ writes: { kind: AssetWithAltAccessType['kind']; path: string }[] // Body-inferred reads, so the parent's draft keeps its input // lineage while inactive (no live inference runs for it). - reads: { kind: AssetWithAltAccessType['kind']; path: string }[] + // Undefined when nothing was inferred: keep what the draft has. + reads?: { kind: AssetWithAltAccessType['kind']; path: string }[] // Full edited script — set when the source is a persisted // script (needed to seed a brand-new draft entry). script?: Script @@ -156,6 +166,12 @@ path: string unsaved?: boolean }> + /** The selected asset's producing scripts, for its "Edit script" action, + * which calls `onEditScript` with the one picked. */ + producerScripts?: UpstreamScript[] + onEditScript?: (path: string) => void + /** The selected asset's upstream triggers that can be opened from here. */ + producerTriggers?: UpstreamTriggerAction[] // Pipeline-wide column-lineage graph (built by the parent page from the // resolved graph). Drives the transitive column-lineage trace shown for a // selected materialized asset. @@ -215,15 +231,18 @@ // the edges. Counter rather than boolean so back-to-back runs // re-fire the effect even if no other prop changed. requestRunSignal?: number - // Folder-scoped non-editable prefix shown next to the suffix - // editor when the user renames a draft (e.g. `f/<folder>/`). The - // new path = pathPrefix + suffix. - pathPrefix?: string // Called when the user renames a draft — the parent reseats the // path key in its drafts map and updates activeDraftPath. Returns // true on success; false on collision/validation failure so the // popover can keep itself open and surface the error inline. onDraftPathChange?: (oldPath: string, newPath: string) => boolean | string + onDraftMetaChange?: ( + path: string, + meta: { summary: string; labels: string[] | undefined } + ) => void + // The pipeline's folder prefix (`f/<folder>/`). A draft renamed outside it + // would be deployed out of the pipeline, so the rename is refused. + pathPrefix?: string // Bumped by the parent (e.g. from the runnable-node action menu) to // auto-open the archive/delete confirmation modal for the currently // loaded persisted script. No-ops while the pane is showing a draft @@ -280,6 +299,19 @@ // can persist a data-upload entry's staged input (drives node readiness). // `isValid` is the full-schema validity, not just "file present". onRunFormArgsChange?: (path: string, args: Record<string, any>, isValid: boolean) => void + // Show only the open script's inputs and runs (a data-upload click), not + // its editor. `onRunInputs` runs it with them, drafts included, and + // `onShowScript` leaves this view for the script. + inputsOnly?: boolean + /** `live` is the pane's buffer when it differs from what is stored: always + * for a draft, and for a deployed script edited before switching to the + * inputs view. A run with it previews that body. */ + onRunInputs?: ( + path: string, + args: Record<string, any>, + live?: { content: string; language: ScriptLang } + ) => Promise<string | undefined> + onShowScript?: () => void } let { selection, @@ -301,6 +333,9 @@ onScriptRenamed, onScriptRemoved, selectionProducers = [], + producerScripts = [], + onEditScript, + producerTriggers = [], selectionColumnGraph, selectionColumnLoading = false, selectionColumnTruncated = false, @@ -315,8 +350,9 @@ activeRunnable, onTestStateChange, requestRunSignal, - pathPrefix = '', onDraftPathChange, + onDraftMetaChange, + pathPrefix = '', requestRemoveSignal, downstreamSubscribers = 0, onStartBoundedRun, @@ -328,10 +364,15 @@ onRunByPath, onRunCascadeByPath, runFormInitialArgs, - onRunFormArgsChange + onRunFormArgsChange, + inputsOnly = false, + onRunInputs, + onShowScript }: Props = $props() let readOnly = $derived(mode !== 'edit') + // Someone who cannot switch the pipeline to edit mode only gets to read it. + let editScriptLabel = $derived(readOnly && !onRequestEdit ? 'Open script' : 'Edit script') // Root element of the pane — used to scope the S3-input lookup for the // data_upload focus effect. @@ -408,7 +449,7 @@ // PipelineScriptView renders instead of the test panel. let viewReadyForTarget = $derived.by( () => - readOnly && + (readOnly || inputsOnly) && runTargetPath !== undefined && script?.path === runTargetPath && (isDraft || (!scriptRes.loading && scriptRes.current?.path === runTargetPath)) @@ -484,6 +525,12 @@ // alongside `liveBodyAssets` and forwarded so the live graph can show // inferred column lineage on the edited script before it deploys. let liveColumnLineage = $state<ColumnLineage[] | undefined>(undefined) + // The script whose editor last bound `liveBodyAssets` (undefined there means it + // inferred nothing). They stay bound after that editor unmounts, so a script + // that never had one (the inputs-only view) must not report or persist them as + // its lineage. Set by an effect declared after the save-on-switch one, whose + // cleanup still needs the previous owner when the selection moves. + let liveAssetsOwner: string | undefined = undefined // Bumped when the runs panel reports a watched job has reached a // terminal state. Drives S3FilePreview's refreshKey so the preview @@ -549,7 +596,9 @@ let args = $state<Record<string, any>>({}) let argsSeedPath: string | undefined = undefined $effect.pre(() => { - const p = script?.path + // Re-seeded on leaving the inputs-only view too, so the file picked there + // shows in the editor's test form. + const p = script?.path === undefined ? undefined : `${script.path}|${inputsOnly}` if (p === argsSeedPath) return argsSeedPath = p args = runFormInitialArgs ? structuredClone($state.snapshot(runFormInitialArgs)) : {} @@ -559,7 +608,8 @@ // required field (not just the S3 file) is satisfied. let runFormIsValid = $state(true) $effect(() => { - if (readOnly || !script) return + // Inputs-only mounts no ScriptEditor: PipelineScriptView reports its own args. + if (readOnly || inputsOnly || !script) return onRunFormArgsChange?.(script.path, $state.snapshot(args), runFormIsValid) }) @@ -596,18 +646,25 @@ b: Array<{ kind: string; path: string }> ) => a.length === b.length && a.every((x, i) => x.kind === b[i]?.kind && x.path === b[i]?.path) return () => { - const writes = (liveBodyAssets ?? []) + // No editor inferred this script (the inputs-only view): keep its stored + // lineage rather than persisting it as empty. + const inferred = liveAssetsOwner === captured.path + const writes = !inferred + ? (writesAtRegister ?? []) + : (liveBodyAssets ?? []) .filter((a) => { const t = a.access_type ?? a.alt_access_type return t === 'w' || t === 'rw' }) .map((a) => ({ kind: a.kind, path: a.path })) - const reads = (liveBodyAssets ?? []) - .filter((a) => { - const t = a.access_type ?? a.alt_access_type - return t === 'r' || t === 'rw' - }) - .map((a) => ({ kind: a.kind, path: a.path })) + const reads = !inferred + ? readsAtRegister + : (liveBodyAssets ?? []) + .filter((a) => { + const t = a.access_type ?? a.alt_access_type + return t === 'r' || t === 'rw' + }) + .map((a) => ({ kind: a.kind, path: a.path })) // Draft runs: emit only when content or lineage changed in THIS clone. // An unconditional emit ping-pongs forever when the entry is rewritten // externally while the pane stays mounted (rename rekey, AI edit): @@ -617,6 +674,7 @@ (captured.content ?? '') === contentAtRegister && refsEq(writesAtRegister ?? [], writes) && readsAtRegister != undefined && + reads != undefined && refsEq(readsAtRegister, reads) ) return @@ -651,12 +709,42 @@ } }) + $effect(() => { + if (script && !readOnly && !inputsOnly) liveAssetsOwner = script.path + }) + let saving = $state(false) // What this pane last deployed, so the persist-back cleanup can tell "the // buffer equals the new deployed head" from real unsaved edits (plain // variable: only read inside the untracked cleanup). let deployedFromPane: { path: string; content: string } | undefined = undefined let isDraft = $derived(draftScript != undefined) + function liveBody(): { content: string; language: ScriptLang } | undefined { + if (!script) return undefined + const live = { content: script.content ?? '', language: script.language as ScriptLang } + if (isDraft) return live + const orig = scriptRes.current + return orig?.path === script.path && (orig.content ?? '') !== live.content ? live : undefined + } + // A draft's stored schema is empty until an editor infers it, and the inputs + // view mounts none: infer from the body here so its fields (the file picker) + // show up. + const inputsSchema = resource( + [() => (inputsOnly && isDraft ? script?.content : undefined), () => script?.language], + async ([content, language]) => { + if (content === undefined || !language) return undefined + const schema = emptySchema() + try { + await inferArgs(language, content, schema as Schema) + } catch { + return undefined + } + return schema + } + ) + let inputsScript = $derived( + script && inputsSchema.current ? { ...script, schema: inputsSchema.current } : undefined + ) // Single trash-bin button opens one modal that exposes both Archive // (always available) and Delete permanently (admin-only). Archive is @@ -763,12 +851,17 @@ onAnnotationsChange?.(script?.path, liveAnnotations) }) $effect(() => { - if (readOnly) return + if (readOnly || (inputsOnly && liveAssetsOwner !== script?.path)) return onAssetsChange?.(script?.path, liveBodyAssets ?? [], liveColumnLineage) }) $effect(() => { if (readOnly) return - onContentChange?.(script?.path, script?.content ?? '') + const base = draftScript ? undefined : scriptRes.current + onContentChange?.( + script?.path, + script?.content ?? '', + base && base.path === script?.path ? base : undefined + ) }) async function save() { @@ -910,49 +1003,6 @@ JSON.stringify(script.schema ?? null) === JSON.stringify(orig.schema ?? null) ) }) - - // Suffix editor for the draft-path popover. Seeded from the current - // path each time the popover opens so the user starts with what they - // see, not stale state from an earlier rename. - let draftPathSuffix = $state('') - let draftPathError = $state<string | undefined>(undefined) - let draftPathInput: HTMLInputElement | undefined = $state(undefined) - - function suffixOf(fullPath: string): string { - return fullPath.startsWith(pathPrefix) ? fullPath.slice(pathPrefix.length) : fullPath - } - - async function openDraftPathEditor() { - draftPathSuffix = script ? suffixOf(script.path) : '' - draftPathError = undefined - await tick() - draftPathInput?.focus() - draftPathInput?.select() - } - - function confirmDraftPath(close: () => void) { - if (!script) return - const suffix = draftPathSuffix.trim() - if (!suffix) { - draftPathError = 'Path cannot be empty' - return - } - const newPath = pathPrefix + suffix - if (newPath === script.path) { - close() - return - } - const result = onDraftPathChange?.(script.path, newPath) - if (result === true || result === undefined) { - script.path = newPath - draftPathError = undefined - close() - } else if (typeof result === 'string') { - draftPathError = result - } else { - draftPathError = 'Path already in use' - } - } </script> <div class="flex flex-col h-full bg-surface" bind:this={paneEl}> @@ -964,80 +1014,34 @@ {@const draftScriptPath = script.path} <Code2 size={16} class="shrink-0 text-tertiary" /> {#if onDraftPathChange && !readOnly} - <!-- Inline rename popover for drafts. The persisted-script - branch uses SummaryPathDisplay which round-trips through - updateItemPathAndSummary; drafts have no server row yet, - so we just rekey the parent's drafts map locally. --> - <Popover - placement="bottom-start" - contentClasses="p-3" - usePointerDownOutside - on:openChange={(e) => { - if (e.detail) openDraftPathEditor() + <!-- Same summary/path popover as a deployed script, saved into the + drafts map instead of through the API: a draft has no row yet. --> + <SummaryPathDisplay + summary={script.summary ?? ''} + path={draftScriptPath} + labels={script.labels ?? []} + kind="script" + onSaved={() => {}} + saveOverride={({ path, summary, labels }) => { + if (pathPrefix && (!path.startsWith(pathPrefix) || path === pathPrefix)) { + return `A pipeline script stays in ${pathPrefix}: pick a name inside that folder` + } + // Before the rename, which carries the draft entry over as it is. + onDraftMetaChange?.(draftScriptPath, { summary, labels }) + if (script) { + script.summary = summary + script.labels = labels + } + if (path === draftScriptPath) return undefined + const result = onDraftPathChange(draftScriptPath, path) + if (result !== true && result !== undefined) { + return typeof result === 'string' ? result : 'Path already in use' + } + if (script) script.path = path + return undefined }} - > - {#snippet trigger()} - <button - type="button" - class="flex flex-col min-w-0 text-left px-2 py-1 rounded-md hover:bg-surface-hover transition-colors group" - title="Edit draft path" - > - <span - class="text-3xs uppercase tracking-wide text-tertiary flex items-center gap-1" - > - Draft pipeline script - <Pencil size={9} class="opacity-0 group-hover:opacity-60 transition-opacity" /> - </span> - <span class="text-xs font-mono truncate" title={draftScriptPath} - >{draftScriptPath}</span - > - </button> - {/snippet} - {#snippet content({ close })} - <div class="flex flex-col gap-2 w-[420px]"> - <span class="text-2xs font-normal text-secondary">Path</span> - <div - class="flex items-stretch border rounded-md bg-surface overflow-hidden focus-within:ring-2 focus-within:ring-blue-400" - > - {#if pathPrefix} - <span - class="flex items-center px-2 bg-surface-secondary text-tertiary text-sm font-mono border-r select-none" - > - {pathPrefix} - </span> - {/if} - <input - bind:this={draftPathInput} - bind:value={draftPathSuffix} - onkeydown={(e) => { - if (e.key === 'Enter') { - e.preventDefault() - confirmDraftPath(close) - } else if (e.key === 'Escape') { - e.preventDefault() - close() - } - }} - class="flex-1 min-w-0 px-2 py-1.5 text-sm font-mono bg-transparent focus:outline-none" - placeholder="my_script" - /> - </div> - {#if draftPathError} - <span class="text-2xs text-red-500">{draftPathError}</span> - {/if} - <div class="flex justify-end"> - <Button - variant="accent" - unifiedSize="sm" - disabled={!draftPathSuffix.trim()} - onClick={() => confirmDraftPath(close)} - > - Rename - </Button> - </div> - </div> - {/snippet} - </Popover> + /> + <Badge color="gray">Draft</Badge> {:else} <div class="flex flex-col min-w-0"> <span class="text-3xs uppercase tracking-wide text-tertiary"> @@ -1097,6 +1101,66 @@ {/if} </div> <div class="flex items-center gap-1 shrink-0"> + {#if selection?.kind === 'asset' && onEditScript && producerScripts.length === 1} + <Button + variant="default" + unifiedSize="sm" + startIcon={{ icon: Pencil }} + onclick={() => onEditScript(producerScripts[0].path)} + title={`Open ${producerScripts[0].path}, which builds this asset`} + > + {editScriptLabel} + </Button> + {:else if selection?.kind === 'asset' && onEditScript && producerScripts.length > 1} + <DropdownV2 + items={upstreamScriptItems(producerScripts, onEditScript)} + placement="bottom-end" + enableFlyTransition + > + {#snippet buttonReplacement()} + <Button + nonCaptureEvent + variant="default" + unifiedSize="sm" + startIcon={{ icon: Pencil }} + endIcon={{ icon: ChevronDown }} + title={`${producerScripts.length} scripts build this asset`} + > + {editScriptLabel} + </Button> + {/snippet} + </DropdownV2> + {/if} + {#if selection?.kind === 'asset' && producerTriggers.length === 1} + <Button + variant="default" + unifiedSize="sm" + startIcon={{ icon: Zap }} + onclick={() => producerTriggers[0].onOpen()} + title={producerTriggers[0].detail} + > + {producerTriggers[0].label} + </Button> + {:else if selection?.kind === 'asset' && producerTriggers.length > 1} + <DropdownV2 + items={upstreamTriggerItems(producerTriggers)} + placement="bottom-end" + enableFlyTransition + > + {#snippet buttonReplacement()} + <Button + nonCaptureEvent + variant="default" + unifiedSize="sm" + startIcon={{ icon: Zap }} + endIcon={{ icon: ChevronDown }} + title={`${producerTriggers.length} triggers start the scripts that build this asset`} + > + Triggers + </Button> + {/snippet} + </DropdownV2> + {/if} {#if readOnly && onRequestEdit} <Button variant="accent" @@ -1118,28 +1182,17 @@ title="Discard draft" /> {/if} - <!-- Action order, left → right: trash, external link, save, close. - Save sits closest to Close so the primary commit action is - anchored at the right edge of the bar; trash lives at the - far left so destructive ops are visually separated from - navigation/commit. Mirrors the draft Discard placement. --> - {#if !readOnly && !isDraft && isScriptView && script?.hash} - <Button - variant="subtle" - unifiedSize="sm" - startIcon={{ icon: Trash2 }} - onclick={() => (removeOpen = true)} - iconOnly - title="Archive or delete" - /> - {/if} + <!-- Action order, left → right: external link, save, close. Save sits + closest to Close so the primary commit action is anchored at the + right edge of the bar. Removing a script goes through its node's + menu. --> {#if !readOnly && !isDraft && selection?.kind === 'runnable'} <Button variant="subtle" unifiedSize="sm" href={selection.runnable_kind === 'flow' - ? `${base}/flows/edit/${selection.path}` - : `${base}/scripts/edit/${selection.path}`} + ? `/flows/edit/${selection.path}` + : `/scripts/edit/${selection.path}`} target="_blank" startIcon={{ icon: ExternalLink }} iconOnly @@ -1331,21 +1384,38 @@ {#if readOnly} Flows have no inline view here. Open <a class="text-blue-600 hover:underline" - href="{base}/flows/get/{selection.path}">the flow page</a + href="/flows/get/{selection.path}">the flow page</a > for details and runs. {:else} Flows are not editable inline. Use the open-in-editor button above. {/if} </div> {:else if !isDraft && scriptRes.loading && !script} - <div class="absolute inset-0 flex items-center justify-center gap-2 text-tertiary"> - <Loader2 size={16} class="animate-spin" /> - <span class="text-xs">Loading script…</span> - </div> + <!-- Blank while the script loads: the fetch is short, and a spinner only flashes. --> {:else if !isDraft && scriptRes.error} <div class="p-3 text-xs text-red-500"> Failed to load: {scriptRes.error.message} </div> + {:else if script && inputsOnly} + {#key script.path} + <PipelineScriptView + {isDraft} + canRun + runsDrafts + inputsOnly + {onShowScript} + onRun={onRunInputs && ((path, args) => onRunInputs(path, args, liveBody()))} + script={inputsScript ?? script} + {runsRefreshKey} + {runsPendingJobId} + initialArgs={runFormInitialArgs} + onArgsChange={onRunFormArgsChange} + onRunCompleted={() => { + previewRefreshKey += 1 + onRunCompleted?.() + }} + /> + {/key} {:else if script && readOnly} <!-- Read-only modes: no Monaco/ScriptEditor (operators are backend-blocked from previews anyway) — highlighted source, diff --git a/frontend/src/lib/components/assets/AssetGraph/AssetGraphEdge.svelte b/frontend/src/lib/components/assets/AssetGraph/AssetGraphEdge.svelte index f39c2d8d18..a6d38b05d8 100644 --- a/frontend/src/lib/components/assets/AssetGraph/AssetGraphEdge.svelte +++ b/frontend/src/lib/components/assets/AssetGraph/AssetGraphEdge.svelte @@ -1,6 +1,7 @@ <script lang="ts"> import { BaseEdge, getBezierPath, type EdgeProps } from '@xyflow/svelte' import { NODE } from '$lib/components/graph/util' + import { PIPELINE_NODE_HEIGHT } from './assetGraphLayout' import { FlaskConical, Columns3, SquareFunction, BellOff } from 'lucide-svelte' import type { ColumnLineage, DataTest } from './parsePipelineAnnotations' @@ -103,33 +104,42 @@ // straight under the nodes in between — the child-and-grandchild-of-the- // same-node case, where the tidy-tree layout puts all three on one // column. Detour those through the gutter beside the column. - const SKIP_DY = NODE.gap.vertical * 2 + NODE.height + const SKIP_DY = NODE.gap.vertical * 2 + PIPELINE_NODE_HEIGHT const NEAR_VERTICAL_DX = NODE.width / 4 // Lane offset: half a node plus a margin that stays inside the // inter-column gutter (gap.horizontal / 2). const LANE = NODE.width / 2 + NODE.gap.horizontal / 2 - const CORNER = 14 - // Rounded-orthogonal detour: drop out of the source, swing into the - // gutter lane at `midX`, run it down past the intermediate rows, swing - // back into the target. + // Detour through the gutter lane at `midX`, drawn with the same curves as + // every other edge: curve out of the source into the lane within the gap + // below it, run down the lane past the rows in between, curve into the + // target within the gap above it. function gutterPath(midX: number): string { - const yTop = sourceY + 24 - const yBot = targetY - 24 - const outDir = midX > sourceX ? 1 : -1 - const inDir = targetX > midX ? 1 : -1 - return [ - `M ${sourceX} ${sourceY}`, - `L ${sourceX} ${yTop - CORNER}`, - `Q ${sourceX} ${yTop} ${sourceX + outDir * CORNER} ${yTop}`, - `L ${midX - outDir * CORNER} ${yTop}`, - `Q ${midX} ${yTop} ${midX} ${yTop + CORNER}`, - `L ${midX} ${yBot - CORNER}`, - `Q ${midX} ${yBot} ${midX + inDir * CORNER} ${yBot}`, - `L ${targetX - inDir * CORNER} ${yBot}`, - `Q ${targetX} ${yBot} ${targetX} ${yBot + CORNER}`, - `L ${targetX} ${targetY}` - ].join(' ') + const bend = NODE.gap.vertical + const yTop = sourceY + bend + // Clamp only downward edges: an upward (feedback) edge must still run up the + // lane, or its last curve cuts across the node the detour was clearing. + const yBot = targetY > sourceY ? Math.max(yTop, targetY - bend) : targetY - bend + const [out] = getBezierPath({ + sourceX, + sourceY, + sourcePosition, + targetX: midX, + targetY: yTop, + targetPosition, + curvature: 0.25 + }) + const [into] = getBezierPath({ + sourceX: midX, + sourceY: yBot, + sourcePosition, + targetX, + targetY, + targetPosition, + curvature: 0.25 + }) + // Continue from the lane rather than lifting the pen. + return `${out} L${midX},${yBot} ${into.replace(/^M/, 'L')}` } // Long edges bend out of the source within the layer gap and descend in @@ -178,7 +188,7 @@ path={edgePath} {markerEnd} {style} - interactionWidth={0} + interactionWidth={12} label={undefined} labelStyle={undefined} /> diff --git a/frontend/src/lib/components/assets/AssetGraph/AssetNode.svelte b/frontend/src/lib/components/assets/AssetGraph/AssetNode.svelte index e719bfe2bd..d0835b2880 100644 --- a/frontend/src/lib/components/assets/AssetGraph/AssetNode.svelte +++ b/frontend/src/lib/components/assets/AssetGraph/AssetNode.svelte @@ -2,9 +2,14 @@ import { Handle, Position } from '@xyflow/svelte' import { twMerge } from 'tailwind-merge' import AssetGenericIcon from '$lib/components/icons/AssetGenericIcon.svelte' - import { formatShortAssetPath, type AssetKind } from '$lib/components/assets/lib' - import { NODE } from '$lib/components/graph/util' - import PipelineInsertMenu, { type PipelineInsertPick } from './PipelineInsertMenu.svelte' + import { formatAssetKind, formatShortAssetPath, type AssetKind } from '$lib/components/assets/lib' + import PipelineNodeCard from './PipelineNodeCard.svelte' + import NodeActionsMenu from './NodeActionsMenu.svelte' + import NodeFixButton, { type NodeFix } from './NodeFixButton.svelte' + import NodeOnDot from './NodeOnDot.svelte' + import { PIPELINE_NODE_HEADER } from './assetGraphLayout' + import AddDownstreamMenu from './AddDownstreamMenu.svelte' + import AddDownstreamPill from './AddDownstreamPill.svelte' import { ArrowUpRight, Code2, @@ -12,19 +17,28 @@ History, Play, Loader2, - Plus, ShieldCheck, ShieldAlert, CheckCircle2, + ChevronDown, + Pencil, + CircleSlash, + Trash2, + Upload, XCircle } from 'lucide-svelte' + import { Button } from '$lib/components/common' import type { ScriptLang } from '$lib/gen' import { enterpriseLicense } from '$lib/stores' - import { sendUserToast } from '$lib/utils' - import { PIPELINE_LANGUAGES } from './pipelineLanguages' + import { sendUserToast, type Item } from '$lib/utils' import type { PipelineOutputKind } from './pipelineTemplates' import type { DbtAssetProvenance } from './types' import DbtIcon from '$lib/components/icons/DbtIcon.svelte' + import LanguageIcon from '$lib/components/common/languageIcons/LanguageIcon.svelte' + import RunStateChip from './RunStateChip.svelte' + import DropdownV2 from '$lib/components/DropdownV2.svelte' + import { upstreamScriptItems } from './upstreamScriptItems' + import type { RunnableRunState } from './activeRunnables.svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' const operatingWorkspace = useOperatingWorkspace() @@ -33,6 +47,49 @@ // `content` / `language` so the page-level run handler can dispatch to // `runScriptPreview` instead of `runScriptByPath` (which 404s for // non-deployed scripts). + /** What starts a producing script, as its chip shows it. */ + export type TriggerChipData = { + label: string + /** The native trigger kind; a data upload renders as a call to action. */ + kind?: string + /** No chip: the node's incoming edges already show what starts it. */ + hidden?: boolean + missing?: boolean + draft?: boolean + /** Opens the trigger's editor; unset for what has none (manual, asset change). */ + onOpen?: () => void + selected?: boolean + } + + export type AssetUpstreamChips = + | { none: true } + | { + multiple: true + /** The producing scripts; one when only its triggers are ambiguous. */ + scripts: Array<{ + runnableId: string + path: string + summary?: string + language?: ScriptLang + unsaved?: boolean + onOpen: () => void + }> + /** The scripts' own triggers, each named with its script. */ + triggers: Array<TriggerChipData & { script: string }> + selected?: boolean + } + | { + runnableId: string + path: string + summary?: string + language?: ScriptLang + unsaved?: boolean + runState?: RunnableRunState + trigger: TriggerChipData + onOpen: () => void + selected?: boolean + } + export type AssetProducer = { kind: 'script' | 'flow' path: string @@ -51,6 +108,8 @@ // "current view of <dim>" marker so it reads as a derived node, not an // unrelated table. derived_from?: string + // Why the node is misconfigured, when it is: renders it red. + error?: string // dbt provenance when this warehouse table is a dbt node: which model // it is, how dbt materializes it, its tags and its generic tests. dbt?: DbtAssetProvenance @@ -65,10 +124,14 @@ language: ScriptLang, scriptPath: string, outputKind: PipelineOutputKind, - aiPrompt?: string + aiPrompt?: string, + options?: import('./PipelineInsertMenu.svelte').PipelineInsertOptions ) => void pathPrefix?: string defaultPathSuffix?: string + /** Starts dragging the "+" onto a script (subscribing it to this asset) + * or onto the blank canvas (opening the add menu there). */ + onStartFeedDrag?: (e: PointerEvent) => void // Producer scripts/flows that write to this asset, supplied by // the canvas from the graph's write/rw edges. Drives the on-hover // "Run" button. Includes unsaved/draft producers so the button @@ -99,6 +162,41 @@ // instead of only settling once the job ends. runStatus?: 'running' | 'materialized' | 'failed' runRowCount?: number | null + /** Set in the assets-only view, where the producing script and its + * trigger are folded into the asset: `none` for an asset nothing in the + * pipeline writes, `multiple` when the producer or its trigger is + * ambiguous. */ + upstream?: AssetUpstreamChips + /** What is wrong with the node, and how to fix it: replaces the "+". */ + fix?: NodeFix + /** Assets-only: errors of the scripts and triggers folded into this node. */ + foldedFixes?: NodeFix[] + /** Assets-only: starts dragging the top dot onto an asset, subscribing the + * scripts that build this one to it. */ + onStartOnDrag?: (e: PointerEvent) => void + /** The assets-only node for the scripts that build no asset. */ + noAsset?: boolean + /** The No-asset node's script, by its file name. */ + noAssetName?: string + /** Assets-only: the node is only its script's banner. */ + bannerOnly?: boolean + /** Assets-only: a script folded into the node has an error. */ + scriptError?: boolean + /** No script in the workspace writes it; a flow's write fires no asset trigger. */ + neverWritten?: boolean + /** Card width in the assets-only view, sized to its text. */ + width?: number + /** Assets-only view: the producing script and trigger no other asset + * shares, which the menu offers to delete one by one or together. */ + upstreamDelete?: import('./assetsOnlyView').AssetUpstreamDelete + /** When no combined delete is possible: the folded scripts, each deletable + * on its own. */ + scriptDeletes?: Array<{ path: string; unsaved: boolean }> + triggerDeletes?: Array<NonNullable<import('./assetsOnlyView').AssetUpstreamDelete['trigger']>> + onDeleteUpstream?: (target: import('./assetsOnlyView').AssetUpstreamDelete) => void + deleteVerb?: 'Delete' | 'Archive' + /** Why nothing can be deleted, when the producer is shared. */ + deleteBlocked?: string } // SvelteFlow injects this on the node component when the user clicks // the node. Combined with our own `hovered` state to drive the @@ -140,19 +238,94 @@ } } - function handlePick(pick: PipelineInsertPick) { - if (pick.kindId === 'pipeline_script' && pick.language && pick.path) { - data.onAddScript?.( - { kind: data.asset_kind, path: data.path }, - pick.language as ScriptLang, - pick.path, - (pick.outputKind ?? 'none') as PipelineOutputKind, - pick.aiPrompt - ) - } - } - let showAdd = $derived(data.onAddScript != undefined) + + // A red asset needs fixing where its error comes from, not a downstream step; + // and a step downstream of what nothing writes would never run on its writes. + let showAdd = $derived(data.onAddScript != undefined && !data.error && !data.neverWritten) + let menuItems: Item[] = $derived( + data.onDeleteUpstream && data.upstreamDelete + ? deleteItems(data.upstreamDelete, data.onDeleteUpstream) + : data.onDeleteUpstream && (data.scriptDeletes?.length || data.triggerDeletes?.length) + ? [ + ...(data.scriptDeletes ?? []).map((script) => ({ script })), + ...(data.triggerDeletes ?? []).map((trigger) => ({ trigger })) + ].flatMap((t) => deleteItems(t, data.onDeleteUpstream!)) + : data.deleteBlocked + ? [ + { + displayName: `Can't delete: ${data.deleteBlocked}`, + icon: Trash2, + disabled: true + } + ] + : [] + ) + const lastSegment = (p: string) => p.split('/').pop() ?? p + // A script is archived rather than deleted when the user may not delete it; + // a trigger is always deleted. + function deleteItems( + t: import('./assetsOnlyView').AssetUpstreamDelete, + run: (target: import('./assetsOnlyView').AssetUpstreamDelete) => void + ): Item[] { + const items: Item[] = [] + if (t.script) { + const script = t.script + items.push({ + displayName: `${data.deleteVerb ?? 'Delete'} script ${lastSegment(script.path)}`, + icon: Trash2, + type: 'delete' as const, + action: () => run({ script }) + }) + } + if (t.trigger) { + const trigger = t.trigger + items.push({ + displayName: `Delete ${trigger.kind} trigger ${lastSegment(trigger.path)}`, + icon: Trash2, + type: 'delete' as const, + action: () => run({ trigger }) + }) + } + if (t.script && t.trigger) { + items.push({ + displayName: `${data.deleteVerb === 'Archive' ? 'Remove' : 'Delete'} all 2 items`, + icon: Trash2, + type: 'delete' as const, + action: () => run(t) + }) + } + return items + } + let upstream = $derived(data.upstream) + let HEADER_SELECTED = $derived( + data.scriptError + ? 'bg-red-200 dark:bg-red-600 hover:bg-red-200 dark:hover:bg-red-600' + : 'bg-surface-accent-selected hover:bg-surface-accent-selected text-accent' + ) + const CHIP_SELECTED = + 'bg-surface-accent-selected border-border-selected hover:bg-surface-accent-selected text-accent' + let producer = $derived(upstream && 'path' in upstream ? upstream : undefined) + let coProducers = $derived(upstream && 'scripts' in upstream ? upstream.scripts : []) + let hasHeader = $derived(!!producer || coProducers.length > 0) + // The corner controls sit on the card's corner, below the header tab: + // -top-2 plus PIPELINE_NODE_HEADER (22px). + const CARD_CORNER_TOP = 'top-[14px]' + let coSelected = $derived(!!(upstream && 'scripts' in upstream && upstream.selected)) + let coProducerItems = $derived( + upstreamScriptItems(coProducers, (path) => coProducers.find((s) => s.path === path)?.onOpen()) + ) + let scriptMenuOpen = $state(false) + let coTriggers = $derived(upstream && 'triggers' in upstream ? upstream.triggers : []) + let coTriggerItems: Item[] = $derived( + coTriggers.map((t) => ({ + displayName: `${t.label}${t.draft ? ' · draft' : ''}`, + description: coProducers.length > 1 ? t.script : undefined, + disabled: !t.onOpen, + action: () => t.onOpen?.() + })) + ) + let triggerMenuOpen = $state(false) // dbt badge. `materialized` is dbt's own word rather than the Windmill // strategy because `view` and `ephemeral` have no strategy, and showing the @@ -220,6 +393,185 @@ ) </script> +{#snippet scriptHeader()} + <!-- The script building this asset, folded into it: a strip across the top + naming it, which opens it. Several scripts open a menu to pick one. --> + {@const one = producer ?? (coProducers.length === 1 ? coProducers[0] : undefined)} + {@const headerClass = twMerge( + 'flex items-center gap-1.5 w-full min-w-0 px-2 text-3xs font-normal leading-none text-secondary hover:bg-surface-hover hover:text-primary', + data.scriptError && + 'bg-red-100 dark:bg-red-700 text-red-700 dark:text-red-200 hover:bg-red-200 dark:hover:bg-red-600 hover:text-red-800' + )} + {#if one} + {@const isSelected = producer ? !!producer.selected : coSelected} + <button + type="button" + class={twMerge(headerClass, isSelected && HEADER_SELECTED)} + title={`Open ${one.summary ? `${one.summary} (${one.path})` : one.path}${one.unsaved ? ' · draft' : ''}`} + onpointerdown={(e) => e.stopPropagation()} + onkeydown={(e) => e.stopPropagation()} + onclick={(e) => { + e.stopPropagation() + one.onOpen() + }} + > + {#if one.language} + <LanguageIcon lang={one.language} width={11} height={11} /> + {:else} + <Code2 size={11} class="shrink-0" /> + {/if} + <span class="truncate">{one.summary || one.path}</span> + {#if one.unsaved}<span class="shrink-0 text-tertiary">draft</span>{/if} + {#if producer?.runState} + <RunStateChip runState={producer.runState} class="ml-auto h-4 px-1 rounded" /> + {/if} + <Pencil size={10} class={twMerge('shrink-0 opacity-70', !producer?.runState && 'ml-auto')} /> + </button> + {:else if coProducers.length > 1} + <!-- svelte-ignore a11y_no_static_element_interactions --> + <div + class="w-full min-w-0 flex" + onpointerdown={(e) => e.stopPropagation()} + onkeydown={(e) => e.stopPropagation()} + > + <DropdownV2 + items={coProducerItems} + placement="bottom-start" + bind:open={scriptMenuOpen} + fixedHeight={false} + usePointerDownOutside + enableFlyTransition + class="w-full" + > + {#snippet buttonReplacement()} + <span + class={twMerge(headerClass, 'h-full', (coSelected || scriptMenuOpen) && HEADER_SELECTED)} + title={`Built by ${coProducers.length} scripts: pick one to open`} + > + {#each coProducers.slice(0, 2) as sc (sc.path)} + {#if sc.language} + <LanguageIcon lang={sc.language} width={11} height={11} /> + {:else} + <Code2 size={11} class="shrink-0" /> + {/if} + {/each} + <span class="truncate">{coProducers.length} scripts</span> + <ChevronDown size={11} class="shrink-0 ml-auto" /> + </span> + {/snippet} + </DropdownV2> + </div> + {/if} +{/snippet} + +{#snippet upstreamRow()} + {#if data.foldedFixes?.length} + <!-- A folded script or trigger is misconfigured: its Fix, one at a time. --> + <NodeFixButton + chip + fix={data.foldedFixes[0]} + label={`${data.foldedFixes.length} error${data.foldedFixes.length === 1 ? '' : 's'} · Fix`} + /> + {:else if upstream && coTriggers.length > 1 && !coTriggers.some((t) => t.onOpen)} + <!-- Several triggers, none editable here (View mode): a plain label. --> + <span + class="truncate rounded-md border px-1.5 py-1 text-3xs leading-none font-normal border-gray-300 dark:border-gray-600 text-secondary" + >Multiple triggers</span + > + {:else if upstream && coTriggers.length > 1} + <!-- Several triggers start what builds this asset: one chip, a menu to pick + the one to edit. --> + <!-- svelte-ignore a11y_no_static_element_interactions --> + <div + class="min-w-0 flex" + onpointerdown={(e) => e.stopPropagation()} + onkeydown={(e) => e.stopPropagation()} + > + <DropdownV2 + items={coTriggerItems} + placement="bottom-start" + bind:open={triggerMenuOpen} + fixedHeight={false} + usePointerDownOutside + enableFlyTransition + > + {#snippet buttonReplacement()} + <span + class={twMerge( + 'flex items-center gap-1 min-w-0 rounded-md border px-1.5 py-1 text-3xs leading-none font-normal border-gray-300 dark:border-gray-600 text-secondary bg-surface hover:bg-surface-hover cursor-pointer', + (triggerMenuOpen || coTriggers.some((t) => t.selected)) && CHIP_SELECTED + )} + title="Started by several triggers: pick one to edit" + > + <span class="truncate">Multiple triggers</span> + <ChevronDown size={9} class="shrink-0 opacity-70" /> + </span> + {/snippet} + </DropdownV2> + </div> + {:else if upstream} + {@const trigger = producer?.trigger ?? coTriggers[0]} + {@const triggerScript = producer?.path ?? coTriggers[0]?.script} + {@const chipClass = twMerge( + 'truncate rounded-md border px-1.5 py-1 text-3xs leading-none font-normal', + trigger?.missing + ? 'border-red-300 dark:border-red-600 text-red-700 dark:text-red-300' + : 'border-gray-300 dark:border-gray-600 text-secondary', + trigger?.draft && 'border-dashed', + trigger?.onOpen && 'bg-surface hover:bg-surface-hover cursor-pointer', + trigger?.selected && CHIP_SELECTED + )} + {#if trigger?.kind === 'data_upload' && trigger.onOpen} + <!-- The one trigger that needs the user: nothing runs until a file is + provided, so it reads as the node's main action rather than a chip. --> + <!-- svelte-ignore a11y_no_static_element_interactions --> + <span + class="flex min-w-0" + onpointerdown={(e) => e.stopPropagation()} + onkeydown={(e) => e.stopPropagation()} + > + <Button + variant="accent" + unifiedSize="sm" + startIcon={{ icon: Upload }} + title={`Upload the data ${triggerScript} runs on`} + onClick={(e) => { + e?.stopPropagation() + trigger.onOpen?.() + }} + > + Upload data + </Button> + </span> + {:else if trigger?.onOpen} + <button + type="button" + class={twMerge(chipClass, 'flex items-center gap-1 min-w-0')} + title={trigger.missing + ? `No ${trigger.label} trigger targets ${triggerScript} yet: click to create one` + : `Edit the ${trigger.label} trigger`} + onpointerdown={(e) => e.stopPropagation()} + onkeydown={(e) => e.stopPropagation()} + onclick={(e) => { + e.stopPropagation() + trigger.onOpen?.() + }} + > + <span class="truncate">{trigger.label}{trigger.draft ? ' · draft' : ''}</span> + {#if !trigger.missing}<Pencil size={9} class="shrink-0 opacity-70" />{/if} + </button> + {:else} + <span class={chipClass}> + {#if 'none' in upstream} + External source + {:else if trigger} + {trigger.label}{trigger.draft ? ' · draft' : ''} + {/if} + </span> + {/if} + {/if} +{/snippet} + <!-- onmouseenter/leave on the wrapper (not the inner card) so the run button — which floats outside the card — keeps the hover state alive when the cursor moves between the card and the button. --> @@ -236,123 +588,169 @@ <div class="wm-recompute-flash pointer-events-none absolute inset-0 z-10 rounded-md"></div> {/key} {/if} - <!-- Mirrors the flow editor's asset pill: quiet surface + gray border at - rest, accent reserved for the selected state. --> - <div - class={twMerge( - 'flex items-center rounded-md drop-shadow-sm overflow-hidden border', - 'bg-surface-secondary border-gray-400 dark:border-gray-600 hover:border-gray-500 dark:hover:border-gray-500 transition-colors', - selected && 'bg-surface-accent-selected border-border-selected' + <NodeActionsMenu + items={menuItems} + hover={hovered} + kebabClass={twMerge( + showGuardBadge && '-right-8', + hasHeader && !data.bannerOnly && CARD_CORNER_TOP )} - style="width: {NODE.width}px; min-height: {NODE.height}px;" - title={data.path} > - <!-- Data identity carries the accent (luminance blue), pairing with - the blue write edges that produce these assets — scripts stay - neutral, so script vs data reads at a glance. --> - <AssetGenericIcon - assetKind={data.asset_kind} - class={`shrink-0 ml-2 mr-2 ${selected ? 'text-accent' : 'text-blue-600 dark:text-blue-400'}`} - size="14px" - /> - {#if data.runStatus} - <!-- The run in view, per relation: a spinner while its producer is - building it, then its outcome. Left of the name so the eye finds - the moving nodes first on a wide graph. --> - <span - class="shrink-0 mr-1 {data.runStatus === 'failed' - ? 'text-red-600 dark:text-red-400' - : data.runStatus === 'materialized' - ? 'text-green-600 dark:text-green-400' - : 'text-blue-600 dark:text-blue-400'}" - title={data.runStatus} + {#if data.bannerOnly} + <!-- A script that builds nothing and runs only on writes to what it reads: + the incoming edges say how it starts, so its banner is the whole node. --> + <div + class={twMerge( + 'flex items-stretch min-w-0 rounded-md overflow-hidden bg-surface border border-gray-200 dark:border-gray-700 drop-shadow-sm', + (producer ? producer.selected : coSelected) && + 'border-border-selected dark:border-border-selected' + )} + style="width: {data.width ?? 160}px; height: {PIPELINE_NODE_HEADER}px;" > - {#if data.runStatus === 'running'} - <Loader2 size={11} class="animate-spin" /> - {:else if data.runStatus === 'failed'} - <XCircle size={11} /> + {@render scriptHeader()} + </div> + {:else} + <PipelineNodeCard + kindLabel={data.noAsset ? 'No asset' : formatAssetKind(asset)} + title={data.noAsset ? (data.noAssetName ?? '') : formatShortAssetPath(asset)} + tooltip={data.noAsset + ? 'This script builds no asset' + : data.error + ? `${data.path}: ${data.error}` + : data.path} + {selected} + tone={data.error ? 'error' : undefined} + subtitle={data.foldedFixes?.length || + (upstream && + !producer?.trigger?.hidden && + !('triggers' in upstream && upstream.triggers.length === 0)) + ? upstreamRow + : undefined} + header={hasHeader ? scriptHeader : undefined} + headerTone={data.scriptError ? 'error' : undefined} + headerSelected={producer ? !!producer.selected : coSelected} + width={data.width} + surface={upstream ? 'primary' : 'secondary'} + > + {#snippet icon()} + <!-- Data identity carries the accent (luminance blue), pairing with + the blue write edges that produce these assets — scripts stay + neutral, so script vs data reads at a glance. --> + {#if data.noAsset} + <CircleSlash size={14} class="text-tertiary" /> {:else} - <CheckCircle2 size={11} /> + <AssetGenericIcon + assetKind={data.asset_kind} + class={data.error + ? 'text-red-600 dark:text-red-200' + : selected + ? 'text-accent' + : 'text-blue-600 dark:text-blue-400'} + size="14px" + /> {/if} - </span> - <!-- Rows the run wrote. Recorded per relation already, and the cheapest - answer to "did this model actually produce anything" — a model that - built green but emitted 0 rows is the failure that looks like a - success. Only once settled: mid-build the number is not yet real. --> - {#if data.runStatus === 'materialized' && data.runRowCount != undefined} - <span - class="shrink-0 mr-1 text-3xs tabular-nums text-tertiary" - title="{data.runRowCount} rows written by this run" - > - {Intl.NumberFormat().format(data.runRowCount)} - </span> - {/if} - {/if} - <span class="flex-1 min-w-0 pr-1 py-0.5 text-2xs font-mono text-emphasis truncate"> - {formatShortAssetPath(asset)} - </span> - <!-- Fork data-environment chip: in a fork every asset shares its parent's - name, so the env it resolves to must read at a glance. Labeled + tinted - (amber "parent" = deferred read of the parent's current table via a - view; emerald "fork" = the fork's own materialized copy) rather than a - bare icon, which was too easy to miss. The title carries the detail. --> - {#if data.fork_materialization === 'deferred'} - <span - class="shrink-0 mr-1.5 flex items-center gap-0.5 rounded px-1 py-px text-3xs font-semibold uppercase tracking-wide bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300 border border-amber-300 dark:border-amber-700" - title="Deferred to parent workspace: reads the parent's current data. Materialize it in this fork to iterate on it." - > - <ArrowUpRight size={10} /> - parent - </span> - {:else if data.fork_materialization === 'fork'} - <span - class="shrink-0 mr-1.5 flex items-center gap-0.5 rounded px-1 py-px text-3xs font-semibold uppercase tracking-wide bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300 border border-emerald-300 dark:border-emerald-700" - title="Materialized in this fork: reads and writes use the fork's isolated copy." - > - <GitFork size={10} /> - fork - </span> - {/if} - <!-- dbt chip: names the materialization dbt declares, plus a test count - when the model carries generic tests. Orange keeps it visually - separate from the fork/SCD2 chips, which describe Windmill state. - Where the project node is on the graph it also stands in for the edge - to it: hovering lights that node up, clicking selects it. Where it is - not — the run page, and a pipeline holding a dbt project — there is - nothing to point at, so the chip renders inert. --> - {#if data.dbt} - <button - type="button" - class="shrink-0 mr-1.5 flex items-center gap-0.5 rounded px-1 py-px text-3xs font-semibold tracking-wide bg-orange-100 dark:bg-orange-900/40 text-orange-700 dark:text-orange-300 border border-orange-300 dark:border-orange-700 {data.onDbtSelect - ? 'hover:brightness-95 cursor-pointer' - : 'cursor-default'}" - title={dbtTitle} - onmouseenter={() => data.onDbtHover?.(true)} - onmouseleave={() => data.onDbtHover?.(false)} - onclick={(e) => { - e.stopPropagation() - data.onDbtSelect?.() - }} - > - <DbtIcon width={9} height={9} /> - {dbtLabel} - {#if data.dbt.data_tests?.length} - <span class="opacity-70">· {data.dbt.data_tests.length}T</span> + {/snippet} + {#snippet leading()} + {#if data.runStatus} + <!-- The run in view, per relation: a spinner while its producer is + building it, then its outcome. Left of the name so the eye finds + the moving nodes first on a wide graph. --> + <span + class="shrink-0 mr-1 {data.runStatus === 'failed' + ? 'text-red-600 dark:text-red-400' + : data.runStatus === 'materialized' + ? 'text-green-600 dark:text-green-400' + : 'text-blue-600 dark:text-blue-400'}" + title={data.runStatus} + > + {#if data.runStatus === 'running'} + <Loader2 size={11} class="animate-spin" /> + {:else if data.runStatus === 'failed'} + <XCircle size={11} /> + {:else} + <CheckCircle2 size={11} /> + {/if} + </span> + <!-- Rows the run wrote. Recorded per relation already, and the cheapest + answer to "did this model actually produce anything" — a model that + built green but emitted 0 rows is the failure that looks like a + success. Only once settled: mid-build the number is not yet real. --> + {#if data.runStatus === 'materialized' && data.runRowCount != undefined} + <span + class="shrink-0 mr-1 text-3xs tabular-nums text-tertiary" + title="{data.runRowCount} rows written by this run" + > + {Intl.NumberFormat().format(data.runRowCount)} + </span> + {/if} {/if} - </button> + {/snippet} + {#snippet trailing()} + <!-- Fork data-environment chip: in a fork every asset shares its parent's + name, so the env it resolves to must read at a glance. Labeled + tinted + (amber "parent" = deferred read of the parent's current table via a + view; emerald "fork" = the fork's own materialized copy) rather than a + bare icon, which was too easy to miss. The title carries the detail. --> + {#if data.fork_materialization === 'deferred'} + <span + class="shrink-0 mr-1.5 flex items-center gap-0.5 rounded px-1 py-px text-3xs font-semibold uppercase tracking-wide bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300 border border-amber-300 dark:border-amber-700" + title="Deferred to parent workspace: reads the parent's current data. Materialize it in this fork to iterate on it." + > + <ArrowUpRight size={10} /> + parent + </span> + {:else if data.fork_materialization === 'fork'} + <span + class="shrink-0 mr-1.5 flex items-center gap-0.5 rounded px-1 py-px text-3xs font-semibold uppercase tracking-wide bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300 border border-emerald-300 dark:border-emerald-700" + title="Materialized in this fork: reads and writes use the fork's isolated copy." + > + <GitFork size={10} /> + fork + </span> + {/if} + <!-- dbt chip: names the materialization dbt declares, plus a test count + when the model carries generic tests. Orange keeps it visually + separate from the fork/SCD2 chips, which describe Windmill state. + Where the project node is on the graph it also stands in for the edge + to it: hovering lights that node up, clicking selects it. Where it is + not — the run page, and a pipeline holding a dbt project — there is + nothing to point at, so the chip renders inert. --> + {#if data.dbt} + <button + type="button" + class="shrink-0 mr-1.5 flex items-center gap-0.5 rounded px-1 py-px text-3xs font-semibold tracking-wide bg-orange-100 dark:bg-orange-900/40 text-orange-700 dark:text-orange-300 border border-orange-300 dark:border-orange-700 {data.onDbtSelect + ? 'hover:brightness-95 cursor-pointer' + : 'cursor-default'}" + title={dbtTitle} + onmouseenter={() => data.onDbtHover?.(true)} + onmouseleave={() => data.onDbtHover?.(false)} + onclick={(e) => { + e.stopPropagation() + data.onDbtSelect?.() + }} + > + <DbtIcon width={9} height={9} /> + {dbtLabel} + {#if data.dbt.data_tests?.length} + <span class="opacity-70">· {data.dbt.data_tests.length}T</span> + {/if} + </button> + {/if} + <!-- SCD2 companion marker: this node is the `<dim>_current` "latest row + per key" view its producer maintains alongside the base dimension. + Icon-only (the pill already truncates); the title names the base. --> + {#if data.derived_from} + <span + class="shrink-0 mr-1.5 text-violet-600 dark:text-violet-400" + title={`SCD2 current view of ${data.derived_from}: latest row per key, maintained by the same producer as the base dimension.`} + > + <History size={12} /> + </span> + {/if} + {/snippet} + </PipelineNodeCard> {/if} - <!-- SCD2 companion marker: this node is the `<dim>_current` "latest row - per key" view its producer maintains alongside the base dimension. - Icon-only (the pill already truncates); the title names the base. --> - {#if data.derived_from} - <span - class="shrink-0 mr-1.5 text-violet-600 dark:text-violet-400" - title={`SCD2 current view of ${data.derived_from}: latest row per key, maintained by the same producer as the base dimension.`} - > - <History size={12} /> - </span> - {/if} - </div> + </NodeActionsMenu> {#if showGuardBadge} <!-- Data-test outcome badge. Floats off the TOP-RIGHT corner (opposite the left-edge run button and the bottom + inserter) so it never collides @@ -361,6 +759,7 @@ <div class={twMerge( 'absolute -top-2 -right-2 z-10 rounded-full w-5 h-5 grid place-items-center border shadow-sm', + hasHeader && CARD_CORNER_TOP, guardClass )} title={guardTitle} @@ -376,7 +775,13 @@ cards. Drafts are runnable too via runScriptPreview, so no greyed-out state — the page-supplied callback handles the dispatch. --> - <div class="absolute -left-3 top-1/2 -translate-y-1/2 z-10"> + <!-- Centred on the card, below the header tab when there is one. --> + <div + class={twMerge( + 'absolute -left-3 top-1/2 -translate-y-1/2 z-10', + hasHeader && !data.bannerOnly && 'top-[calc(50%+11px)]' + )} + > <button type="button" onclick={runProducers} @@ -398,53 +803,47 @@ </button> </div> {/if} - {#if showAdd} - <!-- Always-visible + below the asset for downstream pipeline-script - creation. Half-overlapping the bottom edge so it visually attaches - to the node like the flow editor's between-step inserter. --> + {#if data.onStartOnDrag} + <NodeOnDot onStart={data.onStartOnDrag} visible={hovered} /> + {/if} + {#if data.fix} + <!-- A red node's way out replaces its "+": adding downstream of a broken + node is not what it needs. --> <div class="absolute left-1/2 -bottom-3 -translate-x-1/2 z-10"> - <PipelineInsertMenu - kinds={[ - { - id: 'pipeline_script', - label: 'Add downstream pipeline script', - description: 'Triggered when this asset changes', - icon: Code2 - } - ]} - languages={PIPELINE_LANGUAGES as any} - pathPrefix={data.pathPrefix ?? ''} - defaultPathSuffix={data.defaultPathSuffix ?? ''} - onPick={handlePick} + <NodeFixButton fix={data.fix} /> + </div> + {:else if showAdd} + <!-- Always-visible + on the asset's bottom edge for downstream pipeline- + script creation, half-overlapping it like the flow editor's + between-step inserter. --> + <div class="absolute left-1/2 -bottom-3 -translate-x-1/2 z-10"> + <AddDownstreamMenu + asset={{ kind: data.asset_kind, path: data.path }} + onAddScript={data.onAddScript!} + pathPrefix={data.pathPrefix} + defaultPathSuffix={data.defaultPathSuffix} > - {#snippet trigger()} - <!-- - Sizing notes for the round + button: - - w-6/h-6 (24px) chosen so that with border-2 (2px each - side) the inner area is exactly 20px — divisible by - the 16px icon to leave a 2px gap on every side. At - 20px / 12px before, the gap was 4px-each but the - odd rounding interacted badly with svelte-flow's - fractional zoom transforms and the icon drifted - half a pixel off-center on certain zoom levels. - - `grid place-items-center` instead of flex centering: - flex's baseline alignment introduces a sub-pixel - nudge on small elements that grid avoids. - - `leading-none` strips the default line-height - contribution that the SVG inherits via the parent's - text rendering, otherwise the icon is shifted - downward by ~0.5px at fractional zooms. - --> + {#snippet trigger({ open })} + <!-- A click opens the menu; a drag goes to the canvas, which + tells a real drag from a click by how far the pointer moves. --> <button type="button" + class="nopan nodrag block" onclick={(e) => e.stopPropagation()} - class="bg-surface border border-gray-400 dark:border-gray-600 text-secondary hover:bg-surface-hover rounded-full w-6 h-6 grid place-items-center shadow-sm leading-none" - title="Add downstream pipeline script" + onpointerdown={(e) => { + if (e.button !== 0) return + e.preventDefault() + data.onStartFeedDrag?.(e) + }} + aria-label="Add downstream step" + title={data.onStartFeedDrag + ? 'Click to add a downstream step, or drag onto a script to run it after each write' + : undefined} > - <Plus size={16} strokeWidth={2.5} /> + <AddDownstreamPill expanded={open} /> </button> {/snippet} - </PipelineInsertMenu> + </AddDownstreamMenu> </div> {/if} </div> diff --git a/frontend/src/lib/components/assets/AssetGraph/AssetRunsPanel.svelte b/frontend/src/lib/components/assets/AssetGraph/AssetRunsPanel.svelte index 7cee1deb76..7d55da04a1 100644 --- a/frontend/src/lib/components/assets/AssetGraph/AssetRunsPanel.svelte +++ b/frontend/src/lib/components/assets/AssetGraph/AssetRunsPanel.svelte @@ -15,7 +15,6 @@ import LogViewer from '$lib/components/LogViewer.svelte' import DisplayResult from '$lib/components/DisplayResult.svelte' import JobArgs from '$lib/components/JobArgs.svelte' - import { base } from '$lib/base' import { Badge } from '$lib/components/common' import { Popover } from '$lib/components/meltComponents' import { twMerge } from 'tailwind-merge' @@ -288,7 +287,7 @@ </span> <a class="text-3xs text-blue-600 hover:underline shrink-0" - href={`${base}/run/${selectedJob.id}?workspace=${$operatingWorkspace}`} + href={`/run/${selectedJob.id}?workspace=${$operatingWorkspace}`} target="_blank">Open ↗</a > {#if $operatingWorkspace} diff --git a/frontend/src/lib/components/assets/AssetGraph/DataTablePreview.svelte b/frontend/src/lib/components/assets/AssetGraph/DataTablePreview.svelte index 5f5dc98b60..5391c7caff 100644 --- a/frontend/src/lib/components/assets/AssetGraph/DataTablePreview.svelte +++ b/frontend/src/lib/components/assets/AssetGraph/DataTablePreview.svelte @@ -16,7 +16,6 @@ import { parseDbInputFromAssetSyntax } from '$lib/utils' import { AlertTriangle, Database, Loader2, Settings } from 'lucide-svelte' import Button from '$lib/components/common/button/Button.svelte' - import { base } from '$lib/base' import { twMerge } from 'tailwind-merge' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' @@ -180,7 +179,7 @@ </span> </div> <Button - href="{base}/workspace_settings?tab=windmill_data_tables" + href="/workspace_settings?tab=windmill_data_tables" variant="accent" unifiedSize="sm" startIcon={{ icon: Settings }} diff --git a/frontend/src/lib/components/assets/AssetGraph/DucklakeAssetPanel.svelte b/frontend/src/lib/components/assets/AssetGraph/DucklakeAssetPanel.svelte index 5f7ad050e4..65bd86258d 100644 --- a/frontend/src/lib/components/assets/AssetGraph/DucklakeAssetPanel.svelte +++ b/frontend/src/lib/components/assets/AssetGraph/DucklakeAssetPanel.svelte @@ -11,7 +11,8 @@ // can't be read), so a selectable version always exists in the table. import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte' import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte' - import { Table2, History, Columns3 } from 'lucide-svelte' + import { Table2, History, Columns3, Database } from 'lucide-svelte' + import DBManagerContent from '$lib/components/DBManagerContent.svelte' import { Pane, Splitpanes } from 'svelte-splitpanes' import { resource } from 'runed' import { fetchDucklakeSnapshots } from '$lib/components/dbOps' @@ -31,7 +32,7 @@ } let { path, workspace, schemaCanEvolve = true }: Props = $props() - let tab = $state<'partitions' | 'history' | 'schema'>('partitions') + let tab = $state<'data' | 'partitions' | 'history' | 'schema'>('data') // The user's explicit snapshot pick (undefined until they click a row). let selectedVersion = $state<number | undefined>(undefined) @@ -72,24 +73,28 @@ </script> <div class="flex flex-col h-full"> - {#if !qualifiedTable} - <!-- Catalog-level ducklake node (no table segment, e.g. `ducklake://main`): - snapshot history / time-travel are per-table, so only the partition - grid applies here. --> - <PartitionStatusGrid {path} {workspace} /> - {:else} - <div class="flex items-center gap-2 px-3 py-2 border-b shrink-0"> - <ToggleButtonGroup selected={tab} on:selected={(e) => (tab = e.detail)}> - {#snippet children({ item })} - <ToggleButton size="sm" value="partitions" label="Partitions" icon={Table2} {item} /> + <div class="flex items-center gap-2 px-3 py-2 border-b shrink-0"> + <ToggleButtonGroup selected={tab} on:selected={(e) => (tab = e.detail)}> + {#snippet children({ item })} + <ToggleButton size="sm" value="data" label="Data" icon={Database} {item} /> + <ToggleButton size="sm" value="partitions" label="Partitions" icon={Table2} {item} /> + <!-- Snapshot history and time-travel are per table: a catalog-level node + (`ducklake://main`, no table segment) has only its data and partitions. --> + {#if qualifiedTable} <ToggleButton size="sm" value="schema" label="Schema" icon={Columns3} {item} /> <ToggleButton size="sm" value="history" label="History" icon={History} {item} /> - {/snippet} - </ToggleButtonGroup> - </div> + {/if} + {/snippet} + </ToggleButtonGroup> + </div> - <div class="flex-1 min-h-0"> - {#if tab === 'partitions'} + <div class="flex-1 min-h-0"> + {#if tab === 'data' && parsed} + <!-- Keyed on the asset: the manager opens its table once, on mount. --> + {#key path} + <DBManagerContent input={parsed} {workspace} /> + {/key} + {:else if tab === 'partitions' || !qualifiedTable} <PartitionStatusGrid {path} {workspace} /> {:else if tab === 'schema'} <SchemaHistoryPanel {path} {workspace} canEvolve={schemaCanEvolve} /> @@ -117,7 +122,6 @@ </Pane> </Splitpanes> </div> - {/if} - </div> - {/if} + {/if} + </div> </div> diff --git a/frontend/src/lib/components/assets/AssetGraph/InitialFitView.svelte b/frontend/src/lib/components/assets/AssetGraph/InitialFitView.svelte index eea1fb306d..2f8c0cdfe7 100644 --- a/frontend/src/lib/components/assets/AssetGraph/InitialFitView.svelte +++ b/frontend/src/lib/components/assets/AssetGraph/InitialFitView.svelte @@ -25,6 +25,8 @@ if (!nodesInitialized.current) return if (!nodes.some((n) => n.type !== 'add')) return fittedFor = fitKey - void fitView({ padding: 0.1, maxZoom: 1 }) + // A re-fit over nodes that keep their ids finds them already measured, one + // render before their new positions reach the flow. + requestAnimationFrame(() => void fitView({ padding: 0.1, maxZoom: 1 })) }) </script> diff --git a/frontend/src/lib/components/assets/AssetGraph/NodeActionsMenu.svelte b/frontend/src/lib/components/assets/AssetGraph/NodeActionsMenu.svelte new file mode 100644 index 0000000000..dcb32aa00e --- /dev/null +++ b/frontend/src/lib/components/assets/AssetGraph/NodeActionsMenu.svelte @@ -0,0 +1,68 @@ +<!-- +@component +A pipeline node's actions, reachable two ways: the kebab revealed on hover at the +node's top-right corner, and a right-click menu over the node carrying the same +items. Place it inside the node's `relative` wrapper, around the node's card. +--> +<script lang="ts"> + import type { Snippet } from 'svelte' + import { twMerge } from 'tailwind-merge' + import { EllipsisVertical } from 'lucide-svelte' + import { stopPropagation, preventDefault } from 'svelte/legacy' + import DropdownV2 from '$lib/components/DropdownV2.svelte' + import ContextMenu from '$lib/components/common/contextmenu/ContextMenu.svelte' + import { contextMenuItemsFromMenu } from '$lib/components/common/contextmenu/fromMenuItems' + import type { Item } from '$lib/utils' + + interface Props { + items: Item[] + /** The pointer is over the node: shows the kebab. */ + hover: boolean + /** Moves the kebab, for a node with its own badge on that corner. */ + kebabClass?: string + children: Snippet + } + + let { items, hover, kebabClass, children }: Props = $props() + + let menuOpen = $state(false) + let contextItems = $derived(contextMenuItemsFromMenu(items)) +</script> + +{#if items.length > 0} + <ContextMenu items={contextItems}> + {@render children()} + </ContextMenu> + <!-- Rendered only on hover or while open, so the canvas stays clean at rest. + `pointerdown` is stopped so svelte-flow doesn't select the node when the + user reaches for the menu. --> + <div + class={twMerge('absolute -top-2 -right-2 h-7 p-1 min-w-7', kebabClass)} + style="will-change: transform;" + > + <DropdownV2 + {items} + placement="bottom-end" + bind:open={menuOpen} + fixedHeight={false} + usePointerDownOutside + enableFlyTransition + > + {#snippet buttonReplacement()} + <button + class={twMerge( + 'center-center p-1 text-secondary shadow-sm bg-surface duration-0 hover:bg-surface-tertiary', + hover || menuOpen ? 'block' : '!hidden', + 'shadow-md rounded-md' + )} + onpointerdown={stopPropagation(preventDefault(() => {}))} + title="Actions" + > + <EllipsisVertical size={12} /> + </button> + {/snippet} + </DropdownV2> + </div> +{:else} + {@render children()} +{/if} diff --git a/frontend/src/lib/components/assets/AssetGraph/NodeFixButton.svelte b/frontend/src/lib/components/assets/AssetGraph/NodeFixButton.svelte new file mode 100644 index 0000000000..6e3ba8b8ee --- /dev/null +++ b/frontend/src/lib/components/assets/AssetGraph/NodeFixButton.svelte @@ -0,0 +1,124 @@ +<!-- +@component +The "Fix" pill on the bottom edge of a misconfigured (red) pipeline node: what is +wrong, and the actions that fix it. Styled like the node's "+" pill; the node's +red fill already says something is wrong. +--> +<script lang="ts" module> + export type NodeFixAction = { + label: string + /** The side effect, spelled out: what changes, where. */ + detail?: string + /** `anchor`: where the Fix pill sits, for an action opening a menu there. */ + run: (anchor: { x: number; y: number }) => void + } + /** Prose, with the entities it names as links that select them. */ + export type FixExplainer = Array<string | { text: string; onClick: () => void }> + export type NodeFix = { explainer: FixExplainer; actions: NodeFixAction[] } + + /** A fix as its supplier declares it: an action, or opening the schedule + * wizard (which the canvas owns). */ + export type NodeFixSpec = { + explainer: FixExplainer + actions: Array<{ + label: string + detail?: string + run?: () => void + /** Opens the schedule wizard for this script; its confirm calls `onSchedule`. */ + scheduleFor?: { + script: string + onSchedule: (s: import('./PipelineInsertMenu.svelte').PipelineInsertSchedule) => void + } + }> + } +</script> + +<script lang="ts"> + import Popover from '$lib/components/meltComponents/Popover.svelte' + import { Button } from '$lib/components/common' + import { Wrench } from 'lucide-svelte' + + let { + fix, + label = 'Fix', + chip = false + }: { + fix: NodeFix + label?: string + /** A small chip in a node's text, rather than the pill on its edge. */ + chip?: boolean + } = $props() + + let open = $state(false) + let anchorEl: HTMLElement | undefined = $state() +</script> + +<!-- svelte-ignore a11y_no_static_element_interactions --> +<div + bind:this={anchorEl} + onpointerdown={(e) => e.stopPropagation()} + onkeydown={(e) => e.stopPropagation()} + onclick={(e) => e.stopPropagation()} +> + <Popover + bind:isOpen={open} + placement="bottom" + enableFlyTransition + usePointerDownOutside + contentClasses="p-3 w-96" + > + {#snippet trigger()} + {#if chip} + <span + class="flex items-center gap-1 rounded-md border px-1.5 py-1 text-3xs leading-none font-normal whitespace-nowrap bg-surface border-red-300 dark:border-red-600 text-red-700 dark:text-red-300 hover:bg-surface-hover" + > + <Wrench size={10} class="shrink-0" /> + {label} + </span> + {:else} + <span + class="h-6 px-2 rounded-full flex items-center gap-1 bg-surface border border-gray-400 dark:border-gray-600 text-secondary hover:text-primary hover:border-gray-500 shadow-sm text-2xs font-normal leading-none whitespace-nowrap" + > + <Wrench size={12} class="shrink-0" /> + {label} + </span> + {/if} + {/snippet} + {#snippet content()} + <div class="flex flex-col gap-3"> + <p class="text-xs text-primary"> + {#each fix.explainer as part} + {#if typeof part === 'string'}{part}{:else}<button + type="button" + class="text-accent hover:underline" + onclick={() => { + open = false + part.onClick() + }}>{part.text}</button + >{/if} + {/each} + </p> + <div class="flex flex-col gap-2"> + {#each fix.actions as action, i (action.label)} + <div class="flex flex-col gap-0.5"> + <Button + variant={i === 0 ? 'accent' : 'default'} + unifiedSize="sm" + onclick={() => { + const r = anchorEl?.getBoundingClientRect() + open = false + action.run({ x: r ? r.left + r.width / 2 : 0, y: r ? r.bottom : 0 }) + }} + > + {action.label} + </Button> + {#if action.detail} + <span class="text-2xs text-secondary">{action.detail}</span> + {/if} + </div> + {/each} + </div> + </div> + {/snippet} + </Popover> +</div> diff --git a/frontend/src/lib/components/assets/AssetGraph/NodeOnDot.svelte b/frontend/src/lib/components/assets/AssetGraph/NodeOnDot.svelte new file mode 100644 index 0000000000..25d84b9197 --- /dev/null +++ b/frontend/src/lib/components/assets/AssetGraph/NodeOnDot.svelte @@ -0,0 +1,23 @@ +<!-- +@component +The dot on a pipeline node's top edge: dragged onto an asset, it makes the node's +script run after each write to that asset. +--> +<script lang="ts"> + let { onStart, visible }: { onStart: (e: PointerEvent) => void; visible: boolean } = $props() +</script> + +<button + type="button" + class="absolute -top-1.5 left-1/2 -translate-x-1/2 z-10 w-3 h-3 rounded-full bg-surface border-2 border-blue-500 cursor-crosshair transition-opacity {visible + ? 'opacity-100' + : 'opacity-0'}" + title="Drag onto an asset to run after each write to it" + aria-label="Drag onto an asset to run after each write to it" + onpointerdown={(e) => { + e.stopPropagation() + e.preventDefault() + onStart(e) + }} + onclick={(e) => e.stopPropagation()} +></button> diff --git a/frontend/src/lib/components/assets/AssetGraph/PanToNode.svelte b/frontend/src/lib/components/assets/AssetGraph/PanToNode.svelte index 83df60b340..22acd606cb 100644 --- a/frontend/src/lib/components/assets/AssetGraph/PanToNode.svelte +++ b/frontend/src/lib/components/assets/AssetGraph/PanToNode.svelte @@ -2,6 +2,7 @@ import { useSvelteFlow, type Node } from '@xyflow/svelte' import { untrack } from 'svelte' import { NODE } from '$lib/components/graph/util' + import { PIPELINE_NODE_HEIGHT } from './assetGraphLayout' // Smoothly pans the viewport so a freshly-created node lands in the middle, // keeping the current zoom. Lives inside <SvelteFlow> so useSvelteFlow() has @@ -27,8 +28,8 @@ untrack(() => { const node = ns.find((n) => n.id === id) if (!node) return // not laid out yet — re-runs when `nodes` updates - const cx = node.position.x + NODE.width / 2 - const cy = node.position.y + NODE.height / 2 + const cx = node.position.x + (node.measured?.width ?? NODE.width) / 2 + const cy = node.position.y + PIPELINE_NODE_HEIGHT / 2 const key = `${id}:${cx}:${cy}` if (key === lastKey) return lastKey = key diff --git a/frontend/src/lib/components/assets/AssetGraph/PipelineActivityPanel.svelte b/frontend/src/lib/components/assets/AssetGraph/PipelineActivityPanel.svelte index 7e6c34adc2..27a3253d0e 100644 --- a/frontend/src/lib/components/assets/AssetGraph/PipelineActivityPanel.svelte +++ b/frontend/src/lib/components/assets/AssetGraph/PipelineActivityPanel.svelte @@ -1,5 +1,4 @@ <script lang="ts"> - import { base } from '$lib/base' import { workspaceStore } from '$lib/stores' import type { Job } from '$lib/gen' import Select from '$lib/components/select/Select.svelte' @@ -416,7 +415,7 @@ onmouseenter={() => onHoverRun?.([e.path])} onmouseleave={() => onHoverRun?.(undefined)} class={twMerge( - 'w-full flex items-center gap-2 px-2 py-1 rounded-sm hover:bg-surface-hover text-xs text-left', + 'w-full flex items-center gap-2 px-2 py-1.5 rounded-sm font-normal hover:bg-surface-hover text-xs text-left', isMember && 'pl-7', expanded && 'bg-surface-selected' )} @@ -445,7 +444,7 @@ {:else} <Code2 size={12} class="shrink-0 text-tertiary" /> {/if} - <span class="flex-1 min-w-0 truncate font-mono text-2xs" title={e.path}> + <span class="flex-1 min-w-0 truncate text-xs" title={e.path}> {e.path} </span> {#if showSource} @@ -477,7 +476,7 @@ <span class="font-mono truncate flex-1 min-w-0">{expandedJob.id}</span> <a class="text-blue-600 hover:underline shrink-0" - href={`${base}/run/${expandedJob.id}?workspace=${$workspaceStore}`} + href={`/run/${expandedJob.id}?workspace=${$workspaceStore}`} target="_blank">Open ↗</a > </div> @@ -533,7 +532,7 @@ onclick={() => toggleGroup(g.key)} onmouseenter={() => onHoverRun?.(g.members.map((m) => m.path))} onmouseleave={() => onHoverRun?.(undefined)} - class="w-full flex items-center gap-2 px-2 py-1 rounded-sm hover:bg-surface-hover text-xs text-left" + class="w-full flex items-center gap-2 px-2 py-1.5 rounded-sm font-normal hover:bg-surface-hover text-xs text-left" title={collapsed ? 'Expand cascade runs' : 'Collapse cascade runs'} > <span class="shrink-0 text-tertiary"> @@ -549,7 +548,7 @@ {/if} </span> <Workflow size={12} class="shrink-0 text-indigo-500" /> - <span class="flex-1 min-w-0 truncate font-mono text-2xs" title={groupTitle(g)}> + <span class="flex-1 min-w-0 truncate text-xs" title={groupTitle(g)}> {groupTitle(g)} </span> <span diff --git a/frontend/src/lib/components/assets/AssetGraph/PipelineDbtSignpost.svelte b/frontend/src/lib/components/assets/AssetGraph/PipelineDbtSignpost.svelte deleted file mode 100644 index 495e9a34bd..0000000000 --- a/frontend/src/lib/components/assets/AssetGraph/PipelineDbtSignpost.svelte +++ /dev/null @@ -1,40 +0,0 @@ -<script lang="ts"> - import { base } from '$lib/base' - import Alert from '$lib/components/common/alert/Alert.svelte' - import Button from '$lib/components/common/button/Button.svelte' - import DbtIcon from '$lib/components/icons/DbtIcon.svelte' - import { BookOpen } from 'lucide-svelte' - - const DBT_DOCS = 'https://www.windmill.dev/docs/getting_started/scripts_quickstart/dbt' -</script> - -<Alert type="info" title="Prefer using dbt? Windmill also runs dbt" size="xs"> - <div class="flex flex-col gap-2"> - <p> - A pipeline is Windmill's own abstraction; an existing dbt project stays a dbt project, and - runs here unchanged as its own kind of script, with dbt still owning its models, refs and - tests. All it needs is a warehouse configured under - <a class="underline" href="{base}/workspace_settings?tab=dbt">Settings → dbt</a>. Its models - show up in the asset graph as <span class="font-mono">dbt://</span> nodes, visible next to whatever - pipelines you do build, so you can adopt pipelines later, or never. - </p> - <div class="flex flex-row flex-wrap items-center gap-2"> - <!-- The dbt mark goes in as a child rather than `startIcon`: that slot - sizes its icon with lucide's `size`, which DbtIcon has no prop for. --> - <Button variant="default" unifiedSize="sm" href="{base}/scripts/add?lang=dbt"> - <DbtIcon width={14} height={14} /> - New dbt script - </Button> - <Button - variant="subtle" - unifiedSize="sm" - href={DBT_DOCS} - target="_blank" - rel="noreferrer" - startIcon={{ icon: BookOpen }} - > - dbt documentation - </Button> - </div> - </div> -</Alert> diff --git a/frontend/src/lib/components/assets/AssetGraph/PipelineDeployErrors.svelte b/frontend/src/lib/components/assets/AssetGraph/PipelineDeployErrors.svelte new file mode 100644 index 0000000000..6206ebdf33 --- /dev/null +++ b/frontend/src/lib/components/assets/AssetGraph/PipelineDeployErrors.svelte @@ -0,0 +1,49 @@ +<script lang="ts"> + import { AlertTriangle } from 'lucide-svelte' + import Popover from '$lib/components/meltComponents/Popover.svelte' + + // Which drafts failed to deploy and why, anchored next to the deploy button so + // the reasons are one click away without leaving the editor. Deployed drafts + // leave the map; what is listed is still unresolved. + let { + errors, + open = $bindable() + }: { + errors: ReadonlyMap<string, string> + open?: boolean + } = $props() +</script> + +<Popover + placement="bottom-end" + contentClasses="p-3 max-w-[480px]" + usePointerDownOutside + enableFlyTransition + bind:isOpen={open} +> + {#snippet trigger()} + <button + type="button" + class="flex items-center gap-1.5 px-2 py-1 rounded-md text-red-600 dark:text-red-400 bg-red-50 dark:bg-red-900/30 hover:bg-red-100 dark:hover:bg-red-900/50 transition-colors text-xs font-medium" + title="View save errors" + > + <AlertTriangle size={14} /> + <span>{errors.size} failed</span> + </button> + {/snippet} + {#snippet content()} + <div class="flex flex-col gap-2"> + <span class="text-xs font-semibold text-emphasis">Save errors</span> + <div class="flex flex-col gap-2 max-h-72 overflow-y-auto"> + {#each [...errors.entries()] as [path, message] (path)} + <div class="flex flex-col gap-0.5 border-l-2 border-red-400 pl-2"> + <span class="text-2xs font-mono text-emphasis">{path}</span> + <span class="text-2xs text-red-600 dark:text-red-400 break-words"> + {message} + </span> + </div> + {/each} + </div> + </div> + {/snippet} +</Popover> diff --git a/frontend/src/lib/components/assets/AssetGraph/PipelineDeployTriggersModal.svelte b/frontend/src/lib/components/assets/AssetGraph/PipelineDeployTriggersModal.svelte new file mode 100644 index 0000000000..d96b758625 --- /dev/null +++ b/frontend/src/lib/components/assets/AssetGraph/PipelineDeployTriggersModal.svelte @@ -0,0 +1,47 @@ +<script lang="ts"> + import ConfirmationModal from '$lib/components/common/confirmationModal/ConfirmationModal.svelte' + import type { PipelineTriggerDraft } from './types' + + // Triggers start running once deployed, so deploying a pipeline's trigger + // drafts asks first, listing what will start. + let { + open, + triggerDrafts, + onConfirmed, + onCanceled + }: { + open: boolean + triggerDrafts: ReadonlyMap<string, PipelineTriggerDraft> + onConfirmed: () => void + onCanceled: () => void + } = $props() +</script> + +<ConfirmationModal + {open} + title="Deploy triggers?" + confirmationText="Deploy" + type="info" + {onConfirmed} + {onCanceled} +> + <div class="flex flex-col gap-2 text-xs text-secondary"> + <p> + {triggerDrafts.size === 1 + ? 'Saving the pipeline also creates this trigger. It starts running its script once deployed.' + : `Saving the pipeline also creates these ${triggerDrafts.size} triggers. They start running their scripts once deployed.`} + </p> + <ul class="flex flex-col gap-1"> + {#each [...triggerDrafts] as [key, d] (key)} + <li class="flex flex-col"> + <span class="font-mono text-2xs text-emphasis truncate">{d.config.path}</span> + <span class="text-2xs text-hint truncate"> + {d.kind}{#if d.kind === 'schedule'} + · <span class="font-mono">{d.config.schedule}</span> ({d.config.timezone}){/if} + → {d.config.script_path} + </span> + </li> + {/each} + </ul> + </div> +</ConfirmationModal> diff --git a/frontend/src/lib/components/assets/AssetGraph/PipelineFolderList.svelte b/frontend/src/lib/components/assets/AssetGraph/PipelineFolderList.svelte index d35b4f21d6..52772ce515 100644 --- a/frontend/src/lib/components/assets/AssetGraph/PipelineFolderList.svelte +++ b/frontend/src/lib/components/assets/AssetGraph/PipelineFolderList.svelte @@ -1,6 +1,5 @@ <script lang="ts"> import { userStore, workspaceStore } from '$lib/stores' - import { base } from '$lib/base' import { goto } from '$app/navigation' import Button from '$lib/components/common/button/Button.svelte' import FolderPicker from '$lib/components/FolderPicker.svelte' @@ -18,11 +17,18 @@ mode?: 'view' | 'edit' // Called right before navigating — lets a wrapping modal close itself. onOpen?: () => void + // Only the folder picker, for hosts that don't list pipelines. + hideExisting?: boolean } - let { currentFolder = undefined, mode = 'view', onOpen = undefined }: Props = $props() + let { + currentFolder = undefined, + mode = 'view', + onOpen = undefined, + hideExisting = false + }: Props = $props() let pipelines = resource( - () => $workspaceStore, + () => (hideExisting ? undefined : $workspaceStore), async (ws) => { if (!ws) return [] as ListPipelineFoldersResponse return await AssetService.listPipelineFolders({ workspace: ws }) @@ -38,7 +44,7 @@ async function openExistingPipeline(folder: string) { onOpen?.() const modeQuery = mode !== 'view' ? `?mode=${mode}` : '' - await goto(`${base}/pipeline/${encodeURIComponent(folder)}${modeQuery}`) + await goto(`/pipeline/${encodeURIComponent(folder)}${modeQuery}`) } async function openPicked() { @@ -49,50 +55,52 @@ </script> <div class="flex flex-col gap-6 w-full min-w-0"> - <section class="flex flex-col gap-2"> - <h3 class="text-xs font-semibold text-secondary uppercase tracking-wide"> - Existing pipelines - </h3> - {#if pipelines.loading && !pipelines.current} - <div class="text-tertiary text-sm flex items-center gap-2"> - <Loader2 size={14} class="animate-spin" /> - Loading… - </div> - {:else if pipelines.error} - <div class="text-red-500 text-sm">Failed: {pipelines.error.message}</div> - {:else if visiblePipelines.length === 0} - <div class="text-tertiary text-sm"> - {currentFolder - ? 'No other pipelines in this workspace.' - : 'No pipelines yet. A pipeline is any folder whose scripts carry pipeline annotations.'} - </div> - {:else} - <div class="flex flex-col border rounded-md overflow-hidden max-h-64 overflow-y-auto"> - {#each visiblePipelines as p (p.folder)} - <button - type="button" - class="flex items-center justify-between px-3 py-2 border-b last:border-b-0 bg-surface hover:bg-surface-hover transition-colors text-left" - onclick={() => openExistingPipeline(p.folder)} - > - <span class="font-mono text-sm">f/{p.folder}</span> - <span class="text-2xs text-tertiary"> - {p.script_count} - {p.script_count === 1 ? 'script' : 'scripts'} - </span> - </button> - {/each} - </div> - {/if} - </section> + {#if !hideExisting} + <section class="flex flex-col gap-2"> + <h3 class="text-sm font-semibold text-emphasis">Existing pipelines</h3> + {#if pipelines.loading && !pipelines.current} + <div class="text-tertiary text-sm flex items-center gap-2"> + <Loader2 size={14} class="animate-spin" /> + Loading… + </div> + {:else if pipelines.error} + <div class="text-red-500 text-sm">Failed: {pipelines.error.message}</div> + {:else if visiblePipelines.length === 0} + <div class="text-tertiary text-sm"> + {currentFolder + ? 'No other pipelines in this workspace.' + : 'No pipelines yet. A pipeline is any folder whose scripts carry pipeline annotations.'} + </div> + {:else} + <div class="flex flex-col border rounded-md overflow-hidden max-h-64 overflow-y-auto"> + {#each visiblePipelines as p (p.folder)} + <button + type="button" + class="flex items-center justify-between px-3 py-2 border-b last:border-b-0 bg-surface hover:bg-surface-hover transition-colors text-left" + onclick={() => openExistingPipeline(p.folder)} + > + <span class="font-mono text-sm">f/{p.folder}</span> + <span class="text-2xs text-tertiary"> + {p.script_count} + {p.script_count === 1 ? 'script' : 'scripts'} + </span> + </button> + {/each} + </div> + {/if} + </section> + {/if} {#if !$userStore?.operator} <!-- Operators only view existing pipelines — opening an arbitrary folder is a build-a-new-pipeline affordance. --> - <section class="flex flex-col gap-2"> - <h3 class="text-xs font-semibold text-secondary uppercase tracking-wide"> - Pick or create a folder - </h3> - <div class="flex items-center gap-2"> + <section class="flex flex-col gap-1"> + <h3 class="text-sm font-semibold text-emphasis">Pick or create a folder</h3> + <p class="text-xs text-secondary"> + Each folder holds one pipeline, made of its pipeline scripts. Pick a folder to open its + pipeline, or create one to start a new pipeline. + </p> + <div class="flex items-center gap-2 mt-1"> <div class="flex-1 min-w-0"> <FolderPicker bind:folderName={pickedFolder} /> </div> diff --git a/frontend/src/lib/components/assets/AssetGraph/PipelineGraphEditor.svelte b/frontend/src/lib/components/assets/AssetGraph/PipelineGraphEditor.svelte index b71a51ea0a..364c4c6221 100644 --- a/frontend/src/lib/components/assets/AssetGraph/PipelineGraphEditor.svelte +++ b/frontend/src/lib/components/assets/AssetGraph/PipelineGraphEditor.svelte @@ -1,6 +1,15 @@ <script lang="ts"> import { untrack, type Snippet } from 'svelte' - import { PIPELINE_DRAFT_KIND, pipelineBundlePath } from '$lib/pipelinePaths' + import { MousePointerClick } from 'lucide-svelte' + import Disposable from '$lib/components/common/drawer/Disposable.svelte' + import Portal from '$lib/components/Portal.svelte' + import { getOverlayHost } from '$lib/components/common/overlayHost.svelte' + import { useFlowPanelMode } from '$lib/components/flows/flowPanelMode.svelte' + import { + PIPELINE_DRAFT_KIND, + pipelineBundlePath, + pipelineLocalMirrorKey + } from '$lib/pipelinePaths' import { Loader2 } from 'lucide-svelte' import { Pane, Splitpanes } from 'svelte-splitpanes' import { DraftService } from '$lib/gen' @@ -11,6 +20,11 @@ import type { ColumnLineageGraph } from './columnLineageGraph' import HideButton from '$lib/components/apps/editor/settingsPanel/HideButton.svelte' import AssetGraphCanvas from './AssetGraphCanvas.svelte' + import { TRIGGER_NODE_STYLE } from './TriggerNode.svelte' + import { describeSchedule } from '$lib/utils/describeCron' + import type { UpstreamTriggerAction } from './upstreamScriptItems' + import type { AssetUpstreamDelete } from './assetsOnlyView' + import type { NodeFixSpec } from './NodeFixButton.svelte' import AssetGraphDetailsPane from './AssetGraphDetailsPane.svelte' import PipelineEventLog from './PipelineEventLog.svelte' import type { @@ -18,8 +32,10 @@ AssetGraphSelection, NativeTriggerKind, PipelineMode, + PipelineTriggerDraft, DbtAssetProvenance } from './types' + import { isDraftableTriggerKind, triggerDraftKey } from './pipelineTriggerDrafts' import type { AssetKind, Script, ScriptLang } from '$lib/gen' import type { RunnableRunState, PipelineEvent } from './activeRunnables.svelte' import type { PipelineOutputKind } from './pipelineTemplates' @@ -41,6 +57,7 @@ defaultPathSuffix = 'new_pipeline_script', panelHidden = false, onTogglePanelHidden, + modalPanel = false, prefetchingAssets = false, hoveredPaths = [], selectedRunPaths = [], @@ -65,6 +82,11 @@ onAddScriptForAsset, onAddPipelineScript, onRunnableMenuRemove, + onDeleteAssetUpstream, + nodeFixes, + assetDeleteVerb, + onEdgeAction, + onAddAssetTrigger, onRunProducer, idlePane, onRequestEdit, @@ -73,6 +95,9 @@ onRunCascadeByPath, runFormInitialArgs, onRunFormArgsChange, + inputsOnly = false, + onRunInputs, + onShowScript, readyDataUploadPaths, resolveLocalScript, localScriptsVersion, @@ -126,6 +151,9 @@ pathPrefix: string defaultPathSuffix?: string panelHidden?: boolean + /** Let the details pane open as a modal over a full-width graph when the editor + * is too narrow to dock it — the flow editor's step panel rule. */ + modalPanel?: boolean onTogglePanelHidden?: () => void prefetchingAssets?: boolean hoveredPaths?: string[] @@ -153,16 +181,29 @@ language: ScriptLang, scriptPath: string, outputKind: PipelineOutputKind, - aiPrompt?: string + aiPrompt?: string, + options?: import('./PipelineInsertMenu.svelte').PipelineInsertOptions ) => void onAddPipelineScript?: ( language: ScriptLang, path: string, source: { kind: NativeTriggerKind; path: string | undefined }, outputKind: PipelineOutputKind, - aiPrompt?: string + aiPrompt?: string, + options?: import('./PipelineInsertMenu.svelte').PipelineInsertOptions ) => void onRunnableMenuRemove?: (...args: any[]) => void + onDeleteAssetUpstream?: (target: AssetUpstreamDelete) => void + nodeFixes?: ReadonlyMap<string, NodeFixSpec> + assetDeleteVerb?: 'Delete' | 'Archive' + onEdgeAction?: (a: { + action: 'listen' | 'stop' + targets: Array<{ script: string; asset: { kind: AssetKind; path: string }; reads: boolean }> + }) => void + onAddAssetTrigger?: (a: { + scripts: Array<{ script: string; reads: boolean }> + asset: { kind: AssetKind; path: string } + }) => void onRunProducer?: (producer: RunProducer) => Promise<string | undefined> idlePane?: Snippet onRequestEdit?: () => void @@ -175,8 +216,16 @@ // callback to persist them as they change — see the page's dataUploadArgs. runFormInitialArgs?: Record<string, any> onRunFormArgsChange?: (path: string, args: Record<string, any>, isValid: boolean) => void + /** See AssetGraphDetailsPane's `inputsOnly`. */ + inputsOnly?: boolean + onRunInputs?: ( + path: string, + args: Record<string, any>, + live?: { content: string; language: ScriptLang } + ) => Promise<string | undefined> + onShowScript?: () => void // Data-upload entry scripts whose staged upload is ready (green node). - readyDataUploadPaths?: Set<string> + readyDataUploadPaths?: ReadonlySet<string> /** Local-dev (`/pipeline_dev`): resolve a node to its working-tree content * so the details pane skips the (nonexistent) deployed-script fetch. May * be async (to infer the args schema for the run form). */ @@ -247,18 +296,81 @@ ? (editor.selection != undefined || editor.activeDraftPath != undefined) && !panelHidden : !panelHidden ) + // Docked beside the graph, or in a modal over it (modal mode). In modal mode the + // details only show once asked for: a double-click on a node, a click on the + // node already selected, or a script's open button — never on a selection the + // editor makes itself (an AI-built node), which would pop a modal unasked. + const panelController = useFlowPanelMode({ enabled: () => modalPanel }) + $effect(() => panelController.measure(containerWidth)) + const panelMode = $derived(panelController.mode) + let panelModalOpen = $state(false) + const dockedPaneOpen = $derived(detailsPaneOpen && panelMode === 'docked') + $effect(() => { + if (untrack(() => panelModalOpen) && (panelMode === 'docked' || !detailsPaneOpen)) { + panelModalOpen = false + } + }) + let panelDisposable: Disposable | undefined = $state(undefined) + // Disposable joins the overlay stack through its methods, not by watching `open`. + $effect(() => { + panelModalOpen + untrack(() => { + panelModalOpen ? panelDisposable?.openDrawer() : panelDisposable?.closeDrawer() + }) + }) + const overlayHost = getOverlayHost() + const modalHost = $derived(overlayHost?.el()) + + function selectableNodeAt(e: MouseEvent): HTMLElement | null { + return (e.target as HTMLElement | null)?.closest('.svelte-flow__node.selectable') ?? null + } + // Read in the capture phase: once the click bubbles, the canvas has applied + // its selection and a first click looks like a click on the selected node. + let clickStartedOnSelected = false + function noteSelectionBeforeClick(e: MouseEvent) { + clickStartedOnSelected = !!selectableNodeAt(e)?.classList.contains('selected') + } + function openPanelModalIfReselected(e: MouseEvent) { + if (clickStartedOnSelected && selectableNodeAt(e)) panelModalOpen = true + } + function openPanelModalFromGraph(e: MouseEvent) { + if (selectableNodeAt(e)) panelModalOpen = true + } + // A button in the pane that ends it closes the modal in the same update: left to + // the effect above, the modal would first render the pane without its selection. + function closePanelModal() { + if (panelMode === 'modal') panelModalOpen = false + } + function handleCanvasSelect(s: AssetGraphSelection | undefined, opts?: { open?: boolean }) { + onSelect(s) + if (opts?.open && s && panelMode === 'modal') panelModalOpen = true + } + // A data-upload node's click asks for its run form; in modal mode nothing shows + // it unless the modal opens too. + $effect(() => { + if (focusUploadSignal > 0 && untrack(() => panelMode) === 'modal') { + untrack(() => (panelModalOpen = true)) + } + }) + const showNodeHint = $derived(panelMode === 'modal' && !panelModalOpen) + const nodeHintText = $derived( + effectiveSelection + ? 'Click the selected node to open it' + : 'Double click a node to open it' + ) + let idleView = $derived( mode !== 'edit' && editor.selection == undefined && editor.activeDraftPath == undefined ) // Wrap the writes (and the rightPaneSize read in the else branch) in untrack so - // the effect tracks only `detailsPaneOpen` / `storedRightPaneSize` — without it, + // the effect tracks only `dockedPaneOpen` / `storedRightPaneSize` — without it, // the Pane `bind:size` feedback loops the effect and pegs the main thread. $effect(() => { // Stacked (vertical) splits give the details pane more room — the run // form + result need height more than the graph needs it. const fallback = stacked ? 55 : 40 - if (detailsPaneOpen) { + if (dockedPaneOpen) { const restore = storedRightPaneSize untrack(() => { rightPaneSize = restore > 0 ? restore : fallback @@ -272,6 +384,67 @@ } }) + // The selected asset's producing scripts, named and iconed from the graph, for + // the pane's "Edit script". + let producerScripts = $derived( + selectionProducers + .filter((p) => p.kind === 'script') + .map((p) => { + const r = displayGraph.runnables.find((x) => x.usage_kind === 'script' && x.path === p.path) + return { path: p.path, summary: r?.summary, language: r?.language } + }) + ) + // The selected asset's upstream triggers that can be opened from here, each + // with the same action its trigger node has: edit (edit mode), create a + // missing one (edit mode), or the webhook / data-upload drawers. + let producerTriggers = $derived.by((): UpstreamTriggerAction[] => { + const scripts = new Set(producerScripts.map((p) => p.path)) + const seen = new Set<string>() + const out: UpstreamTriggerAction[] = [] + for (const t of displayGraph.triggers ?? []) { + if (t.trigger_kind === 'asset' || !scripts.has(t.runnable_path)) continue + const kind = t.trigger_kind + const rowless = kind === 'webhook' || kind === 'data_upload' + const key = `${kind}:${rowless || t.missing ? t.runnable_path : t.path}` + if (seen.has(key)) continue + seen.add(key) + const label = TRIGGER_NODE_STYLE[kind]?.label ?? kind + const script = t.runnable_path + let action: UpstreamTriggerAction | undefined + if (kind === 'webhook') { + if (onOpenWebhook) + action = { label: 'Open webhook', detail: script, onOpen: () => onOpenWebhook(script) } + } else if (kind === 'data_upload') { + if (onOpenDataUpload) + action = { label: 'Upload data', detail: script, onOpen: () => onOpenDataUpload(script) } + } else if (t.missing && !rowless) { + if (onCreateMissingTrigger) + action = { + label: `Create ${label} trigger`, + detail: script, + onOpen: () => onCreateMissingTrigger(kind, script) + } + } else if (t.path && onEditTrigger) { + const path = t.path + action = { + label: kind === 'schedule' ? 'Edit schedule' : `Edit ${label} trigger`, + detail: + kind === 'schedule' && t.schedule + ? (t.summary ?? describeSchedule(t.schedule, t.timezone) ?? path) + : path, + onOpen: () => onEditTrigger(kind, path, script) + } + } + if (action) out.push(action) + } + return out + }) + + function editProducerScript(path: string) { + if (mode !== 'edit') onRequestEdit?.() + onSelect({ kind: 'runnable', runnable_kind: 'script', path }) + } + // ===================== Draft autosave (persistDrafts only) ===================== // All of this folder's in-flight drafts live in ONE per-user DB draft (typ // `data_pipeline`) keyed at the folder, syncing across devices + surfacing in @@ -279,12 +452,21 @@ // for the one-time migration below; the DB is the source of truth on load. // FlowBuilder's autosave analogue — gated by `persistDrafts`. let pipelineDraftPath = $derived(pipelineBundlePath(folder)) - let storageKey = $derived(`pipeline-${folder}`) - type PipelineDraftBundle = { drafts: Array<[string, PipelineDraft]>; activeDraftPath?: string } + let storageKey = $derived(pipelineLocalMirrorKey(folder)) + type PipelineDraftBundle = { + drafts: Array<[string, PipelineDraft]> + activeDraftPath?: string + triggerDrafts?: PipelineTriggerDraft[] + } // Hydration is tracked on the editor instance (`editor.hydratedFromDb`), not a // component flag: the in-session preview reuses one instance across editor // hide/show, and it must hydrate ONCE per instance, not on every remount. let lastPersistedBundle: string | undefined = undefined + // What decides whether the bundle needs saving: its drafts, not which one is + // open. Opening a draft is not an edit, so it rides along with the next real + // change instead of saving (and spinning the sync indicator) on a click. + const persistKey = (b: PipelineDraftBundle | undefined) => + b ? JSON.stringify({ drafts: b.drafts, triggerDrafts: b.triggerDrafts }) : undefined function restoreBundle(bundle: PipelineDraftBundle) { if (Array.isArray(bundle.drafts)) { @@ -300,6 +482,18 @@ if (loaded.size > 0) editor.drafts = loaded } if (typeof bundle.activeDraftPath === 'string') editor.activeDraftPath = bundle.activeDraftPath + if (Array.isArray(bundle.triggerDrafts)) { + editor.triggerDrafts = new Map( + bundle.triggerDrafts + .filter( + (d) => + isDraftableTriggerKind(d?.kind) && + typeof d.config?.path === 'string' && + typeof d.config?.script_path === 'string' + ) + .map((d) => [triggerDraftKey(d.kind, d.config.path), d]) + ) + } } function readLocalBundle(): PipelineDraftBundle | undefined { @@ -311,7 +505,8 @@ if (s && (Array.isArray(s.drafts) || typeof s.activeDraftPath === 'string')) { return { drafts: Array.isArray(s.drafts) ? s.drafts : [], - activeDraftPath: typeof s.activeDraftPath === 'string' ? s.activeDraftPath : undefined + activeDraftPath: typeof s.activeDraftPath === 'string' ? s.activeDraftPath : undefined, + triggerDrafts: Array.isArray(s.triggerDrafts) ? s.triggerDrafts : undefined } } } catch (e) { @@ -339,8 +534,8 @@ fromServer = true } } - // A folder retarget during the await (the route-page header switcher, or a - // session retarget) changed the target and reset hydratedFromDb. Don't + // A folder switch during the await (the route page's header switcher) + // changed the target and reset hydratedFromDb. Don't // apply this now-stale folder's bundle or mark the new folder hydrated — // otherwise the stale result blocks the new folder's hydrate and its // drafts bleed across folders. @@ -359,7 +554,7 @@ { workspace: ws ?? '', itemKind: PIPELINE_DRAFT_KIND, path }, migratedFromLocal ? undefined : serverSavedAt ) - if (!migratedFromLocal) lastPersistedBundle = bundle ? JSON.stringify(bundle) : undefined + if (!migratedFromLocal) lastPersistedBundle = persistKey(bundle) } catch (e) { console.warn('failed to load pipeline drafts', e) } finally { @@ -412,30 +607,52 @@ return [p, d] as [string, PipelineDraft] return [p, { ...d, script, outputAssets, inputAssets }] as [string, PipelineDraft] }) + // A deployed script being edited is only promoted to a draft when its pane + // closes; until then its buffer is saved as the draft it will become. + const { scriptPath: livePath, content: liveBody, base } = editor.liveContent + if ( + livePath != undefined && + base && + !editor.drafts.has(livePath) && + liveBody !== (base.content ?? '') + ) { + const live = editor.liveBodyAssets.scriptPath === livePath + const writes = live ? extractWrites(editor.liveBodyAssets.assets) : [] + serialized.push([ + livePath, + { + localId: editor.promotedDraftLocalId(livePath), + script: { ...base, content: liveBody }, + outputAssets: writes.length > 0 ? writes : undefined, + inputAssets: live ? extractReads(editor.liveBodyAssets.assets) : undefined + } + ]) + } const activePath = editor.activeDraftPath + const triggerDrafts = [...editor.triggerDrafts.values()] const key = storageKey const ws = workspace const path = pipelineDraftPath const hydrated = editor.hydratedFromDb untrack(() => { if (!hydrated) return - const isEmpty = serialized.length === 0 && !activePath + const isEmpty = serialized.length === 0 && !activePath && triggerDrafts.length === 0 const bundle: PipelineDraftBundle | undefined = isEmpty ? undefined - : { drafts: serialized, activeDraftPath: activePath } + : { + drafts: serialized, + activeDraftPath: activePath, + ...(triggerDrafts.length > 0 ? { triggerDrafts } : {}) + } try { if (typeof localStorage !== 'undefined') { if (isEmpty) localStorage.removeItem(key) - else - localStorage.setItem( - key, - encodeState({ drafts: serialized, activeDraftPath: activePath }) - ) + else localStorage.setItem(key, encodeState(bundle)) } } catch (e) { console.warn('failed to mirror pipeline state', e) } - const serializedBundle = bundle ? JSON.stringify(bundle) : undefined + const serializedBundle = persistKey(bundle) if (serializedBundle === lastPersistedBundle) return lastPersistedBundle = serializedBundle if (!ws) return @@ -450,10 +667,90 @@ }) </script> -<div class="h-full w-full" bind:clientWidth={containerWidth}> +{#snippet detailsBody(ws: string)} + {#if idleView && idlePane} + {@render idlePane()} + {:else} + <AssetGraphDetailsPane + {mode} + {onRequestEdit} + {canRunByPath} + {onRunByPath} + {onRunCascadeByPath} + {runFormInitialArgs} + {onRunFormArgsChange} + {inputsOnly} + {onRunInputs} + {onShowScript} + {resolveLocalScript} + {localScriptsVersion} + selection={activeDraft ? undefined : editor.selection} + selectionProducers={activeDraft ? [] : selectionProducers} + {producerScripts} + onEditScript={editProducerScript} + {producerTriggers} + {selectionColumnGraph} + {selectionColumnLoading} + {selectionColumnTruncated} + {selectionColumnFailed} + {selectionDbt} + {schemaCanEvolve} + {selectionForkMaterialization} + {schemaContractContext} + {runsRefreshKey} + {runsPendingJobId} + {activeRunnable} + {downstreamSubscribers} + onStartBoundedRun={canBoundedRunOpenScript && + editor.openScriptPath && + onStartBoundedRunForOpen + ? () => onStartBoundedRunForOpen?.(editor.openScriptPath!) + : undefined} + {onRunCompleted} + {onTestStateChange} + {requestRemoveSignal} + {requestRunSignal} + {requestRunCascadeSignal} + {focusUploadSignal} + draftScript={activeDraft?.script} + draftOutputAssets={activeDraft?.outputAssets} + draftInputAssets={activeDraft?.inputAssets} + {onDraftPathChange} + onDraftMetaChange={editor.setDraftMeta} + {pathPrefix} + workspace={ws} + onAnnotationsChange={editor.handleAnnotationsChange} + onAssetsChange={editor.handleAssetsChange} + onContentChange={editor.handleContentChange} + onDraftPersist={editor.handleDraftPersist} + onclose={() => { + closePanelModal() + onClose() + }} + onHide={onTogglePanelHidden && + (() => { + closePanelModal() + onTogglePanelHidden() + })} + {onDiscard} + {onDraftSaved} + {onPersistedSaved} + {onScriptRenamed} + {onScriptRemoved} + /> + {/if} +{/snippet} + +<div class="relative h-full w-full" bind:clientWidth={containerWidth}> <Splitpanes class="!h-full" horizontal={stacked}> <Pane bind:size={leftPaneSize}> - <div class="relative h-full"> + <!-- svelte-ignore a11y_click_events_have_key_events, a11y_no_static_element_interactions --> + <div + class="relative h-full" + ondblclick={panelMode === 'modal' ? openPanelModalFromGraph : undefined} + onpointerdowncapture={panelMode === 'modal' ? noteSelectionBeforeClick : undefined} + onclick={panelMode === 'modal' ? openPanelModalIfReselected : undefined} + > <AssetGraphCanvas graph={displayGraph} selection={effectiveSelection} @@ -470,10 +767,15 @@ {onOpenWebhook} {onOpenDataUpload} {readyDataUploadPaths} - onselect={onSelect} + onselect={handleCanvasSelect} {onAddScriptForAsset} {onAddPipelineScript} {onRunnableMenuRemove} + {onDeleteAssetUpstream} + {nodeFixes} + {assetDeleteVerb} + {onEdgeAction} + {onAddAssetTrigger} {onRunProducer} {validStartPaths} {onStartBoundedRun} @@ -482,6 +784,8 @@ {panToNodeId} showMinimap={!stacked} viewportFitKey={viewportFitKey ?? folder} + assetsOnlyToggle + assetsOnlyFolder={workspace ? `${workspace}/${folder}` : undefined} /> {#if boundBar}{@render boundBar()}{/if} {#if mode === 'edit'} @@ -509,66 +813,47 @@ {/if} </div></Pane > - {#if detailsPaneOpen && workspace} + {#if dockedPaneOpen && workspace} <Pane bind:size={rightPaneSize} minSize={25}> - {#if idleView && idlePane} - {@render idlePane()} - {:else} - <AssetGraphDetailsPane - {mode} - {onRequestEdit} - {canRunByPath} - {onRunByPath} - {onRunCascadeByPath} - {runFormInitialArgs} - {onRunFormArgsChange} - {resolveLocalScript} - {localScriptsVersion} - selection={activeDraft ? undefined : editor.selection} - selectionProducers={activeDraft ? [] : selectionProducers} - {selectionColumnGraph} - {selectionColumnLoading} - {selectionColumnTruncated} - {selectionColumnFailed} - {selectionDbt} - {schemaCanEvolve} - {selectionForkMaterialization} - {schemaContractContext} - {runsRefreshKey} - {runsPendingJobId} - {activeRunnable} - {downstreamSubscribers} - onStartBoundedRun={canBoundedRunOpenScript && - editor.openScriptPath && - onStartBoundedRunForOpen - ? () => onStartBoundedRunForOpen?.(editor.openScriptPath!) - : undefined} - {onRunCompleted} - {onTestStateChange} - {requestRemoveSignal} - {requestRunSignal} - {requestRunCascadeSignal} - {focusUploadSignal} - draftScript={activeDraft?.script} - draftOutputAssets={activeDraft?.outputAssets} - draftInputAssets={activeDraft?.inputAssets} - {pathPrefix} - {onDraftPathChange} - {workspace} - onAnnotationsChange={editor.handleAnnotationsChange} - onAssetsChange={editor.handleAssetsChange} - onContentChange={editor.handleContentChange} - onDraftPersist={editor.handleDraftPersist} - onclose={onClose} - onHide={onTogglePanelHidden} - {onDiscard} - {onDraftSaved} - {onPersistedSaved} - {onScriptRenamed} - {onScriptRemoved} - /> - {/if} + {@render detailsBody(workspace)} </Pane> {/if} </Splitpanes> + {#if showNodeHint} + <!-- Above the event log's bar, which owns the canvas's bottom edge. --> + <div + class="pointer-events-none absolute bottom-10 left-3 z-30 flex items-center gap-1.5 text-xs text-hint" + > + <MousePointerClick size={13} /> + {nodeHintText} + </div> + {/if} </div> + +<!-- Portalled to the host's overlay anchor (a session preview tab) so the modal covers + that tab rather than the whole page; Disposable owns its place in the overlay stack + and its Escape. --> +<Disposable bind:open={panelModalOpen} bind:this={panelDisposable}> + {#snippet children({ zIndex })} + {#if panelMode === 'modal' && panelModalOpen && workspace} + <Portal target={modalHost ?? 'body'} class="contents"> + <!-- svelte-ignore a11y_click_events_have_key_events --> + <!-- svelte-ignore a11y_no_static_element_interactions --> + <div + class="{modalHost ? 'absolute' : 'fixed'} inset-0 flex justify-center px-2 py-6" + style="z-index: {zIndex}" + role="dialog" + > + <div class="absolute inset-0 bg-black/20" onclick={() => (panelModalOpen = false)}></div> + <div + class="relative flex w-full max-w-4xl flex-col overflow-hidden rounded-md border bg-surface shadow-xl" + > + <div class="min-h-0 flex-1 overflow-auto"> + {@render detailsBody(workspace)} + </div> + </div> + </div> + </Portal> + {/if} + {/snippet} +</Disposable> diff --git a/frontend/src/lib/components/assets/AssetGraph/PipelineInsertMenu.svelte b/frontend/src/lib/components/assets/AssetGraph/PipelineInsertMenu.svelte index e341707250..c1b64b59a2 100644 --- a/frontend/src/lib/components/assets/AssetGraph/PipelineInsertMenu.svelte +++ b/frontend/src/lib/components/assets/AssetGraph/PipelineInsertMenu.svelte @@ -1,6 +1,7 @@ <script lang="ts" module> import type { ComponentType } from 'svelte' import type { SupportedLanguage } from '$lib/common' + import type { AssetKind, NewSchedule } from '$lib/gen' export type PipelineInsertKind = { // Machine-readable id; drives which right-column panel renders. @@ -8,6 +9,9 @@ label: string description?: string icon?: ComponentType + // Its trigger is configured in its own editor right after the script is + // created, so the wizard's last button reads "Configure". + configuredAfterCreate?: boolean } export type PipelineInsertPick = { @@ -22,7 +26,18 @@ // from this prompt via AI (using language + outputKind + the // upstream input as context) instead of using the seeded template. aiPrompt?: string + // Set by the schedule step when the picked kind is `schedule`. + schedule?: PipelineInsertSchedule + // Set by the asset step for the table output kinds, replacing the + // generated name. + outputAsset?: { kind: AssetKind; path: string } } + + export type PipelineInsertOptions = Pick<PipelineInsertPick, 'schedule' | 'outputAsset'> + + // Everything but the target, which is the script being created. An empty + // `path` means the default `<script>_schedule`. + export type PipelineInsertSchedule = Omit<NewSchedule, 'script_path'> </script> <script lang="ts"> @@ -36,10 +51,28 @@ PIPELINE_OUTPUT_KINDS, type PipelineOutputKind } from './pipelineTemplates' + import CronInput from '$lib/components/CronInput.svelte' import type { ScriptLang } from '$lib/gen' import Label from '$lib/components/Label.svelte' - import TextInput from '$lib/components/text_input/TextInput.svelte' - import { CornerDownLeft, Sparkles } from 'lucide-svelte' + import TextInput, { + inputBaseClass, + inputBorderClass, + inputSizeClasses + } from '$lib/components/text_input/TextInput.svelte' + import DucklakePicker from '$lib/components/DucklakePicker.svelte' + import DatatablePicker from '$lib/components/DatatablePicker.svelte' + import Path from '$lib/components/Path.svelte' + import Section from '$lib/components/Section.svelte' + import Toggle from '$lib/components/Toggle.svelte' + import DateTimeInput from '$lib/components/DateTimeInput.svelte' + import ScheduleAdvancedOptions, { + emptyScheduleAdvanced, + loadDefaultScheduleAdvanced, + scheduleAdvancedCfg + } from '$lib/components/triggers/schedules/ScheduleAdvancedOptions.svelte' + import { workspaceStore } from '$lib/stores' + import { ArrowLeft, ChevronDown, CornerDownLeft, Loader2, Sparkles } from 'lucide-svelte' + import { tick, untrack } from 'svelte' import { arrowTabNav } from '$lib/attachments/arrowTabNav' import { selectAndAdvanceTo } from '$lib/attachments/selectAndAdvanceTo' @@ -49,8 +82,15 @@ pathPrefix?: string defaultPathSuffix?: string onPick: (pick: PipelineInsertPick) => void - trigger: import('svelte').Snippet + /** Receives whether the menu is open, e.g. to keep a hover state while it is. */ + trigger: import('svelte').Snippet<[{ open: boolean }]> placement?: 'bottom' | 'top' | 'left' | 'right' + /** Opens the menu each time it changes, for an entry point other than the trigger. */ + openSignal?: number + /** With `openSignal`: only the schedule step, for this existing script; its + * confirm hands the schedule to `onSchedule` instead of creating a script. */ + scheduleFor?: string + onSchedule?: (schedule: PipelineInsertSchedule) => void } let { @@ -60,7 +100,10 @@ trigger: triggerSnippet, placement = 'bottom', defaultPathSuffix, - onPick + onPick, + openSignal, + scheduleFor, + onSchedule }: Props = $props() // When there's only one trigger kind, hide the Trigger column entirely @@ -75,6 +118,107 @@ aiPrompt: undefined as undefined | string }) let selected = $state(buildEmptySelected()) + let menuOpen = $state(false) + $effect(() => { + if (!openSignal) return + untrack(() => { + if (scheduleFor) { + resetWizard() + selected.triggerId = 'schedule' + step = 1 + config.schedulePath = `${scheduleFor}_schedule` + loadAdvancedDefaults() + void focusCurrentStep() + } + menuOpen = true + }) + }) + let selectedKind = $derived(kinds.find((k) => k.id === selected.triggerId)) + + // Steps after the first, each configuring something the picks call for. + type ConfigStep = 'schedule' | 'asset' + const NAMED_OUTPUT_KINDS: PipelineOutputKind[] = ['materialize', 'datatable', 'ducklake'] + let configSteps = $derived.by<ConfigStep[]>(() => { + const steps: ConfigStep[] = [] + if (selected.triggerId === 'schedule') steps.push('schedule') + if (selected.outputId && NAMED_OUTPUT_KINDS.includes(selected.outputId)) steps.push('asset') + return steps + }) + // 0 is the trigger/language/output/path step; `n` is `configSteps[n - 1]`. + let step = $state(0) + let currentConfigStep = $derived(step > 0 ? configSteps[step - 1] : undefined) + let isLastStep = $derived(step >= configSteps.length) + + const buildEmptyConfig = () => ({ + schedule: '0 0 12 * *', + timezone: Intl.DateTimeFormat().resolvedOptions().timeZone, + cronVersion: 'v2', + validCron: true, + // Follows the script path until the Path field is edited. + schedulePath: '', + schedulePathDirty: false, + schedulePathError: '', + summary: '', + description: '', + pauseUntil: false, + pausedUntil: undefined as string | undefined, + advanced: emptyScheduleAdvanced(), + // The workspace's default handlers, loaded when the schedule step opens. + advancedDefaults: 'unloaded' as 'unloaded' | 'loading' | 'loaded', + // `store` is the data table or DuckLake catalog name. The table name + // follows the script name until the user types in it. + asset: undefined as + | undefined + | { kind: 'ducklake' | 'datatable'; store: string | undefined; table: string }, + tableEdited: false + }) + let config = $state(buildEmptyConfig()) + + // A new schedule starts from the workspace's default handlers, as in the schedule + // drawer. The step cannot be confirmed until they are in. + function loadAdvancedDefaults() { + const ws = $workspaceStore + if (!ws || config.advancedDefaults !== 'unloaded') return + const target = config + target.advancedDefaults = 'loading' + loadDefaultScheduleAdvanced(ws) + .then((d) => (target.advanced = d)) + .catch(() => {}) + .finally(() => (target.advancedDefaults = 'loaded')) + } + + function resetWizard() { + selected = buildEmptySelected() + config = buildEmptyConfig() + step = 0 + } + + const TABLE_NAME_RE = /^[^/\s]+$/ + // The path grammar of `Path.svelte`: word segments, no empty or trailing ones. + const SCRIPT_NAME_RE = /^[\w-]+(\/[\w-]+)*$/ + let scriptNameValid = $derived(SCRIPT_NAME_RE.test(selected.scriptPath.trim())) + let assetValid = $derived(!!config.asset?.store && TABLE_NAME_RE.test(config.asset.table.trim())) + let stepValid = $derived( + currentConfigStep === 'schedule' + ? config.validCron && + !!config.schedule.trim() && + !config.schedulePathError && + config.advancedDefaults === 'loaded' + : currentConfigStep === 'asset' + ? assetValid + : scriptNameValid && !!selected.triggerId && !!selected.language && !!selected.outputId + ) + + function enterAssetStep() { + const kind = selected.outputId === 'datatable' ? 'datatable' : 'ducklake' + if (config.asset?.kind !== kind) { + config.asset = { kind, store: 'main', table: '' } + config.tableEdited = false + } + if (!config.tableEdited && config.asset) { + config.asset.table = selected.scriptPath.trim().split('/').pop() ?? '' + } + } // Refs to the column containers so Enter inside one column can hand // focus off to the first tabbable in the next column. @@ -104,16 +248,73 @@ return out } + // A step change re-renders the popover body, dropping focus to <body>, where + // keystrokes (Enter, Cmd+Enter) no longer reach the step's key handlers. + let contentEl: HTMLElement | undefined = $state() + async function focusCurrentStep() { + await tick() + const target = + step === 0 + ? pathEl?.querySelector('input') + : contentEl?.querySelector<HTMLElement>('[data-autofocus] input') + target?.focus() + } + + function goBack() { + step -= 1 + void focusCurrentStep() + } + + function scheduleConfig(): PipelineInsertSchedule { + return { + path: config.schedulePath, + schedule: config.schedule.trim(), + timezone: config.timezone, + cron_version: config.cronVersion, + summary: config.summary.trim() || undefined, + description: config.description, + paused_until: config.pauseUntil ? config.pausedUntil : undefined, + is_flow: false, + args: {}, + ...scheduleAdvancedCfg($state.snapshot(config.advanced)) + } + } + function confirm(close: () => void) { + if (scheduleFor) { + if (!stepValid) return + onSchedule?.(scheduleConfig()) + close() + return + } const suffix = selected.scriptPath.trim() if (!suffix || !selected.triggerId || !selected.language || !selected.outputId) return + if (!stepValid) return + if (!isLastStep) { + step += 1 + if (configSteps[step - 1] === 'asset') enterAssetStep() + if (configSteps[step - 1] === 'schedule') { + loadAdvancedDefaults() + if (!config.schedulePathDirty) config.schedulePath = `${pathPrefix}${suffix}_schedule` + } + void focusCurrentStep() + return + } const trimmedPrompt = selected.aiPrompt?.trim() onPick({ kindId: selected.triggerId, language: selected.language, path: pathPrefix + suffix, outputKind: selected.outputId, - aiPrompt: trimmedPrompt && trimmedPrompt.length > 0 ? trimmedPrompt : undefined + aiPrompt: trimmedPrompt && trimmedPrompt.length > 0 ? trimmedPrompt : undefined, + schedule: configSteps.includes('schedule') ? scheduleConfig() : undefined, + outputAsset: + configSteps.includes('asset') && config.asset + ? { + kind: config.asset.kind as AssetKind, + path: `${config.asset.store}/${config.asset.table.trim()}` + } + : undefined }) close() } @@ -123,9 +324,18 @@ enableFlyTransition contentClasses={twMerge( 'p-0 bg-surface overflow-hidden relative transition-height', - showBottomPanel ? 'h-[26rem]' : 'h-[22rem]' + // The first step's columns (w-56 + w-48 + w-80), held across steps. + singleKind ? 'w-[32rem]' : 'w-[46rem]', + currentConfigStep === 'schedule' + ? 'h-[27rem]' + : currentConfigStep === 'asset' + ? 'h-[14rem]' + : showBottomPanel + ? 'h-[26rem]' + : 'h-[22rem]' )} class="inline-block" + bind:isOpen={menuOpen} usePointerDownOutside floatingConfig={{ placement, @@ -136,24 +346,30 @@ fitViewport: true, overlap: false }} - onClose={() => (selected = buildEmptySelected())} + onClose={resetWizard} > {#snippet trigger()} - {@render triggerSnippet?.()} + {@render triggerSnippet?.({ open: menuOpen })} {/snippet} {#snippet content({ close })} - <div class="flex flex-col h-full"> - <div class={'flex flex-row transition-height divide-x overflow-y-scroll'}> - {@render topSection()} - </div> - <div - class={twMerge( - 'flex flex-col gap-5 grow transition-height px-4 border-t', - showBottomPanel ? 'h-[14rem] py-4' : 'h-0' - )} - > - {@render bottomSection(close)} - </div> + <div class="h-full" bind:this={contentEl}> + {#if currentConfigStep} + {@render configStepSection(currentConfigStep, close)} + {:else} + <div class="flex flex-col h-full"> + <div class={'flex flex-row transition-height divide-x overflow-y-scroll'}> + {@render topSection()} + </div> + <div + class={twMerge( + 'flex flex-col gap-5 grow transition-height px-4 border-t', + showBottomPanel ? 'h-[14rem] py-4' : 'h-0' + )} + > + {@render bottomSection(close)} + </div> + </div> + {/if} </div> {/snippet} </Popover> @@ -170,7 +386,10 @@ <Button variant="subtle" btnClasses={'text-left'} - onClick={() => (selected.triggerId = k.id)} + onClick={() => { + selected.triggerId = k.id + if (k.id === 'schedule') loadAdvancedDefaults() + }} selected={isSelected} > {#if k.icon} @@ -264,14 +483,30 @@ {#snippet bottomSection(close: () => void)} <Label label="Path"> <!-- svelte-ignore a11y_no_static_element_interactions --> - <div bind:this={pathEl} class="flex" onkeydown={selectAndAdvanceTo(() => aiPromptEl ?? saveEl)}> + <div + bind:this={pathEl} + class="flex" + onkeydown={(e) => + (e.metaKey || e.ctrlKey) && e.key === 'Enter' + ? (e.preventDefault(), e.stopPropagation(), confirm(close)) + : selectAndAdvanceTo(() => aiPromptEl ?? saveEl)(e)} + > <div class="border rounded-md rounded-r-none border-r-0 text-xs w-fit shrink-0 whitespace-nowrap flex items-center px-2 text-secondary bg-surface-input" > {pathPrefix} </div> - <TextInput bind:value={selected.scriptPath} class="rounded-l-none" /> + <TextInput + bind:value={selected.scriptPath} + class="rounded-l-none" + error={!scriptNameValid && !!selected.scriptPath.trim()} + /> </div> + {#if !scriptNameValid && selected.scriptPath.trim()} + <span class="text-2xs text-red-600 dark:text-red-400"> + Letters, digits, <code>_</code> and <code>-</code>, in <code>/</code>-separated segments + </span> + {/if} </Label> {#if !$copilotInfo.workspaceDisabled} <Label label="AI Prompt (optional)"> @@ -292,15 +527,208 @@ </div> </Label> {/if} - {@const hasAiPrompt = !!selected.aiPrompt?.trim()} <div class="ml-auto" bind:this={saveEl}> - <Button - variant="accent" - btnClasses="w-fit" - disabled={!selected.scriptPath.trim()} - onClick={() => confirm(close)} - startIcon={hasAiPrompt ? { icon: Sparkles } : undefined} - shortCut={{ Icon: CornerDownLeft }}>{hasAiPrompt ? 'Generate' : 'Create'}</Button - > + {@render confirmButton(close)} + </div> +{/snippet} + +{#snippet confirmButton(close: () => void)} + {@const hasAiPrompt = !!selected.aiPrompt?.trim()} + <Button + variant="accent" + btnClasses="w-fit" + disabled={!stepValid} + onClick={() => confirm(close)} + startIcon={isLastStep && hasAiPrompt ? { icon: Sparkles } : undefined} + shortCut={{ Icon: CornerDownLeft }} + >{scheduleFor + ? 'Create schedule' + : !isLastStep + ? step === 0 + ? 'Configure' + : 'Next' + : hasAiPrompt + ? 'Generate' + : selectedKind?.configuredAfterCreate + ? 'Configure' + : 'Create'}</Button + > +{/snippet} + +{#snippet configStepSection(configStep: ConfigStep, close: () => void)} + <!-- svelte-ignore a11y_no_static_element_interactions --> + <div + class="flex flex-col h-full" + onkeydown={(e) => { + if (e.key !== 'Enter') return + const target = e.target as HTMLElement | null + // Cmd/Ctrl+Enter confirms from anywhere; bare Enter only from the step's own + // inputs, not from the Advanced fields (a textarea, pickers with their own Enter). + const bareEnterSubmits = target?.tagName === 'INPUT' && !target.closest('[data-advanced]') + if (e.metaKey || e.ctrlKey || bareEnterSubmits) { + e.preventDefault() + e.stopPropagation() + confirm(close) + } + }} + > + <div class="flex items-center gap-2 px-2 py-2 border-b"> + {#if !scheduleFor} + <Button + variant="subtle" + unifiedSize="sm" + iconOnly + startIcon={{ icon: ArrowLeft }} + onClick={goBack} + title="Back" + /> + {/if} + <span class="text-xs font-semibold text-emphasis {scheduleFor ? 'pl-2' : ''}"> + {scheduleFor + ? `Schedule for ${scheduleFor}` + : configStep === 'schedule' + ? 'Schedule' + : 'Output asset'} + </span> + {#if !scheduleFor} + <span class="text-2xs text-hint ml-auto pr-2" + >Step {step + 1} of {configSteps.length + 1}</span + > + {/if} + </div> + <div class="flex flex-col gap-2 grow overflow-auto p-4"> + {#if configStep === 'schedule'} + <span class="text-2xs text-secondary"> + Saved as a draft schedule and deployed along with the pipeline. + </span> + <div data-autofocus class="contents"> + <CronInput + bind:schedule={config.schedule} + bind:timezone={config.timezone} + bind:validCRON={config.validCron} + bind:cronVersion={config.cronVersion} + /> + </div> + <div data-advanced class="mt-4"> + <Section label="Advanced" collapsable initiallyCollapsed> + <div class="flex flex-col gap-6"> + <Label label="Summary"> + <TextInput + bind:value={config.summary} + inputProps={{ placeholder: 'Short summary to be displayed when listed' }} + /> + </Label> + <Label label="Path"> + <Path + bind:path={config.schedulePath} + bind:dirty={config.schedulePathDirty} + bind:error={config.schedulePathError} + initialPath="" + checkInitialPathExistence + namePlaceholder="schedule" + kind="schedule" + /> + </Label> + <Label label="Description"> + <TextInput + underlyingInputEl="textarea" + bind:value={config.description} + inputProps={{ placeholder: 'What this schedule does and how to use it' }} + /> + </Label> + <div class="flex flex-col gap-1"> + <Toggle + options={{ + right: 'Pause schedule until...', + rightTooltip: + 'Pausing the schedule will program the next job to run as if the schedule starts at the time the pause is lifted, instead of now.' + }} + bind:checked={config.pauseUntil} + /> + {#if config.pauseUntil} + <DateTimeInput bind:value={config.pausedUntil} /> + {/if} + </div> + <!-- Rendered once the workspace defaults are in, so they never + overwrite a handler picked while they load. --> + {#if config.advancedDefaults === 'loaded'} + <ScheduleAdvancedOptions + wsId={$workspaceStore} + itemKind="script" + canWrite + bind:errorHandler={config.advanced.errorHandler} + bind:wsErrorHandlerMuted={config.advanced.wsErrorHandlerMuted} + bind:failedTimes={config.advanced.failedTimes} + bind:failedExact={config.advanced.failedExact} + bind:recoveryHandler={config.advanced.recoveryHandler} + bind:recoveredTimes={config.advanced.recoveredTimes} + bind:successHandler={config.advanced.successHandler} + bind:retry={config.advanced.retry} + bind:dynamicSkipPath={config.advanced.dynamicSkipPath} + bind:tag={config.advanced.tag} + /> + {:else} + <div class="flex items-center gap-1.5 text-xs text-secondary"> + <Loader2 size={12} class="animate-spin" /> + Loading the workspace's default handlers… + </div> + {/if} + </div> + </Section> + </div> + {:else if configStep === 'asset' && config.asset} + <Label label="Name"> + <div + class={twMerge( + inputBaseClass, + inputBorderClass({ error: !assetValid }), + inputSizeClasses.md, + 'flex flex-row items-center gap-0 py-0 pl-2 pr-0' + )} + > + <span class="text-xs text-secondary shrink-0">{config.asset.kind}://</span> + {#if config.asset.kind === 'datatable'} + <DatatablePicker + bind:value={config.asset.store} + class="shrink-0" + selectInputClass="!border-none" + placeholder="data table" + useContentEditable + RightIcon={ChevronDown} + /> + {:else} + <DucklakePicker + bind:value={config.asset.store} + class="shrink-0" + selectInputClass="!border-none" + placeholder="catalog" + useContentEditable + RightIcon={ChevronDown} + /> + {/if} + <span class="text-sm text-secondary">/</span> + <div data-autofocus class="grow flex"> + <TextInput + bind:value={config.asset.table} + class="!border-none grow" + inputProps={{ + placeholder: 'table', + oninput: () => (config.tableEdited = true) + }} + /> + </div> + </div> + </Label> + <span class="text-2xs text-hint"> + {config.asset.kind === 'datatable' ? 'Data table' : 'DuckLake catalog'}, then the table + name + </span> + {/if} + </div> + <div class="flex px-4 py-3 border-t"> + <div class="ml-auto"> + {@render confirmButton(close)} + </div> + </div> </div> {/snippet} diff --git a/frontend/src/lib/components/assets/AssetGraph/PipelineNodeCard.svelte b/frontend/src/lib/components/assets/AssetGraph/PipelineNodeCard.svelte new file mode 100644 index 0000000000..e78058f905 --- /dev/null +++ b/frontend/src/lib/components/assets/AssetGraph/PipelineNodeCard.svelte @@ -0,0 +1,174 @@ +<!-- +@component +The body every pipeline graph node shares: icon, a kind line ("Script · draft", "Data table"), +a title, and trailing chips. Node components add only what is theirs — the icon, the chips, +and the controls hung around the card. +--> +<script lang="ts"> + import { NODE } from '$lib/components/graph/util' + import { + PIPELINE_NODE_EXTRA_ROW, + PIPELINE_NODE_HEADER, + PIPELINE_NODE_HEADER_CARD_PAD, + PIPELINE_NODE_HEIGHT + } from './assetGraphLayout' + import { twMerge } from 'tailwind-merge' + import type { Snippet } from 'svelte' + + interface Props { + icon: Snippet + kindLabel: string + title: string + /** Hover text; the path, when the title is a summary. */ + tooltip?: string + /** Scripts sit on the main surface, assets and triggers a step down; in the + * assets-only view, which has no scripts, assets take the main surface. */ + surface?: 'primary' | 'secondary' + selected?: boolean + /** Not deployed yet: dashed edge. */ + draft?: boolean + /** Feedback states, which recolor the whole card. `error` is a misconfigured + * node, styled like a failed flow step. */ + tone?: 'danger' | 'error' | 'success' | 'running' + /** Makes the whole card a button. */ + onclick?: (e: MouseEvent) => void + /** Between the icon and the text: a live status the eye should find first. */ + leading?: Snippet + trailing?: Snippet + /** Defaults to `NODE.width`. */ + width?: number + /** A line under the title, in the text column. */ + subtitle?: Snippet + /** A tab on the card's top edge. Only on a card without `onclick`, since it + * may hold buttons of its own. */ + header?: Snippet + /** The header's script is selected: its edge takes the selected colour. */ + headerSelected?: boolean + /** The header's script has an error: its edge goes red. */ + headerTone?: 'error' + } + + let { + icon, + kindLabel, + title, + tooltip, + surface = 'secondary', + selected = false, + draft = false, + tone, + onclick, + leading, + trailing, + subtitle, + header, + headerSelected = false, + headerTone, + width = NODE.width + }: Props = $props() + + const cardClass = $derived( + twMerge( + 'flex items-center w-full text-left font-normal rounded-md drop-shadow-sm overflow-hidden border transition-colors', + surface === 'primary' ? 'bg-surface' : 'bg-surface-secondary', + 'border-gray-400 dark:border-gray-600 hover:border-gray-500 dark:hover:border-gray-500', + // Like a flow step: a card with a background needs no edge, only its shadow, + // until one of the states below draws one. + surface === 'primary' && + !draft && + !selected && + !tone && + 'border-transparent dark:border-transparent hover:border-transparent dark:hover:border-transparent', + draft && 'border-dashed border-gray-400 dark:border-gray-500', + // Like a selected flow step: the fill and the edge colour change, the edge's + // width and dashes stay. + // Each dark: variant too: the base edge sets its own dark colour, which a plain + // border class does not override. + selected && + 'bg-surface-accent-selected border-border-selected dark:border-border-selected hover:border-border-selected dark:hover:border-border-selected', + tone === 'danger' && + 'bg-red-50 dark:bg-red-900/30 border-dashed border-red-400 dark:border-red-500 hover:bg-red-100 dark:hover:bg-red-900/40', + tone === 'error' && + (selected + ? 'bg-red-200 dark:bg-red-600 border-red-500 dark:border-red-500 hover:border-red-500 dark:hover:border-red-500' + : 'bg-red-100 dark:bg-red-700 border-transparent dark:border-transparent hover:border-transparent dark:hover:border-transparent'), + tone === 'success' && + 'bg-green-50 dark:bg-green-900/30 border-green-500 dark:border-green-600', + tone === 'running' && + 'bg-amber-50 dark:bg-amber-900/30 border-amber-400 dark:border-amber-600 animate-pulse' + ) + ) + const minHeight = $derived(PIPELINE_NODE_HEIGHT + (subtitle ? PIPELINE_NODE_EXTRA_ROW : 0)) + const toneText = $derived( + tone === 'danger' + ? 'text-red-700 dark:text-red-400' + : tone === 'error' + ? 'text-red-700 dark:text-red-200' + : tone === 'success' + ? 'text-green-700 dark:text-green-400' + : undefined + ) +</script> + +{#snippet body()} + <span class="shrink-0 ml-3 mr-2.5 flex items-center">{@render icon()}</span> + {@render leading?.()} + <span class="flex flex-col min-w-0 flex-1 pr-1 py-1 leading-tight"> + <span class={twMerge('text-2xs truncate text-secondary', toneText)}>{kindLabel}</span> + <span class={twMerge('text-xs truncate text-emphasis', selected && 'text-accent', toneText)} + >{title}</span + > + {#if subtitle} + <span class="flex items-center min-w-0 mt-1">{@render subtitle()}</span> + {/if} + </span> + {#if trailing} + <span class="flex items-center shrink-0 pr-2">{@render trailing()}</span> + {/if} +{/snippet} + +{#if onclick} + <button + type="button" + {onclick} + class={cardClass} + style="width: {width}px; min-height: {minHeight}px;" + title={tooltip} + > + {@render body()} + </button> +{:else if header} + <!-- The header is a tab on the card's top edge, inset from its sides. --> + <div class="flex flex-col" style="width: {width}px;"> + <div + class={twMerge( + 'mx-2 flex items-stretch min-w-0 rounded-t-md overflow-hidden bg-surface border border-b-0 border-gray-200 dark:border-gray-700', + // Like an errored card: red, and a stronger red when selected. + headerTone === 'error' + ? headerSelected + ? 'border-red-500 dark:border-red-500' + : 'border-red-300 dark:border-red-600' + : headerSelected && 'border-border-selected dark:border-border-selected' + )} + style="height: {PIPELINE_NODE_HEADER}px;" + > + {@render header()} + </div> + <div + class={twMerge(cardClass, !selected && !tone && 'bg-surface-tertiary')} + style="min-height: {minHeight + PIPELINE_NODE_HEADER_CARD_PAD}px; padding-block: {PIPELINE_NODE_HEADER_CARD_PAD / + 2}px;" + title={tooltip} + > + {@render body()} + </div> + </div> +{:else} + <div + class={cardClass} + style="width: {width}px; min-height: {minHeight}px;" + title={tooltip} + > + {@render body()} + </div> +{/if} diff --git a/frontend/src/lib/components/assets/AssetGraph/PipelineScriptView.svelte b/frontend/src/lib/components/assets/AssetGraph/PipelineScriptView.svelte index 2450595b6d..8a060e0b2c 100644 --- a/frontend/src/lib/components/assets/AssetGraph/PipelineScriptView.svelte +++ b/frontend/src/lib/components/assets/AssetGraph/PipelineScriptView.svelte @@ -1,6 +1,6 @@ <script lang="ts"> import type { AssetKind, Script } from '$lib/gen' - import { CalendarClock, Loader2, Play, Upload, Zap } from 'lucide-svelte' + import { CalendarClock, Code2, Loader2, Play, Upload, Zap } from 'lucide-svelte' import Button from '$lib/components/common/button/Button.svelte' import HighlightCode from '$lib/components/HighlightCode.svelte' import PipelineRunForm from './PipelineRunForm.svelte' @@ -44,6 +44,12 @@ // "green / ready" state and seeds the whole-pipeline run. `isValid` is the // full-schema validity (all required fields, not just the S3 file). onArgsChange?: (path: string, args: Record<string, any>, isValid: boolean) => void + // Just the run form and the runs, without the source: what a data-upload + // click asks for. `onShowScript` switches to the script itself. + inputsOnly?: boolean + onShowScript?: () => void + // `onRun` previews a draft's own content, so a draft can run too. + runsDrafts?: boolean } let { @@ -57,8 +63,12 @@ runsPendingJobId, onRunCompleted, initialArgs, - onArgsChange + onArgsChange, + inputsOnly = false, + onShowScript, + runsDrafts = false }: Props = $props() + let runBlockedByDraft = $derived(isDraft && !runsDrafts) // Seed once from the persisted args (see initialArgs). Cloned so the run // form mutates its own copy, not the page's stored snapshot. @@ -139,7 +149,7 @@ </script> <div class="flex flex-col h-full"> - {#if isDraft} + {#if runBlockedByDraft} <div class="shrink-0 flex items-center gap-2 px-3 py-1.5 text-2xs bg-amber-50 dark:bg-amber-900/30 border-b border-amber-200 dark:border-amber-900/60 text-amber-700 dark:text-amber-400" > @@ -168,13 +178,24 @@ {/if} </span> <div class="flex items-center gap-1.5"> + {#if inputsOnly && onShowScript} + <Button + variant="subtle" + unifiedSize="sm" + startIcon={{ icon: Code2 }} + onclick={onShowScript} + title="Show the script instead of its inputs" + > + Open script + </Button> + {/if} {#if hasCascade} <Button variant="accent-secondary" unifiedSize="sm" startIcon={{ icon: running ? Loader2 : Zap }} onclick={() => run(true)} - disabled={isDraft || running || !runValid} + disabled={runBlockedByDraft || running || !runValid} title={`Run this script with these inputs, then run its ${downstreamCount} downstream pipeline script${downstreamCount === 1 ? '' : 's'} in order`} > Run + downstream @@ -185,8 +206,8 @@ unifiedSize="sm" startIcon={{ icon: running ? Loader2 : Play }} onclick={() => run(false)} - disabled={isDraft || running || !runValid || !onRun} - title={isDraft + disabled={runBlockedByDraft || running || !runValid || !onRun} + title={runBlockedByDraft ? 'Deploy this draft to run it for real' : hasCascade ? 'Run just this step — downstream scripts are not triggered' @@ -210,9 +231,11 @@ {/key} {/if} </div> - <div class="flex-1 min-h-0 overflow-auto text-xs p-3"> - <HighlightCode code={script.content ?? ''} language={script.language} /> - </div> + {#if !inputsOnly} + <div class="flex-1 min-h-0 overflow-auto text-xs p-3"> + <HighlightCode code={script.content ?? ''} language={script.language} /> + </div> + {/if} </div> </Pane> <Pane size={45} minSize={20}> diff --git a/frontend/src/lib/components/assets/AssetGraph/PipelineSetupSignpost.svelte b/frontend/src/lib/components/assets/AssetGraph/PipelineSetupSignpost.svelte index 751ecbbdc8..c79e638265 100644 --- a/frontend/src/lib/components/assets/AssetGraph/PipelineSetupSignpost.svelte +++ b/frontend/src/lib/components/assets/AssetGraph/PipelineSetupSignpost.svelte @@ -1,8 +1,9 @@ <script lang="ts"> import { resource } from 'runed' import { WorkspaceService } from '$lib/gen' - import { base } from '$lib/base' import { CircleCheck, CircleAlert, Database, HardDrive, ArrowRight } from 'lucide-svelte' + import Alert from '$lib/components/common/alert/Alert.svelte' + import { Button } from '$lib/components/common' interface Props { workspace: string @@ -57,7 +58,7 @@ title: 'Workspace object storage', description: 'Materialized partitions and DuckLake data files are written to S3 / object storage.', - href: `${base}/workspace_settings?tab=windmill_lfs`, + href: '/workspace_settings?tab=windmill_lfs', cta: 'Configure object storage' }, { @@ -66,55 +67,50 @@ title: 'A DuckLake catalog', description: 'DuckLake is the table format pipelines materialize into — add at least one catalog.', - href: `${base}/workspace_settings?tab=ducklake`, + href: '/workspace_settings?tab=ducklake', cta: 'Configure DuckLake' } ]) </script> {#if show} - <div - class="flex flex-col gap-3 rounded-lg border border-amber-300 dark:border-amber-900/60 bg-amber-50 dark:bg-amber-950/30 p-4" - > - <div class="flex items-start gap-2"> - <CircleAlert size={18} class="text-amber-600 dark:text-amber-400 mt-0.5 shrink-0" /> - <div class="flex flex-col gap-0.5"> - <h3 class="text-sm font-semibold text-emphasis">Finish setting up pipelines</h3> - <p class="text-xs text-tertiary"> - Pipelines materialize data into DuckLake tables backed by object storage. Configure the - following before your first pipeline can run. - </p> - </div> + <Alert type="warning" title="Finish setting up pipelines" hideIcon> + <div class="flex flex-col gap-3"> + <p> + Pipelines materialize data into DuckLake tables backed by object storage. Configure the + following before your first pipeline can run. + </p> + <ul class="flex flex-col gap-2"> + {#each steps as step (step.title)} + {@const Icon = step.icon} + <li class="flex items-center gap-3 rounded-md border bg-surface-tertiary px-3 py-2"> + {#if step.done === true} + <CircleCheck size={16} class="text-green-600 dark:text-green-400 shrink-0" /> + {:else if step.done === false} + <CircleAlert size={16} class="text-yellow-600 dark:text-yellow-400 shrink-0" /> + {:else} + <Icon size={16} class="text-secondary shrink-0" /> + {/if} + <div class="flex flex-col min-w-0 flex-1"> + <span class="text-xs font-semibold text-emphasis">{step.title}</span> + <span class="text-2xs text-secondary">{step.description}</span> + </div> + {#if step.done !== true} + <Button + variant="default" + unifiedSize="sm" + href={step.href} + endIcon={{ icon: ArrowRight }} + wrapperClasses="shrink-0" + > + {step.cta} + </Button> + {:else} + <span class="shrink-0 text-2xs text-green-700 dark:text-green-400">Configured</span> + {/if} + </li> + {/each} + </ul> </div> - - <ul class="flex flex-col gap-2"> - {#each steps as step (step.title)} - {@const Icon = step.icon} - <li class="flex items-center gap-3 rounded-md border bg-surface px-3 py-2"> - {#if step.done === true} - <CircleCheck size={16} class="text-green-600 dark:text-green-400 shrink-0" /> - {:else if step.done === false} - <CircleAlert size={16} class="text-amber-600 dark:text-amber-400 shrink-0" /> - {:else} - <Icon size={16} class="text-tertiary shrink-0" /> - {/if} - <div class="flex flex-col min-w-0 flex-1"> - <span class="text-xs font-semibold text-primary">{step.title}</span> - <span class="text-2xs text-tertiary">{step.description}</span> - </div> - {#if step.done !== true} - <a - href={step.href} - class="shrink-0 inline-flex items-center gap-1 text-xs text-blue-500 hover:underline whitespace-nowrap" - > - {step.cta} - <ArrowRight size={12} /> - </a> - {:else} - <span class="shrink-0 text-2xs text-green-700 dark:text-green-400">Configured</span> - {/if} - </li> - {/each} - </ul> - </div> + </Alert> {/if} diff --git a/frontend/src/lib/components/assets/AssetGraph/PipelineTriggerEditors.svelte b/frontend/src/lib/components/assets/AssetGraph/PipelineTriggerEditors.svelte index 4f97039a1c..d8d19845fa 100644 --- a/frontend/src/lib/components/assets/AssetGraph/PipelineTriggerEditors.svelte +++ b/frontend/src/lib/components/assets/AssetGraph/PipelineTriggerEditors.svelte @@ -1,18 +1,10 @@ <script lang="ts"> import { sendUserToast } from '$lib/utils' + import { workspaceStore } from '$lib/stores' import ConfirmationModal from '$lib/components/common/confirmationModal/ConfirmationModal.svelte' - import type { NativeTriggerKind } from './types' - import { - EmailTriggerService, - GcpTriggerService, - KafkaTriggerService, - MqttTriggerService, - AmqpTriggerService, - NatsTriggerService, - PostgresTriggerService, - ScheduleService, - SqsTriggerService - } from '$lib/gen' + import type { NativeTriggerKind, PipelineTriggerDraftKind } from './types' + import type { Schedule } from '$lib/gen' + import { deleteTriggerRow } from './pipelineTriggerDraftDeploy' import KafkaTriggerEditor from '$lib/components/triggers/kafka/KafkaTriggerEditor.svelte' import MqttTriggerEditor from '$lib/components/triggers/mqtt/MqttTriggerEditor.svelte' import AmqpTriggerEditor from '$lib/components/triggers/amqp/AmqpTriggerEditor.svelte' @@ -22,6 +14,10 @@ import GcpTriggerEditor from '$lib/components/triggers/gcp/GcpTriggerEditor.svelte' import EmailTriggerEditor from '$lib/components/triggers/email/EmailTriggerEditor.svelte' import ScheduleEditor from '$lib/components/triggers/schedules/ScheduleEditor.svelte' + import { + loadDefaultScheduleAdvanced, + scheduleAdvancedCfg + } from '$lib/components/triggers/schedules/ScheduleAdvancedOptions.svelte' import WebhookEditor from '$lib/components/triggers/webhook/WebhookEditor.svelte' import { setOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' @@ -110,6 +106,56 @@ } } + /** The kind's full editor over a pipeline-local draft; Save hands the config back, + * and the drawer stays open when `onSave` refuses it. + * `saved` is the draft being edited (absent for a new one), applied over `defaults`. */ + export function openTriggerDraft( + kind: PipelineTriggerDraftKind, + scriptPath: string, + defaults: Record<string, any>, + saved: Record<string, any> | undefined, + onSave: (cfg: Record<string, any>) => boolean + ) { + switch (kind) { + case 'schedule': { + // A new draft starts from the workspace's default handlers, like a new + // schedule does; the drawer only applies them when it opens without one. + const open = (advanced: Record<string, any>) => + scheduleEditor?.openDraft( + { + is_flow: false, + args: {}, + ...advanced, + ...defaults, + ...saved, + script_path: scriptPath + } as Schedule, + onSave + ) + if (saved || !$workspaceStore) return open({}) + return loadDefaultScheduleAdvanced($workspaceStore) + .then((a) => open(scheduleAdvancedCfg(a))) + .catch(() => open({})) + } + case 'kafka': + return kafkaEditor?.openDraft(scriptPath, defaults, saved, onSave) + case 'mqtt': + return mqttEditor?.openDraft(scriptPath, defaults, saved, onSave) + case 'amqp': + return amqpEditor?.openDraft(scriptPath, defaults, saved, onSave) + case 'nats': + return natsEditor?.openDraft(scriptPath, defaults, saved, onSave) + case 'postgres': + return postgresEditor?.openDraft(scriptPath, defaults, saved, onSave) + case 'sqs': + return sqsEditor?.openDraft(scriptPath, defaults, saved, onSave) + case 'gcp': + return gcpEditor?.openDraft(scriptPath, defaults, saved, onSave) + case 'email': + return emailEditor?.openDraft(scriptPath, defaults, saved, onSave) + } + } + // Open the webhook drawer (endpoint URLs + token flow). Caller owns the // draft guard. export function openWebhook(scriptPath: string) { @@ -133,37 +179,7 @@ const { kind, path: triggerPath } = triggerDeleteTarget triggerDeleteLoading = true try { - switch (kind) { - case 'schedule': - await ScheduleService.deleteSchedule({ workspace, path: triggerPath }) - break - case 'kafka': - await KafkaTriggerService.deleteKafkaTrigger({ workspace, path: triggerPath }) - break - case 'mqtt': - await MqttTriggerService.deleteMqttTrigger({ workspace, path: triggerPath }) - break - case 'amqp': - await AmqpTriggerService.deleteAmqpTrigger({ workspace, path: triggerPath }) - break - case 'nats': - await NatsTriggerService.deleteNatsTrigger({ workspace, path: triggerPath }) - break - case 'postgres': - await PostgresTriggerService.deletePostgresTrigger({ workspace, path: triggerPath }) - break - case 'sqs': - await SqsTriggerService.deleteSqsTrigger({ workspace, path: triggerPath }) - break - case 'gcp': - await GcpTriggerService.deleteGcpTrigger({ workspace, path: triggerPath }) - break - case 'email': - await EmailTriggerService.deleteEmailTrigger({ workspace, path: triggerPath }) - break - default: - return - } + if (!(await deleteTriggerRow(kind, triggerPath, workspace))) return sendUserToast(`Deleted ${kind} trigger "${triggerPath}"`) triggerDeleteTarget = undefined onUpdate() diff --git a/frontend/src/lib/components/assets/AssetGraph/RunStateChip.svelte b/frontend/src/lib/components/assets/AssetGraph/RunStateChip.svelte new file mode 100644 index 0000000000..21edf1df52 --- /dev/null +++ b/frontend/src/lib/components/assets/AssetGraph/RunStateChip.svelte @@ -0,0 +1,37 @@ +<script lang="ts"> + import { twMerge } from 'tailwind-merge' + import { CheckCircle2, Loader2, XCircle } from 'lucide-svelte' + import type { RunnableRunState } from './activeRunnables.svelte' + + let { runState: rs, class: className }: { runState: RunnableRunState; class?: string } = $props() +</script> + +<div + class={twMerge( + 'shrink-0 flex items-center gap-0.5 px-1 py-0.5 rounded-sm border', + rs.status === 'running' + ? 'bg-blue-100 dark:bg-blue-900/40 text-blue-700 dark:text-blue-300 border-blue-300 dark:border-blue-700' + : rs.status === 'success' + ? 'bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300 border-emerald-300 dark:border-emerald-700' + : 'bg-red-100 dark:bg-red-900/40 text-red-700 dark:text-red-300 border-red-300 dark:border-red-700', + className + )} + title={`${ + rs.status === 'running' + ? 'Running now' + : rs.status === 'success' + ? 'Last run succeeded' + : 'Last run failed' + }${rs.runs > 0 ? ` — ran ${rs.runs}× this session` : ''}`} +> + {#if rs.status === 'running'} + <Loader2 size={10} class="animate-spin" /> + {:else if rs.status === 'success'} + <CheckCircle2 size={10} /> + {:else} + <XCircle size={10} /> + {/if} + {#if rs.runs > 0} + <span class="text-3xs leading-none tabular-nums">×{rs.runs}</span> + {/if} +</div> diff --git a/frontend/src/lib/components/assets/AssetGraph/RunnableNode.svelte b/frontend/src/lib/components/assets/AssetGraph/RunnableNode.svelte index c4cb5ca998..5d28067982 100644 --- a/frontend/src/lib/components/assets/AssetGraph/RunnableNode.svelte +++ b/frontend/src/lib/components/assets/AssetGraph/RunnableNode.svelte @@ -1,10 +1,8 @@ <script lang="ts"> import { Handle, Position } from '@xyflow/svelte' import { - CheckCircle2, ChevronDown, Code2, - EllipsisVertical, GitBranch, Layers, Loader2, @@ -15,17 +13,20 @@ Target, Timer, Trash2, - XCircle, Zap } from 'lucide-svelte' import DbtIcon from '$lib/components/icons/DbtIcon.svelte' import { twMerge } from 'tailwind-merge' - import { preventDefault, stopPropagation } from 'svelte/legacy' import type { GraphUsageKind } from './types' import type { RunnableRunState } from './activeRunnables.svelte' import { parseDurationSecs } from './parsePipelineAnnotations' - import { NODE } from '$lib/components/graph/util' - import DropdownV2 from '$lib/components/DropdownV2.svelte' + import LanguageIcon from '$lib/components/common/languageIcons/LanguageIcon.svelte' + import PipelineNodeCard from './PipelineNodeCard.svelte' + import NodeActionsMenu from './NodeActionsMenu.svelte' + import NodeFixButton, { type NodeFix } from './NodeFixButton.svelte' + import NodeOnDot from './NodeOnDot.svelte' + import RunStateChip from './RunStateChip.svelte' + import type { ScriptLang } from '$lib/gen' import Popover from '$lib/components/meltComponents/Popover.svelte' import type { Item } from '$lib/utils' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' @@ -35,8 +36,16 @@ interface Props { data: { + /** What is wrong with the node, and how to fix it: shows the Fix pill. */ + fix?: NodeFix + /** Starts dragging the top dot onto an asset to subscribe the script to it. */ + onStartOnDrag?: (e: PointerEvent) => void runnable_kind: GraphUsageKind path: string + summary?: string + language?: ScriptLang + // Why the script is misconfigured, when it is: renders it red. + error?: string in_pipeline?: boolean partition_kind?: 'daily' | 'hourly' | 'weekly' | 'monthly' | 'dynamic' freshness?: string @@ -101,10 +110,11 @@ } let { data, selected = false }: Props = $props() - // The icon alone conveys "script" vs "flow"; the uppercase kind label was - // visually noisy and redundant. Tooltip on hover surfaces the path in - // full when truncated. let Icon = $derived(data.runnable_kind === 'flow' ? GitBranch : Code2) + let kindLabel = $derived( + data.runnable_kind === 'flow' ? 'Flow' : data.dbt ? 'dbt project' : 'Script' + ) + // The title shows the summary when there is one, so the tooltip keeps the path. let nodeTooltip = $derived( data.unsaved ? `${data.path} (unsaved draft)` @@ -114,7 +124,6 @@ ) let hover = $state(false) - let menuOpen = $state(false) let running = $state(false) // Amber "computing now" surface, gated so only the replay player lights it up. @@ -214,131 +223,106 @@ <!-- Mirrors the flow editor's step styling (getNodeColorClasses): muted surface-tertiary fill with a quiet gray border, accent only for the - selected state, dashes for unsaved drafts. The 2px dashed stroke is - necessary for the dash gaps to be readable; 1px disappears into the - fill. + selected state, dashes for unsaved drafts — 1px, like the trigger + nodes' dashed outline, so every draft node reads the same. --> - <div - class={twMerge( - 'flex items-center rounded-md drop-shadow-sm overflow-hidden border transition-colors', - 'bg-surface border-gray-400 dark:border-gray-600 hover:border-gray-500 dark:hover:border-gray-500', - selected && 'bg-surface-accent-selected border-border-selected', - data.unsaved && 'border-2 border-dashed border-gray-400 dark:border-gray-500', - computingNow && - 'bg-amber-50 dark:bg-amber-900/30 border-amber-400 dark:border-amber-600 animate-pulse' - )} - style="width: {NODE.width}px; min-height: {NODE.height}px;" - title={nodeTooltip} - > - <Icon size={14} class={`shrink-0 ml-2 mr-2 ${selected ? 'text-accent' : 'text-secondary'}`} /> - <span class="flex-1 min-w-0 pr-1 py-0.5 text-2xs font-mono text-emphasis truncate"> - {data.path} - </span> - <!-- Annotation chips share one neutral treatment — the icon carries - the meaning (colors are reserved for feedback, per the brand - guidelines). Only the freshness chip (when it has a verdict) - and the run-state chip below use semantic colors. --> - {#if data.partition_kind} - <div - class="shrink-0 flex items-center gap-0.5 px-1 py-0.5 mr-1 rounded-sm bg-surface-secondary text-secondary" - title={`// partitioned ${data.partition_kind}`} - > - <Layers size={10} /> - <span class="text-3xs leading-none">{data.partition_kind}</span> - </div> - {/if} - <!-- Freshness is the one annotation chip that carries feedback (a - fresh/stale verdict against real run history), so like the - run-state chip it uses semantic colors: emerald = within window, - amber = stale. Neutral when there's no verdict (drafts, bad - window value). --> - {#if data.freshness} - <div - class={twMerge( - 'shrink-0 flex items-center gap-0.5 px-1 py-0.5 mr-1 rounded-sm', - freshnessState === 'fresh' - ? 'bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300' - : freshnessState === 'stale' - ? 'bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300' - : 'bg-surface-secondary text-secondary' - )} - title={freshnessTooltip} - > - <Timer size={10} /> - <span class="text-3xs leading-none">{data.freshness}</span> - </div> - {/if} - {#if data.tag} - <div - class="shrink-0 flex items-center gap-0.5 px-1 py-0.5 mr-1 rounded-sm bg-surface-secondary text-secondary" - title={`// tag ${data.tag}`} - > - <Tag size={10} /> - <span class="text-3xs leading-none">{data.tag}</span> - </div> - {/if} - {#if data.retry} - {@const r = data.retry} - <div - class="shrink-0 flex items-center gap-0.5 px-1 py-0.5 mr-1 rounded-sm bg-surface-secondary text-secondary" - title={`// retry ${r.count}${r.delay ? ` ${r.delay}` : ''}`} - > - <RotateCw size={10} /> - <span class="text-3xs leading-none">×{r.count}</span> - </div> - {/if} - {#if data.macros && data.macros.length > 0} - <div - class="shrink-0 flex items-center gap-0.5 px-1 py-0.5 mr-1 rounded-sm bg-surface-secondary text-secondary" - title={`// macros — defines ${data.macros.length} macro${data.macros.length > 1 ? 's' : ''}:\n${data.macros - .map((m) => `• ${m.name}(${m.params})${m.is_table ? ' → table' : ''}`) - .join('\n')}`} - > - <SquareFunction size={10} /> - <span class="text-3xs leading-none">×{data.macros.length}</span> - </div> - {/if} - {#if data.dbt} - <div - class="shrink-0 flex items-center gap-0.5 px-1 py-0.5 mr-1 rounded-sm bg-orange-100 dark:bg-orange-900/40 text-orange-700 dark:text-orange-300" - title={`dbt project — materializes ${data.dbt.model_count} model${data.dbt.model_count === 1 ? '' : 's'}`} - > - <DbtIcon width={10} height={10} /> - <span class="text-3xs leading-none">×{data.dbt.model_count}</span> - </div> - {/if} - {#if data.runState} - {@const rs = data.runState} - <div - class={twMerge( - 'shrink-0 flex items-center gap-0.5 px-1 py-0.5 mr-1 rounded-sm', - rs.status === 'running' - ? 'bg-blue-100 dark:bg-blue-900/40 text-blue-700 dark:text-blue-300' - : rs.status === 'success' - ? 'bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300' - : 'bg-red-100 dark:bg-red-900/40 text-red-700 dark:text-red-300' - )} - title={`${ - rs.status === 'running' - ? 'Running now' - : rs.status === 'success' - ? 'Last run succeeded' - : 'Last run failed' - }${rs.runs > 0 ? ` — ran ${rs.runs}× this session` : ''}`} - > - {#if rs.status === 'running'} - <Loader2 size={10} class="animate-spin" /> - {:else if rs.status === 'success'} - <CheckCircle2 size={10} /> + <NodeActionsMenu items={menuItems} {hover}> + <PipelineNodeCard + surface="primary" + kindLabel="{kindLabel}{data.unsaved ? ' · draft' : ''}" + title={data.summary || data.path} + tooltip={data.error ? `${data.path}: ${data.error}` : nodeTooltip} + {selected} + draft={data.unsaved} + tone={computingNow ? 'running' : data.error ? 'error' : undefined} + > + {#snippet icon()} + {#if data.language && data.runnable_kind === 'script'} + <LanguageIcon lang={data.language} width={14} height={14} /> {:else} - <XCircle size={10} /> + <Icon size={14} class={selected ? 'text-accent' : 'text-secondary'} /> {/if} - {#if rs.runs > 0} - <span class="text-3xs leading-none tabular-nums">×{rs.runs}</span> + {/snippet} + {#snippet trailing()} + <!-- Annotation chips share one neutral treatment — the icon carries + the meaning (colors are reserved for feedback, per the brand + guidelines). Only the freshness chip (when it has a verdict) + and the run-state chip below use semantic colors. --> + {#if data.partition_kind} + <div + class="shrink-0 flex items-center gap-0.5 px-1 py-0.5 mr-1 rounded-sm bg-surface-secondary text-secondary" + title={`// partitioned ${data.partition_kind}`} + > + <Layers size={10} /> + <span class="text-3xs leading-none">{data.partition_kind}</span> + </div> {/if} - </div> - {/if} - </div> + <!-- Freshness is the one annotation chip that carries feedback (a + fresh/stale verdict against real run history), so like the + run-state chip it uses semantic colors: emerald = within window, + amber = stale. Neutral when there's no verdict (drafts, bad + window value). --> + {#if data.freshness} + <div + class={twMerge( + 'shrink-0 flex items-center gap-0.5 px-1 py-0.5 mr-1 rounded-sm', + freshnessState === 'fresh' + ? 'bg-emerald-100 dark:bg-emerald-900/40 text-emerald-700 dark:text-emerald-300' + : freshnessState === 'stale' + ? 'bg-amber-100 dark:bg-amber-900/40 text-amber-700 dark:text-amber-300' + : 'bg-surface-secondary text-secondary' + )} + title={freshnessTooltip} + > + <Timer size={10} /> + <span class="text-3xs leading-none">{data.freshness}</span> + </div> + {/if} + {#if data.tag} + <div + class="shrink-0 flex items-center gap-0.5 px-1 py-0.5 mr-1 rounded-sm bg-surface-secondary text-secondary" + title={`// tag ${data.tag}`} + > + <Tag size={10} /> + <span class="text-3xs leading-none">{data.tag}</span> + </div> + {/if} + {#if data.retry} + {@const r = data.retry} + <div + class="shrink-0 flex items-center gap-0.5 px-1 py-0.5 mr-1 rounded-sm bg-surface-secondary text-secondary" + title={`// retry ${r.count}${r.delay ? ` ${r.delay}` : ''}`} + > + <RotateCw size={10} /> + <span class="text-3xs leading-none">×{r.count}</span> + </div> + {/if} + {#if data.macros && data.macros.length > 0} + <div + class="shrink-0 flex items-center gap-0.5 px-1 py-0.5 mr-1 rounded-sm bg-surface-secondary text-secondary" + title={`// macros — defines ${data.macros.length} macro${data.macros.length > 1 ? 's' : ''}:\n${data.macros + .map((m) => `• ${m.name}(${m.params})${m.is_table ? ' → table' : ''}`) + .join('\n')}`} + > + <SquareFunction size={10} /> + <span class="text-3xs leading-none">×{data.macros.length}</span> + </div> + {/if} + {#if data.dbt} + <div + class="shrink-0 flex items-center gap-0.5 px-1 py-0.5 mr-1 rounded-sm bg-orange-100 dark:bg-orange-900/40 text-orange-700 dark:text-orange-300" + title={`dbt project — materializes ${data.dbt.model_count} model${data.dbt.model_count === 1 ? '' : 's'}`} + > + <DbtIcon width={10} height={10} /> + <span class="text-3xs leading-none">×{data.dbt.model_count}</span> + </div> + {/if} + {#if data.runState} + <RunStateChip runState={data.runState} class="mr-1" /> + {/if} + {/snippet} + </PipelineNodeCard> + </NodeActionsMenu> {#if showRun} <!-- Run button revealed on hover/select. Matches the placement, size, and behaviour of AssetNode's run button so both nodes feel @@ -463,38 +447,12 @@ {/if} </div> {/if} - - {#if menuItems.length > 0} - <!-- - Hover-revealed action menu, top-right of the node. Mirrors the - FlowModuleSchemaItem pattern: position the trigger button just - outside the node frame, only render it on hover (or while the - menu is open) so the canvas isn't visually cluttered when idle. - The pointerdown stop+preventDefault keeps xyflow from selecting - the node when the user is reaching for the menu. - --> - <div class="absolute -top-2 -right-2 h-7 p-1 min-w-7" style="will-change: transform;"> - <DropdownV2 - items={menuItems} - placement="bottom-end" - bind:open={menuOpen} - fixedHeight={false} - usePointerDownOutside - > - {#snippet buttonReplacement()} - <button - class={twMerge( - 'center-center p-1 text-secondary shadow-sm bg-surface duration-0 hover:bg-surface-tertiary', - hover || menuOpen ? 'block' : '!hidden', - 'shadow-md rounded-md' - )} - onpointerdown={stopPropagation(preventDefault(() => {}))} - title="Actions" - > - <EllipsisVertical size={12} /> - </button> - {/snippet} - </DropdownV2> + {#if data.onStartOnDrag} + <NodeOnDot onStart={data.onStartOnDrag} visible={hover} /> + {/if} + {#if data.fix} + <div class="absolute left-1/2 -bottom-3 -translate-x-1/2 z-10"> + <NodeFixButton fix={data.fix} /> </div> {/if} </div> diff --git a/frontend/src/lib/components/assets/AssetGraph/TriggerNode.svelte b/frontend/src/lib/components/assets/AssetGraph/TriggerNode.svelte index 0e279112cd..f678b3d272 100644 --- a/frontend/src/lib/components/assets/AssetGraph/TriggerNode.svelte +++ b/frontend/src/lib/components/assets/AssetGraph/TriggerNode.svelte @@ -24,46 +24,36 @@ type Presentation = { icon: ComponentType label: string - // Tailwind class fragments for bg + border + text accent. - bg: string - border: string - borderUnsaved: string iconText: string } - // One muted treatment for every source kind — colors are meaningful, not + // One muted icon color for every source kind — colors are meaningful, not // decorative (brand guidelines), so the kind is carried by the icon and - // label while bg/border stay on the surface/gray scale like the flow - // editor's nodes. Red stays reserved for the missing-trigger state. - const MUTED = { - bg: 'bg-surface-secondary', - border: 'outline-gray-400 dark:outline-gray-600', - borderUnsaved: 'outline-dashed outline-gray-400 dark:outline-gray-500', - iconText: 'text-secondary' - } + // label. Red stays reserved for the missing-trigger state. + const MUTED = { iconText: 'text-secondary' } export const TRIGGER_NODE_STYLE: Record<TriggerNodeKind, Presentation> = { - schedule: { icon: Clock, label: 'schedule', ...MUTED }, - webhook: { icon: Webhook, label: 'webhook', ...MUTED }, - email: { icon: Mail, label: 'email', ...MUTED }, - kafka: { icon: Zap, label: 'kafka', ...MUTED }, - mqtt: { icon: Radio, label: 'mqtt', ...MUTED }, - amqp: { icon: Radio, label: 'amqp', ...MUTED }, - nats: { icon: MessageSquare, label: 'nats', ...MUTED }, - postgres: { icon: Database, label: 'postgres', ...MUTED }, - sqs: { icon: Send, label: 'sqs', ...MUTED }, - gcp: { icon: CloudCog, label: 'gcp', ...MUTED }, - data_upload: { icon: Upload, label: 'data upload', ...MUTED } + schedule: { icon: Clock, label: 'Schedule', ...MUTED }, + webhook: { icon: Webhook, label: 'Webhook', ...MUTED }, + email: { icon: Mail, label: 'Email', ...MUTED }, + kafka: { icon: Zap, label: 'Kafka', ...MUTED }, + mqtt: { icon: Radio, label: 'MQTT', ...MUTED }, + amqp: { icon: Radio, label: 'AMQP', ...MUTED }, + nats: { icon: MessageSquare, label: 'NATS', ...MUTED }, + postgres: { icon: Database, label: 'Postgres', ...MUTED }, + sqs: { icon: Send, label: 'SQS', ...MUTED }, + gcp: { icon: CloudCog, label: 'GCP Pub/Sub', ...MUTED }, + data_upload: { icon: Upload, label: 'Data upload', ...MUTED } } </script> <script lang="ts"> import { Handle, Position } from '@xyflow/svelte' - import { NODE } from '$lib/components/graph/util' - import { twMerge } from 'tailwind-merge' - import { AlertTriangle, CheckCircle2, EllipsisVertical, Target, Trash2 } from 'lucide-svelte' - import DropdownV2 from '$lib/components/DropdownV2.svelte' - import { stopPropagation, preventDefault } from 'svelte/legacy' + import PipelineNodeCard from './PipelineNodeCard.svelte' + import NodeActionsMenu from './NodeActionsMenu.svelte' + import NodeFixButton, { type NodeFix } from './NodeFixButton.svelte' + import { describeSchedule } from '$lib/utils/describeCron' + import { AlertTriangle, CheckCircle2, Target, Trash2 } from 'lucide-svelte' import type { Item } from '$lib/utils' interface Props { @@ -74,16 +64,22 @@ // owning script is in `runnable_path` (used by the title and the // "+ Create trigger" drawer hook passed by the page). data: { + /** What is wrong with the node, and how to fix it: shows the Fix pill. */ + fix?: NodeFix kind: TriggerNodeKind ref: string unsaved?: boolean missing?: boolean + // A pipeline-local schedule draft: `ref` is the path it deploys to. + // Edit/delete go through the same callbacks, which the page routes + // to the draft instead of a trigger row. + draft?: boolean + // The cron, for a schedule: the node names its cadence instead of "Schedule". + schedule?: string + timezone?: string + // Shown as the title over the trigger's path, when the trigger has one. + summary?: string runnable_path?: string - // True iff the target script is still a draft (no DB row yet). - // Drives the "(after draft save)" hint on the missing - // placeholder, since the page-level handler refuses to open the - // create drawer until the script is deployed. - runnable_unsaved?: boolean // Page-supplied dispatcher that opens the matching native // trigger drawer with `script_path` pre-filled. When absent // (e.g. schedule, or a kind without an editor) the placeholder is @@ -128,7 +124,6 @@ let { data }: Props = $props() let hover = $state(false) - let menuOpen = $state(false) let style = $derived(TRIGGER_NODE_STYLE[data.kind]) // Webhooks are never genuinely "missing" — every deployed runnable has an @@ -143,7 +138,7 @@ let Icon = $derived(displayMissing ? AlertTriangle : style.icon) let missingTitle = $derived( displayMissing - ? `Missing ${style.label} trigger: ${data.runnable_path ?? ''} declares \`// on ${style.label}\` but no ${style.label} trigger targets it. Click to create one, or remove the annotation.` + ? `Missing ${style.label} trigger: ${data.runnable_path ?? ''} declares \`// on ${data.kind}\` but no ${style.label} trigger targets it. Click to create one, or remove the annotation.` : undefined ) // Webhook gets a drawer (URLs + webhook-specific token creation) rather @@ -200,7 +195,7 @@ ...(canDelete ? [ { - displayName: 'Delete…', + displayName: data.draft ? 'Discard draft' : 'Delete…', icon: Trash2, type: 'delete' as const, action: () => { @@ -212,6 +207,75 @@ : []) ]) + // A schedule names its cadence ("Every day at 4:00", or the cron itself + // when it has no plain reading); every other kind names its kind. + let kindName = $derived( + data.kind === 'schedule' && data.schedule + ? (describeSchedule(data.schedule, data.timezone) ?? `Schedule (${data.schedule})`) + : style.label + ) + + // One card for every state: which label, title and click the node gets. + let card = $derived.by( + (): { + kindLabel: string + title: string + tooltip?: string + draft: boolean + tone?: 'danger' | 'success' + onclick?: () => void + } => { + const unsaved = !!data.unsaved + if (canCreate) + return { + kindLabel: `${style.label} · missing`, + title: 'Click to create', + tooltip: missingTitle, + draft: false, + tone: 'danger', + onclick: handleMissingClick + } + if (canEdit) + return { + kindLabel: `${kindName}${data.draft ? ' · draft' : unsaved ? ' · unsaved' : ''}`, + title: data.summary || data.ref, + tooltip: data.draft + ? `Draft ${style.label}: ${data.ref} — created when you save the pipeline. Click to edit.` + : `Edit ${style.label} trigger: ${data.ref}`, + draft: unsaved, + onclick: handleEditClick + } + if (canOpenWebhook) + return { + kindLabel: style.label, + title: 'URLs & token', + tooltip: `Webhook endpoint for ${data.runnable_path ?? ''} — click to view URLs and create a token`, + draft: unsaved, + onclick: handleWebhookClick + } + if (canOpenDataUpload) + return { + kindLabel: `${style.label}${dataUploadReady ? ' · ready' : ''}`, + title: dataUploadReady ? 'File staged' : 'Upload & run', + tooltip: dataUploadReady + ? `Data upload for ${data.runnable_path ?? ''} — a file is staged; the pipeline is ready to run. Click to change it.` + : `Data upload for ${data.runnable_path ?? ''} — click to open the run form and upload a file`, + draft: !dataUploadReady && unsaved, + tone: dataUploadReady ? 'success' : undefined, + onclick: handleDataUploadClick + } + return { + kindLabel: `${displayMissing ? style.label : kindName}${displayMissing ? ' · missing' : unsaved ? ' · unsaved' : ''}`, + title: displayMissing ? 'no trigger row' : data.summary || data.ref, + tooltip: + missingTitle ?? + (unsaved ? `Unsaved ${style.label}: ${data.ref}` : `${style.label}: ${data.ref}`), + draft: unsaved && !displayMissing, + tone: displayMissing ? 'danger' : undefined + } + } + ) + function handleMissingClick() { if (!canCreate || !data.runnable_path || !data.onCreateMissingTrigger) return data.onCreateMissingTrigger(data.kind as NativeTriggerKind, data.runnable_path) @@ -235,195 +299,33 @@ <!-- svelte-ignore a11y_no_static_element_interactions --> <div class="relative" onmouseenter={() => (hover = true)} onmouseleave={() => (hover = false)}> - {#if canCreate} - <!-- Same affordance as the asset's downstream + button: render the - whole node as a button so the cursor + hover + click is obvious - without depending on svelte-flow's wrapper-level handlers. --> - <button - type="button" - onclick={handleMissingClick} - class={twMerge( - 'flex items-center rounded-md drop-shadow-sm overflow-hidden outline outline-1 w-full text-left', - 'bg-red-50 dark:bg-red-900/30 outline-dashed outline-red-400 dark:outline-red-500', - 'hover:bg-red-100 dark:hover:bg-red-900/40 transition-colors' - )} - style="width: {NODE.width}px; min-height: {NODE.height}px;" - title={missingTitle} + <NodeActionsMenu items={menuItems} {hover}> + <PipelineNodeCard + kindLabel={card.kindLabel} + title={card.title} + tooltip={card.tooltip} + draft={card.draft} + tone={card.tone} + onclick={card.onclick} > - <Icon size={14} class="shrink-0 ml-2 mr-2 text-red-600 dark:text-red-400" /> - <div class="flex flex-col min-w-0 flex-1 pr-2 py-0.5 leading-tight"> - <span class="text-3xs uppercase tracking-wide truncate text-red-700 dark:text-red-400"> - {style.label} · missing - </span> - <span class="text-2xs font-mono truncate text-red-700 dark:text-red-400"> - {data.runnable_unsaved ? 'Click to create (after draft save)' : 'Click to create'} - </span> - </div> - </button> - {:else if canEdit} - <!-- Mirrors the missing-trigger pattern: render the whole node as a - button so clicks open the editor drawer reliably (don't rely on - svelte-flow's onnodeclick wiring). --> - <button - type="button" - onclick={handleEditClick} - class={twMerge( - 'flex items-center rounded-md drop-shadow-sm overflow-hidden outline outline-1 w-full text-left', - style.bg, - data.unsaved ? `opacity-80 ${style.borderUnsaved}` : style.border, - 'hover:brightness-95 dark:hover:brightness-110 transition-[filter]' - )} - style="width: {NODE.width}px; min-height: {NODE.height}px;" - title={`Edit ${style.label} trigger: ${data.ref}`} - > - <Icon size={14} class={`shrink-0 ml-2 mr-2 ${style.iconText}`} /> - <div class="flex flex-col min-w-0 flex-1 pr-2 py-0.5 leading-tight"> - <span class="text-3xs uppercase tracking-wide truncate text-tertiary"> - {style.label}{data.unsaved ? ' · unsaved' : ''} - </span> - <span class="text-2xs font-mono truncate text-emphasis"> - {data.ref} - </span> - </div> - </button> - {:else if canOpenWebhook} - <!-- Webhook endpoint: implicit (no trigger row), so the node opens a - drawer with the URLs + webhook-specific token creation instead of - an editor. Styled like an attached trigger, never the red - "missing" state. --> - <button - type="button" - onclick={handleWebhookClick} - class={twMerge( - 'flex items-center rounded-md drop-shadow-sm overflow-hidden outline outline-1 w-full text-left', - style.bg, - data.unsaved ? `opacity-80 ${style.borderUnsaved}` : style.border, - 'hover:brightness-95 dark:hover:brightness-110 transition-[filter]' - )} - style="width: {NODE.width}px; min-height: {NODE.height}px;" - title={`Webhook endpoint for ${data.runnable_path ?? ''} — click to view URLs and create a token`} - > - <Icon size={14} class={`shrink-0 ml-2 mr-2 ${style.iconText}`} /> - <div class="flex flex-col min-w-0 flex-1 pr-2 py-0.5 leading-tight"> - <span class="text-3xs uppercase tracking-wide truncate text-tertiary"> - {style.label} - </span> - <span class="text-2xs font-mono truncate text-emphasis"> URLs & token </span> - </div> - </button> - {:else if canOpenDataUpload} - <!-- Data upload: UI-first entry point (no trigger row). Clicking the - node opens the target script's run form, where the auto-generated - S3 picker lets the user upload a file and run the pipeline. Goes - green once a file is staged (ready), so "Run pipeline" can proceed; - until then it stays neutral with an "upload a file" prompt. Never - the red "missing" state. --> - <button - type="button" - onclick={handleDataUploadClick} - class={twMerge( - 'flex items-center rounded-md drop-shadow-sm overflow-hidden outline outline-1 w-full text-left', - dataUploadReady - ? 'bg-green-50 dark:bg-green-900/30 outline-green-500 dark:outline-green-600' - : style.bg, - dataUploadReady ? '' : data.unsaved ? `opacity-80 ${style.borderUnsaved}` : style.border, - 'hover:brightness-95 dark:hover:brightness-110 transition-[filter]' - )} - style="width: {NODE.width}px; min-height: {NODE.height}px;" - title={dataUploadReady - ? `Data upload for ${data.runnable_path ?? ''} — a file is staged; the pipeline is ready to run. Click to change it.` - : `Data upload for ${data.runnable_path ?? ''} — click to open the run form and upload a file`} - > - <DataUploadIcon - size={14} - class={`shrink-0 ml-2 mr-2 ${dataUploadReady ? 'text-green-600 dark:text-green-400' : style.iconText}`} - /> - <div class="flex flex-col min-w-0 flex-1 pr-2 py-0.5 leading-tight"> - <span - class={twMerge( - 'text-3xs uppercase tracking-wide truncate', - dataUploadReady ? 'text-green-700 dark:text-green-400' : 'text-tertiary' - )} - > - {style.label}{dataUploadReady ? ' · ready' : ''} - </span> - <span - class={twMerge( - 'text-2xs font-mono truncate', - dataUploadReady ? 'text-green-700 dark:text-green-400' : 'text-emphasis' - )} - > - {dataUploadReady ? 'File staged' : 'Upload & run'} - </span> - </div> - </button> - {:else} - <div - class={twMerge( - 'flex items-center rounded-md drop-shadow-sm overflow-hidden outline outline-1', - displayMissing - ? 'bg-red-50 dark:bg-red-900/30 outline-dashed outline-red-400 dark:outline-red-500' - : style.bg, - displayMissing ? '' : data.unsaved ? `opacity-80 ${style.borderUnsaved}` : style.border - )} - style="width: {NODE.width}px; min-height: {NODE.height}px;" - title={missingTitle ?? - (data.unsaved ? `Unsaved ${style.label}: ${data.ref}` : `${style.label}: ${data.ref}`)} - > - <Icon - size={14} - class={`shrink-0 ml-2 mr-2 ${displayMissing ? 'text-red-600 dark:text-red-400' : style.iconText}`} - /> - <div class="flex flex-col min-w-0 flex-1 pr-2 py-0.5 leading-tight"> - <span - class={twMerge( - 'text-3xs uppercase tracking-wide truncate', - displayMissing ? 'text-red-700 dark:text-red-400' : 'text-tertiary' - )} - > - {style.label}{displayMissing ? ' · missing' : data.unsaved ? ' · unsaved' : ''} - </span> - <span - class={twMerge( - 'text-2xs font-mono truncate', - displayMissing ? 'text-red-700 dark:text-red-400' : 'text-emphasis' - )} - > - {displayMissing ? 'no trigger row' : data.ref} - </span> - </div> - </div> - {/if} - - {#if menuItems.length > 0} - <!-- Hover-revealed kebab menu (Delete only for now). Mirrors the - RunnableNode pattern: positioned just outside the top-right of - the node, rendered only on hover or while the menu is open so - the canvas stays clean at rest. `pointerdown` is stopped so - svelte-flow doesn't kick off node selection / drag when the - user reaches for the menu. --> - <div class="absolute -top-2 -right-2 h-7 p-1 min-w-7" style="will-change: transform;"> - <DropdownV2 - items={menuItems} - placement="bottom-end" - bind:open={menuOpen} - fixedHeight={false} - usePointerDownOutside - > - {#snippet buttonReplacement()} - <button - class={twMerge( - 'center-center p-1 text-secondary shadow-sm bg-surface duration-0 hover:bg-surface-tertiary', - hover || menuOpen ? 'block' : '!hidden', - 'shadow-md rounded-md' - )} - onpointerdown={stopPropagation(preventDefault(() => {}))} - title="Actions" - > - <EllipsisVertical size={12} /> - </button> - {/snippet} - </DropdownV2> + {#snippet icon()} + {#if canOpenDataUpload} + <DataUploadIcon + size={14} + class={dataUploadReady ? 'text-green-600 dark:text-green-400' : style.iconText} + /> + {:else} + <Icon + size={14} + class={displayMissing || canCreate ? 'text-red-600 dark:text-red-400' : style.iconText} + /> + {/if} + {/snippet} + </PipelineNodeCard> + </NodeActionsMenu> + {#if data.fix} + <div class="absolute left-1/2 -bottom-3 -translate-x-1/2 z-10"> + <NodeFixButton fix={data.fix} /> </div> {/if} </div> diff --git a/frontend/src/lib/components/assets/AssetGraph/assetGraphLayout.test.ts b/frontend/src/lib/components/assets/AssetGraph/assetGraphLayout.test.ts index 24e7d4c2da..073432e1a5 100644 --- a/frontend/src/lib/components/assets/AssetGraph/assetGraphLayout.test.ts +++ b/frontend/src/lib/components/assets/AssetGraph/assetGraphLayout.test.ts @@ -147,4 +147,18 @@ describe('layoutAssetGraph (tidy-tree with join breaks)', () => { expect(pos.get(id)!.y).toBeGreaterThan(anchor.y) } }) + + it('packs narrow nodes by their own width', () => { + const pos = layoutAssetGraph({ + nodes: [ + { ...n('p'), width: 100 }, + { ...n('l'), width: 100 }, + { ...n('r'), width: 180 } + ], + edges: [e('p', 'l'), e('p', 'r')] + }) + const gap = pos.get('r')!.x - 90 - (pos.get('l')!.x + 50) + expect(gap).toBe(NODE.gap.horizontal) + expect(pos.get('l')!.x).toBe(50) + }) }) diff --git a/frontend/src/lib/components/assets/AssetGraph/assetGraphLayout.ts b/frontend/src/lib/components/assets/AssetGraph/assetGraphLayout.ts index c9d7d60355..e1e1e1e7da 100644 --- a/frontend/src/lib/components/assets/AssetGraph/assetGraphLayout.ts +++ b/frontend/src/lib/components/assets/AssetGraph/assetGraphLayout.ts @@ -7,7 +7,15 @@ import { NODE } from '$lib/components/graph/util' // breathing room. const NODE_WIDTH = NODE.width const NODE_HEIGHT = NODE.height + 30 -const LAYER_GAP = NODE.gap.vertical +/** Rendered height of a pipeline node: a kind label over a title. Fits inside + * the `NODE_HEIGHT` row the layout reserves. */ +export const PIPELINE_NODE_HEIGHT = 48 +// A step more than the flow editor's gap: the + on a node's bottom edge sits in it. +const LAYER_GAP = NODE.gap.vertical + 16 +/** Height of the "Add data source" pill the anchor draws, and its gap to the + * graph: tighter than LAYER_GAP, since no edge runs through it. */ +const ANCHOR_HEIGHT = 32 +const ANCHOR_GAP = 40 const SIBLING_GAP = NODE.gap.horizontal // Horizontal gutter between two disjoint subgraphs. Wider than the // within-subgraph sibling gap so visually-unrelated components (e.g. two @@ -15,10 +23,16 @@ const SIBLING_GAP = NODE.gap.horizontal // into each other's columns — but only ~2×, so they don't drift far apart. const COMPONENT_GAP = SIBLING_GAP * 2 -const LAYER_H = NODE_HEIGHT + LAYER_GAP +/** Extra height of an assets-only node: the trigger chip under its title. */ +export const PIPELINE_NODE_EXTRA_ROW = 20 +/** Height of the header strip naming an assets-only node's producing script. */ +export const PIPELINE_NODE_HEADER = 22 +/** Extra vertical padding of a card under a header, top plus bottom. */ +export const PIPELINE_NODE_HEADER_CARD_PAD = 12 interface GraphInput { - nodes: Array<{ id: string; data: AssetGraphNodeData }> + /** `width` defaults to `NODE.width`. */ + nodes: Array<{ id: string; data: AssetGraphNodeData; width?: number }> edges: Array<{ source: string; target: string }> } @@ -52,15 +66,18 @@ interface Band { // intersects theirs. // // y comes from longest-path layering (same top-down orientation as before: -// producers above, assets in the middle, consumers below). Returns positions -// (band centers) normalized so the component's min x,y = 0. Cyclic input is -// handled by dropping feedback edges (see the Kahn step below). +// producers above, assets in the middle, consumers below). Returns node +// centers, normalized so the component's leftmost edge and top are at 0. +// Cyclic input is handled by dropping feedback edges (see the Kahn step below). function layoutComponent( nodes: GraphInput['nodes'], - edges: GraphInput['edges'] + edges: GraphInput['edges'], + rowH: number ): Map<string, Positioned> { + const layerH = rowH + LAYER_GAP const out = new Map<string, Positioned>() const ids = new Set(nodes.map((n) => n.id)) + const nodeW = new Map(nodes.map((n) => [n.id, n.width ?? NODE_WIDTH])) const parents = new Map<string, string[]>() const children = new Map<string, string[]>() @@ -137,7 +154,7 @@ function layoutComponent( const kids = treeChildren.get(id)! const kidsW = kids.reduce((acc, k) => acc + W.get(k)!, 0) + SIBLING_GAP * Math.max(0, kids.length - 1) - W.set(id, Math.max(NODE_WIDTH, kidsW)) + W.set(id, Math.max(nodeW.get(id)!, kidsW)) } // Vertical (pixel) extent of a subtree, for band collision checks. @@ -152,14 +169,14 @@ function layoutComponent( if (l > hi) hi = l for (const k of treeChildren.get(cur)!) stack.push(k) } - return { top: lo * LAYER_H, bottom: hi * LAYER_H + NODE_HEIGHT } + return { top: lo * layerH, bottom: hi * layerH + rowH } } // Recursive placement: node centered over its band, children packed // side-by-side and centered within it. function placeTree(id: string, left: number) { const w = W.get(id)! - out.set(id, { x: left + w / 2, y: layer.get(id)! * LAYER_H }) + out.set(id, { x: left + w / 2, y: layer.get(id)! * layerH }) const kids = treeChildren.get(id)! if (kids.length === 0) return const kidsW = kids.reduce((acc, k) => acc + W.get(k)!, 0) + SIBLING_GAP * (kids.length - 1) @@ -211,11 +228,11 @@ function layoutComponent( placeAndRecord(id, center - w / 2) } - // Normalize so the component's min x,y = 0. + // Normalize so the component's leftmost edge and top are at 0. let minX = Infinity let minY = Infinity - for (const p of out.values()) { - if (p.x < minX) minX = p.x + for (const [id, p] of out) { + if (p.x - nodeW.get(id)! / 2 < minX) minX = p.x - nodeW.get(id)! / 2 if (p.y < minY) minY = p.y } if (isFinite(minX) && isFinite(minY)) { @@ -243,7 +260,13 @@ function layoutComponent( // // Falls back to a stable grid if the component layout throws (defensive — // cycles are already absorbed by feedback-edge dropping in layoutComponent). -export function layoutAssetGraph(graph: GraphInput, anchorId?: string): Map<string, Positioned> { +export function layoutAssetGraph( + graph: GraphInput, + anchorId?: string, + extraRowHeight = 0 +): Map<string, Positioned> { + const rowH = NODE_HEIGHT + extraRowHeight + const layerH = rowH + LAYER_GAP const byId = new Map<string, Positioned>() if (graph.nodes.length === 0) return byId @@ -297,19 +320,20 @@ export function layoutAssetGraph(graph: GraphInput, anchorId?: string): Map<stri // 3. Lay out each component and pack side-by-side. xOffset advances by // the laid-out width of each component (max node center + a node width, // since positions are node centers) plus the gutter. + const widthOf = new Map(nodes.map((n) => [n.id, n.width ?? NODE_WIDTH])) let xOffset = 0 for (let c = 0; c < nComp; c++) { - const positions = layoutComponent(compNodes[c], compEdges[c]) - let maxX = 0 - for (const p of positions.values()) if (p.x > maxX) maxX = p.x + const positions = layoutComponent(compNodes[c], compEdges[c], rowH) + let maxRight = 0 for (const [id, p] of positions) { + maxRight = Math.max(maxRight, p.x + widthOf.get(id)! / 2) byId.set(id, { x: p.x + xOffset, y: p.y }) } - xOffset += maxX + NODE_WIDTH + COMPONENT_GAP + xOffset += maxRight + COMPONENT_GAP } // 4. Re-place the anchor centered horizontally over the whole packed - // graph, one layer above it; then renormalize so the anchor sits at the + // graph, just above it; then renormalize so the anchor sits at the // top (y = 0), pushing the components down a layer to make room (mirrors // the previous "anchor is the parent of every root" behaviour). if (anchorId && graph.nodes.some((n) => n.id === anchorId)) { @@ -324,7 +348,9 @@ export function layoutAssetGraph(graph: GraphInput, anchorId?: string): Map<stri if (p.x > maxX) maxX = p.x if (p.y < minY) minY = p.y } - byId.set(anchorId, { x: (minX + maxX) / 2, y: minY - LAYER_H }) + // One gap above the graph, sized to the pill rather than a full node row: + // a row tall enough for an assets-only card leaves it floating high. + byId.set(anchorId, { x: (minX + maxX) / 2, y: minY - ANCHOR_HEIGHT - ANCHOR_GAP }) let nMinY = Infinity for (const p of byId.values()) if (p.y < nMinY) nMinY = p.y for (const p of byId.values()) p.y -= nMinY @@ -336,7 +362,7 @@ export function layoutAssetGraph(graph: GraphInput, anchorId?: string): Map<stri graph.nodes.forEach((n, i) => { byId.set(n.id, { x: (i % cols) * (NODE_WIDTH + SIBLING_GAP), - y: Math.floor(i / cols) * LAYER_H + y: Math.floor(i / cols) * layerH }) }) return byId diff --git a/frontend/src/lib/components/assets/AssetGraph/assetNodeWidth.ts b/frontend/src/lib/components/assets/AssetGraph/assetNodeWidth.ts new file mode 100644 index 0000000000..176ecf7411 --- /dev/null +++ b/frontend/src/lib/components/assets/AssetGraph/assetNodeWidth.ts @@ -0,0 +1,66 @@ +import { NODE } from '$lib/components/graph/util' + +const MIN_WIDTH = 160 + +let ctx: CanvasRenderingContext2D | null | undefined + +/** Rendered width of `text` at `rem` in the page font, or a rough guess without a DOM. */ +function textWidth(text: string, rem: number): number { + if (typeof document === 'undefined') return text.length * rem * 16 * 0.6 + ctx ??= document.createElement('canvas').getContext('2d') + const root = parseFloat(getComputedStyle(document.documentElement).fontSize) || 16 + if (!ctx) return text.length * rem * root * 0.6 + const body = getComputedStyle(document.body) + ctx.font = `${rem * root}px ${body.fontFamily}` + const spacing = parseFloat(body.letterSpacing) || 0 + return ctx.measureText(text).width + spacing * text.length +} + +/** + * Width of an assets-only asset card, from the pieces `PipelineNodeCard` and + * `AssetNode` lay out: icon and the widest of kind / title / trigger chip, or the + * header naming the producing script, if wider. The numbers mirror their Tailwind spacing; change one + * and the other drifts. Clamped to the regular node width, past which the title + * truncates as usual. + */ +export function assetsOnlyNodeWidth(n: { + kind: string + title: string + chip: string + /** The chip leads with an icon (the folded-errors Fix chip). */ + chipIcon?: boolean + /** The chip ends in the edit icon (an editable trigger). */ + chipEdit?: boolean + /** The header tab: its text (a script's summary or path, "N scripts"), icon + * count, and whether it ends in the menu chevron (else the edit icon) or has a "draft" mark; + * undefined without a header. */ + header?: { label: string; icons: number; chevron?: boolean; draft?: boolean } +}): number { + const icon = 12 + 14 + 10 + const text = Math.max( + textWidth(n.kind, 0.7), + textWidth(n.title, 0.75), + textWidth(n.chip, 0.65) + 12 + 2 + (n.chipIcon ? 14 : 0) + (n.chipEdit ? 4 + 9 : 0) + ) + const body = Math.ceil(icon + text + 4 + 8 + 2 + 8) + // Header tab: mx-2 and a 1px border around px-2, then gap-1.5 between its + // items: the icons, the label, a "draft" mark, and the chevron or edit icon. + // The run chip is left out: it comes and goes with runs, and a width that + // followed it would re-lay the graph on a click; the label truncates instead. + const h = n.header + const header = h + ? Math.ceil( + 16 + + 2 + + 16 + + h.icons * (11 + 6) + + textWidth(h.label, 0.65) + + (h.draft ? 6 + textWidth('draft', 0.65) : 0) + + // The menu chevron, or the edit icon of a single script. + 6 + + (h.chevron ? 11 : 10) + + 4 + ) + : 0 + return Math.min(NODE.width, Math.max(MIN_WIDTH, body, header)) +} diff --git a/frontend/src/lib/components/assets/AssetGraph/assetsOnlyFolders.ts b/frontend/src/lib/components/assets/AssetGraph/assetsOnlyFolders.ts new file mode 100644 index 0000000000..4079986ee5 --- /dev/null +++ b/frontend/src/lib/components/assets/AssetGraph/assetsOnlyFolders.ts @@ -0,0 +1,25 @@ +// Pipelines open in the assets-only view. This remembers the ones last left +// showing their scripts and triggers, as `<workspace>/<folder>`, so reopening one +// shows it the same way. Browser-local: a missing or unreadable list reads as +// "none", and storage that throws (private mode, blocked site data) is ignored. +const KEY = 'pipeline-full-view-folders' + +function read(): string[] { + try { + const parsed = JSON.parse(localStorage.getItem(KEY) ?? '[]') + return Array.isArray(parsed) ? parsed.filter((f) => typeof f === 'string') : [] + } catch { + return [] + } +} + +export function isAssetsOnlyFolder(folder: string): boolean { + return !read().includes(folder) +} + +export function setAssetsOnlyFolder(folder: string, on: boolean): void { + const rest = read().filter((f) => f !== folder) + try { + localStorage.setItem(KEY, JSON.stringify(on ? rest : [...rest, folder])) + } catch {} +} diff --git a/frontend/src/lib/components/assets/AssetGraph/assetsOnlyView.test.ts b/frontend/src/lib/components/assets/AssetGraph/assetsOnlyView.test.ts new file mode 100644 index 0000000000..0f2cf472ac --- /dev/null +++ b/frontend/src/lib/components/assets/AssetGraph/assetsOnlyView.test.ts @@ -0,0 +1,162 @@ +import { describe, expect, it } from 'vitest' +import { + assetsOnlyView, + upstreamDeletion, + noAssetNodeId, + withoutPassiveReads, + type AssetUpstream +} from './assetsOnlyView' + +const node = (id: string, type: string, data: any = {}) => ({ id, type, data }) +const edge = (source: string, target: string, kind: string) => ({ + id: `${kind}:${source}->${target}`, + source, + target, + kind +}) + +describe('assetsOnlyView', () => { + const nodes = [ + node('asset:ducklake:raw', 'asset'), + node('asset:ducklake:clean', 'asset'), + node('asset:ducklake:report', 'asset'), + node('script:f/p/clean', 'runnable'), + node('script:f/p/report', 'runnable'), + node('script:f/p/other', 'runnable'), + node('trigger:schedule:f/p/daily', 'trigger', { kind: 'schedule', schedule: '0 0 4 * * *' }) + ] + const edges = [ + edge('trigger:schedule:f/p/daily', 'script:f/p/clean', 'trigger-native'), + edge('asset:ducklake:raw', 'script:f/p/clean', 'lineage-read'), + edge('script:f/p/clean', 'asset:ducklake:clean', 'lineage-write'), + // read-modify-write: no self edge + edge('asset:ducklake:clean', 'script:f/p/clean', 'lineage-read'), + edge('asset:ducklake:clean', 'script:f/p/report', 'trigger-asset'), + edge('asset:ducklake:clean', 'script:f/p/report', 'lineage-read'), + edge('script:f/p/report', 'asset:ducklake:report', 'lineage-write'), + edge('script:f/p/other', 'asset:ducklake:report', 'lineage-write') + ] + const v = assetsOnlyView(nodes, edges) + + it('joins each script input to its outputs, once', () => { + expect(v.edges.map((e) => `${e.source} -> ${e.target}`).sort()).toEqual([ + 'asset:ducklake:clean -> asset:ducklake:report', + 'asset:ducklake:raw -> asset:ducklake:clean' + ]) + expect([...v.nodeIds].sort()).toEqual([ + 'asset:ducklake:clean', + 'asset:ducklake:raw', + 'asset:ducklake:report' + ]) + }) + + it('names the single producer and its trigger, or marks the asset ambiguous', () => { + expect(v.upstream.get('asset:ducklake:raw')).toBeUndefined() + expect(v.upstream.get('asset:ducklake:clean')).toMatchObject({ + multiple: false, + runnableId: 'script:f/p/clean', + trigger: { kind: 'schedule', data: { schedule: '0 0 4 * * *' } } + }) + expect(v.upstream.get('asset:ducklake:report')).toEqual({ + multiple: true, + runnableIds: ['script:f/p/report', 'script:f/p/other'] + }) + }) +}) + +describe('the No asset nodes', () => { + it('give each script that builds nothing its own node, fed by what it reads', () => { + const v = assetsOnlyView( + [ + node('asset:ducklake:a', 'asset'), + node('asset:ducklake:b', 'asset'), + node('script:f/p/on_a', 'runnable'), + node('script:f/p/on_b', 'runnable'), + node('script:f/p/dbt', 'runnable', { dbt: { model_count: 3 } }), + node('script:f/p/macros', 'runnable', { macros: [{ name: 'm' }] }) + ], + [ + edge('asset:ducklake:a', 'script:f/p/on_a', 'trigger-asset'), + edge('asset:ducklake:b', 'script:f/p/on_b', 'trigger-asset') + ] + ) + const onA = noAssetNodeId('script:f/p/on_a') + const onB = noAssetNodeId('script:f/p/on_b') + expect(v.noAssetNodeIds).toEqual([onA, onB]) + expect(v.upstream.get(onA)).toMatchObject({ runnableId: 'script:f/p/on_a' }) + expect(v.edges.map((e) => `${e.source} -> ${e.target}`)).toEqual([ + `asset:ducklake:a -> ${onA}`, + `asset:ducklake:b -> ${onB}` + ]) + }) +}) + +describe('upstreamDeletion', () => { + const script = { runnable_kind: 'script', path: 'f/p/a' } + const schedule = (targets: string[]) => ({ + kind: 'schedule', + nodeId: 'trigger:schedule:f/p/a_schedule', + data: { ref: 'f/p/a_schedule', runnable_paths: targets } + }) + const own = (trigger?: any): AssetUpstream & { multiple: false } => ({ + multiple: false, + runnableId: 'script:f/p/a', + trigger + }) + + it('deletes the script and a trigger that fires only it', () => { + const u = own(schedule(['f/p/a'])) + expect(upstreamDeletion(u, script, new Map([['asset:x', u]]))).toEqual({ + script: { path: 'f/p/a', unsaved: false }, + trigger: { kind: 'schedule', path: 'f/p/a_schedule', draft: false } + }) + }) + + it('keeps a trigger that fires other scripts', () => { + const u = own(schedule(['f/p/a', 'f/p/b'])) + expect(upstreamDeletion(u, script, new Map([['asset:x', u]]))?.trigger).toBeUndefined() + }) + + it('deletes nothing when the script also co-produces another asset', () => { + const u = own(schedule(['f/p/a'])) + const all = new Map<string, AssetUpstream>([ + ['asset:x', u], + ['asset:y', { multiple: true, runnableIds: ['script:f/p/a', 'script:f/p/b'] }] + ]) + expect(upstreamDeletion(u, script, all)).toBeUndefined() + }) + + it('deletes nothing when the script builds another asset too', () => { + const u = own(schedule(['f/p/a'])) + const all = new Map([ + ['asset:x', u], + ['asset:y', u] + ]) + expect(upstreamDeletion(u, script, all)).toBeUndefined() + }) +}) + +describe('withoutPassiveReads', () => { + it('drops reads that trigger nothing, and the assets only they drew', () => { + const nodes = [ + node('asset:src', 'asset'), + node('asset:lookup', 'asset'), + node('asset:out', 'asset'), + node('script:a', 'runnable') + ] + const edges = [ + edge('asset:src', 'script:a', 'lineage-read'), + edge('asset:src', 'script:a', 'trigger-asset'), + edge('asset:lookup', 'script:a', 'lineage-read'), + edge('asset:out', 'script:a', 'lineage-read'), + edge('script:a', 'asset:out', 'lineage-write') + ] + const r = withoutPassiveReads(nodes, edges) + expect(r.nodes.map((n) => n.id)).toEqual(['asset:src', 'asset:out', 'script:a']) + expect(r.edges.map((e) => e.id)).toEqual([ + 'lineage-read:asset:src->script:a', + 'trigger-asset:asset:src->script:a', + 'lineage-write:script:a->asset:out' + ]) + }) +}) diff --git a/frontend/src/lib/components/assets/AssetGraph/assetsOnlyView.ts b/frontend/src/lib/components/assets/AssetGraph/assetsOnlyView.ts new file mode 100644 index 0000000000..c7bf85d144 --- /dev/null +++ b/frontend/src/lib/components/assets/AssetGraph/assetsOnlyView.ts @@ -0,0 +1,234 @@ +import type { NativeTriggerKind } from './types' + +/** A node or edge of the canvas model, reduced to what the assets-only view reads. */ +export type ViewNode = { id: string; type: string; data: any } +export type ViewEdge = { + id: string + source: string + target: string + kind: string + unsaved?: boolean + /** Assets-only edges: the folded runnables the data goes through. */ + via?: string[] + /** Assets-only edges: a write to the source reruns one of `via`. */ + reactive?: boolean +} + +/** The assets-only node standing for a script that builds no asset: one per + * script, so scripts reacting to different inputs stay apart. */ +export const noAssetNodeId = (runnableId: string) => `no-asset:${runnableId}` +export const isNoAssetNode = (id: string) => id.startsWith('no-asset:') + +/** What an assets-only delete removes: the script, its trigger, or both. */ +export type AssetUpstreamDelete = { + script?: { path: string; unsaved: boolean } + trigger?: { kind: NativeTriggerKind; path: string; draft: boolean } +} + +/** What an asset shows of the script and trigger that produce it, in the assets-only view. */ +export type AssetUpstream = + /** Several producing scripts, or one with several triggers. */ + | { multiple: true; runnableIds: string[] } + | { + multiple: false + /** Canvas id of the producing runnable (`script:<path>`). */ + runnableId: string + /** The producer's trigger; undefined when nothing triggers it (run by hand). */ + trigger?: { nodeId?: string; kind: string; data?: any } + } + +/** + * The asset → asset view of a pipeline graph: runnables and triggers disappear, + * and every read (or asset trigger) of a script is joined to each of its writes, + * so an asset points at the assets computed from it. Each produced asset keeps a + * reference to its single producer and that producer's single trigger, or is + * marked `multiple` when either is ambiguous. + */ +export function assetsOnlyView<N extends ViewNode, E extends ViewEdge>( + nodes: N[], + edges: E[] +): { + nodeIds: Set<string> + edges: Array<ViewEdge> + upstream: Map<string, AssetUpstream> + /** A node per script that builds no asset (`noAssetNodeId`), its upstream + * under that id. */ + noAssetNodeIds: string[] +} { + const nodeById = new Map(nodes.map((n) => [n.id, n])) + const inputsOf = new Map<string, E[]>() + const triggersOf = new Map<string, E[]>() + const producersOf = new Map<string, E[]>() + const push = (m: Map<string, E[]>, k: string, e: E) => m.set(k, [...(m.get(k) ?? []), e]) + for (const e of edges) { + if (e.kind === 'lineage-write') push(producersOf, e.target, e) + else if (e.kind === 'lineage-read' || e.kind === 'trigger-asset') { + push(inputsOf, e.target, e) + if (e.kind === 'trigger-asset') push(triggersOf, e.target, e) + } else if (e.kind === 'trigger-native') push(triggersOf, e.target, e) + } + + const triggered = new Set( + edges.filter((e) => e.kind === 'trigger-asset').map((e) => `${e.source}\n${e.target}`) + ) + const out = new Map<string, ViewEdge>() + for (const [assetId, writes] of producersOf) { + for (const w of writes) { + for (const r of inputsOf.get(w.source) ?? []) { + // A read-modify-write of the same table is not a dependency on itself. + if (r.source === assetId) continue + const id = `flow:${r.source}->${assetId}` + const prev = out.get(id) + const unsaved = !!(w.unsaved || r.unsaved) + const reactive = triggered.has(`${r.source}\n${w.source}`) + if (prev) { + prev.unsaved = prev.unsaved && unsaved + prev.reactive ||= reactive + if (!prev.via?.includes(w.source)) prev.via = [...(prev.via ?? []), w.source] + } else { + out.set(id, { + id, + source: r.source, + target: assetId, + kind: 'asset-flow', + unsaved, + reactive, + via: [w.source] + }) + } + } + } + } + for (const e of edges) if (e.kind === 'dbt-ref') out.set(e.id, e) + + function describe(runnableIds: string[]): AssetUpstream { + if (runnableIds.length !== 1) return { multiple: true, runnableIds } + const runnableId = runnableIds[0] + // Every asset trigger of a script is one cause, "an input changed". + const triggers = [ + ...new Map( + (triggersOf.get(runnableId) ?? []).map((t) => [ + t.kind === 'trigger-asset' ? 'asset' : t.source, + t + ]) + ).values() + ] + if (triggers.length > 1) return { multiple: true, runnableIds } + const t = triggers[0] + const tNode = t && nodeById.get(t.source) + return { + multiple: false, + runnableId, + trigger: !t + ? undefined + : t.kind === 'trigger-asset' + ? { kind: 'asset' } + : { nodeId: t.source, kind: tNode?.data?.kind, data: tNode?.data } + } + } + + const upstream = new Map<string, AssetUpstream>() + for (const [assetId, writes] of producersOf) { + upstream.set(assetId, describe([...new Set(writes.map((w) => w.source))])) + } + + // Scripts that build no asset have nowhere to fold into, so each gets a "No + // asset" node, fed by what it reads. dbt projects (whose writes are not drawn) + // and macro libraries (which build nothing by design) get none. + const writers = new Set([...producersOf.values()].flat().map((w) => w.source)) + const orphans = nodes + .filter( + (n) => n.type === 'runnable' && !writers.has(n.id) && !n.data?.dbt && !n.data?.macros?.length + ) + .map((n) => n.id) + for (const id of orphans) { + const nodeId = noAssetNodeId(id) + upstream.set(nodeId, describe([id])) + for (const r of inputsOf.get(id) ?? []) { + const eid = `flow:${r.source}->${nodeId}` + const reactive = triggered.has(`${r.source}\n${id}`) + const prev = out.get(eid) + if (prev) { + prev.unsaved = prev.unsaved && !!r.unsaved + prev.reactive ||= reactive + } else { + out.set(eid, { + id: eid, + source: r.source, + target: nodeId, + kind: 'asset-flow', + unsaved: !!r.unsaved, + reactive, + via: [id] + }) + } + } + } + + const nodeIds = new Set(nodes.filter((n) => n.type === 'asset').map((n) => n.id)) + return { + nodeIds, + edges: [...out.values()], + upstream, + noAssetNodeIds: orphans.map(noAssetNodeId) + } +} + +/** What deleting an asset's upstream removes: the script unless another asset + * is also built by it, and with it the trigger unless that fires other scripts. + * Undefined when nothing can go. */ +export function upstreamDeletion( + u: AssetUpstream & { multiple: false }, + r: { runnable_kind: string; path: string; unsaved?: boolean }, + all: Map<string, AssetUpstream> +): AssetUpstreamDelete | undefined { + if (r.runnable_kind !== 'script') return undefined + const producesOthers = + [...all.values()].filter((o) => + o.multiple ? o.runnableIds.includes(u.runnableId) : o.runnableId === u.runnableId + ).length > 1 + if (producesOthers) return undefined + const t = u.trigger + const kind = t?.kind as NativeTriggerKind | undefined + const targets: string[] = t?.data?.runnable_paths ?? [] + const ownTrigger = + kind && + kind !== 'webhook' && + kind !== 'data_upload' && + t?.data?.ref && + !t.data.missing && + targets.every((p) => p === r.path) + return { + script: { path: r.path, unsaved: !!r.unsaved }, + trigger: ownTrigger ? { kind, path: t.data.ref, draft: !!t.data.draft } : undefined + } +} + +/** + * The graph without its reads that start nothing: a read edge with no asset + * trigger along it, and the assets only such reads drew. + */ +export function withoutPassiveReads<N extends ViewNode, E extends ViewEdge>( + nodes: N[], + edges: E[] +): { nodes: N[]; edges: E[]; dropped: number } { + const triggers = new Set( + edges.filter((e) => e.kind === 'trigger-asset').map((e) => `${e.source}\n${e.target}`) + ) + const passive = (e: E) => + e.kind === 'lineage-read' && !triggers.has(`${e.source}\n${e.target}`) + const kept = edges.filter((e) => !passive(e)) + const dropped = edges.length - kept.length + if (dropped === 0) return { nodes, edges, dropped } + const linked = new Set( + kept.filter((e) => e.kind !== 'add-anchor').flatMap((e) => [e.source, e.target]) + ) + const readOnly = new Set( + edges.filter(passive).map((e) => e.source).filter((id) => !linked.has(id)) + ) + return { + nodes: nodes.filter((n) => !readOnly.has(n.id)), + edges: kept.filter((e) => !readOnly.has(e.source) && !readOnly.has(e.target)), + dropped + } +} diff --git a/frontend/src/lib/components/assets/AssetGraph/edgeDescription.test.ts b/frontend/src/lib/components/assets/AssetGraph/edgeDescription.test.ts new file mode 100644 index 0000000000..2aff7a0e81 --- /dev/null +++ b/frontend/src/lib/components/assets/AssetGraph/edgeDescription.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from 'vitest' +import { describeEdge } from './edgeDescription' + +const names: Record<string, string> = { + 'asset:ducklake:main/raw': 'raw', + 'asset:ducklake:main/clean': 'clean', + 'script:f/p/clean': 'Clean', + 'trigger:schedule:f/p/daily': 'Daily' +} +const nameOf = (id: string) => names[id] ?? id +const dataOf = (id: string) => + id === 'trigger:schedule:f/p/daily' + ? { kind: 'schedule', schedule: '0 0 12 * * *', timezone: 'UTC' } + : undefined + +describe('describeEdge', () => { + it('names an asset trigger by what runs it: any write, changed or not', () => { + expect( + describeEdge( + { source: 'asset:ducklake:main/raw', target: 'script:f/p/clean', kind: 'trigger-asset' }, + nameOf, + dataOf + ) + ).toEqual({ subject: 'Clean', phrase: 'runs after each write to', object: 'raw' }) + }) + + it("gives a schedule's cadence", () => { + expect( + describeEdge( + { source: 'trigger:schedule:f/p/daily', target: 'script:f/p/clean', kind: 'trigger-native' }, + nameOf, + dataOf + )?.phrase + ).toBe('runs on schedule: Every day at 12:00 UTC') + }) + + it('names the folded script on an assets-only edge', () => { + expect( + describeEdge( + { + source: 'asset:ducklake:main/raw', + target: 'asset:ducklake:main/clean', + kind: 'asset-flow', + via: ['script:f/p/clean'] + }, + nameOf, + dataOf + ) + ).toEqual({ subject: 'clean', phrase: 'is built from', object: 'raw', note: 'By Clean. A write to raw does not rerun it.' }) + }) +}) diff --git a/frontend/src/lib/components/assets/AssetGraph/edgeDescription.ts b/frontend/src/lib/components/assets/AssetGraph/edgeDescription.ts new file mode 100644 index 0000000000..72d8eb103b --- /dev/null +++ b/frontend/src/lib/components/assets/AssetGraph/edgeDescription.ts @@ -0,0 +1,110 @@ +import { describeSchedule } from '$lib/utils/describeCron' +import { isNoAssetNode } from './assetsOnlyView' + +/** What a hovered edge says: "`subject` `phrase` `object`", then a note. */ +export type EdgeDescription = { subject: string; phrase: string; object?: string; note?: string } + +/** The edge fields the description reads (the canvas model's edge). */ +export type DescribedEdge = { + source: string + target: string + kind: string + unsaved?: boolean + muted?: boolean + missing?: boolean + via?: string[] + reactive?: boolean + macro_names?: string[] + via_use?: boolean +} + +// What starts a script, per trigger kind: "runs on <event>". +const TRIGGER_EVENT: Record<string, string> = { + kafka: 'Kafka message', + mqtt: 'MQTT message', + amqp: 'AMQP message', + nats: 'NATS message', + sqs: 'SQS message', + gcp: 'Pub/Sub message', + email: 'incoming email', + postgres: 'Postgres event', + webhook: 'webhook call', + data_upload: 'data upload' +} + +/** + * The relationship an edge draws, as a sentence about its two ends. `nameOf` + * names a node, `dataOf` gives its data (a trigger's kind and cadence). + */ +export function describeEdge( + e: DescribedEdge, + nameOf: (id: string) => string, + dataOf: (id: string) => any +): EdgeDescription | undefined { + const src = nameOf(e.source) + const tgt = nameOf(e.target) + const draft = e.unsaved ? 'Not deployed yet.' : undefined + switch (e.kind) { + case 'lineage-write': + return { subject: src, phrase: 'writes to', object: tgt, note: draft } + case 'lineage-read': + return { + subject: tgt, + phrase: 'reads from', + object: src, + note: e.muted ? 'A write to it does not run the script (muted).' : draft + } + case 'trigger-asset': + return { subject: tgt, phrase: 'runs after each write to', object: src, note: draft } + case 'trigger-native': { + const t = dataOf(e.source) ?? {} + if (e.missing) { + return { + subject: tgt, + phrase: `declares \`// on ${t.kind}\`, but no trigger of that kind targets it` + } + } + const phrase = + t.kind === 'schedule' && t.schedule + ? `runs on schedule: ${describeSchedule(t.schedule, t.timezone) ?? t.schedule}` + : `runs on ${TRIGGER_EVENT[t.kind] ?? `${t.kind} trigger`}` + return { subject: tgt, phrase, note: t.draft ? 'Draft trigger, created on save.' : draft } + } + case 'asset-flow': { + const via = (e.via ?? []).map(nameOf).join(', ') + const rerun = e.reactive + ? `Each write to ${src} reruns it.` + : `A write to ${src} does not rerun it.` + // The scripts that build nothing only read: name them, not the node. + if (isNoAssetNode(e.target)) { + return { subject: src, phrase: 'is read by', object: via || tgt, note: rerun } + } + return { + subject: tgt, + phrase: 'is built from', + object: src, + note: via ? `By ${via}. ${rerun}` : rerun + } + } + case 'dbt-ref': + return { subject: tgt, phrase: 'references', object: src, note: 'dbt ref().' } + case 'macro': + return { + subject: tgt, + phrase: e.via_use ? 'uses the macro library' : 'uses macros from', + object: src, + note: e.macro_names?.length ? e.macro_names.join(', ') : undefined + } + case 'test-dependency': + return { + subject: src, + phrase: 'must run before', + object: tgt, + note: 'Its data test reads what the first one builds.' + } + case 'data-test': + return { subject: tgt, phrase: 'tests', object: src } + default: + return undefined + } +} diff --git a/frontend/src/lib/components/assets/AssetGraph/graphTraversal.test.ts b/frontend/src/lib/components/assets/AssetGraph/graphTraversal.test.ts index 197d7eca6c..d6cf76c389 100644 --- a/frontend/src/lib/components/assets/AssetGraph/graphTraversal.test.ts +++ b/frontend/src/lib/components/assets/AssetGraph/graphTraversal.test.ts @@ -1,6 +1,8 @@ import { describe, expect, it } from 'vitest' import type { AssetGraphResponse } from './types' import { + hoverLineage, + transitivelyImpliedEdges, buildDownstreamMap, computeDownstreamClosure, computeInducedSchedule @@ -225,3 +227,44 @@ describe('computeInducedSchedule', () => { expect(sched.cyclic.sort()).toEqual(['b', 'c']) }) }) + +describe('hoverLineage', () => { + // a → b → c → d, with a side branch x → c and c → y; z is unrelated to b. + const edges = [ + { source: 'a', target: 'b' }, + { source: 'b', target: 'c' }, + { source: 'x', target: 'c' }, + { source: 'c', target: 'd' }, + { source: 'c', target: 'y' }, + { source: 'z', target: 'y' } + ] + + it('reaches everything upstream and downstream, recursively', () => { + const l = hoverLineage(edges, 'b') + expect([...l.upstream].sort()).toEqual(['a', 'b']) + expect([...l.downstream].sort()).toEqual(['b', 'c', 'd', 'y']) + }) + + it('keeps only the edges on a path through the node', () => { + const l = hoverLineage(edges, 'b') + expect(edges.filter(l.hasEdge)).toEqual([ + { source: 'a', target: 'b' }, + { source: 'b', target: 'c' }, + { source: 'c', target: 'd' }, + { source: 'c', target: 'y' } + ]) + }) +}) + +describe('transitivelyImpliedEdges', () => { + it('flags an edge another path already implies, and only that one', () => { + const edges = [ + { id: 'ab', source: 'a', target: 'b' }, + { id: 'bc', source: 'b', target: 'c' }, + { id: 'ac', source: 'a', target: 'c' }, + { id: 'ad', source: 'a', target: 'd' }, + { id: 'ad2', source: 'a', target: 'd' } + ] + expect([...transitivelyImpliedEdges(edges)]).toEqual(['ac']) + }) +}) diff --git a/frontend/src/lib/components/assets/AssetGraph/graphTraversal.ts b/frontend/src/lib/components/assets/AssetGraph/graphTraversal.ts index cc59e8f3a8..0c9fad6c83 100644 --- a/frontend/src/lib/components/assets/AssetGraph/graphTraversal.ts +++ b/frontend/src/lib/components/assets/AssetGraph/graphTraversal.ts @@ -226,3 +226,76 @@ export function computeInducedSchedule( const roots = ordered.filter((n) => (cleanIndegree.get(n) ?? 0) === 0) return { nodes: ordered, edges: cleanEdges, indegree: cleanIndegree, roots, cyclic } } + +/** What is linked to a node through the drawn graph: everything it depends on + * (upstream) and everything depending on it (downstream), both recursive, the + * node itself in each. An edge lies on a path through the node exactly when + * both its ends are upstream, or both downstream. */ +export type HoverLineage = { + upstream: Set<string> + downstream: Set<string> + hasEdge: (e: { source: string; target: string }) => boolean +} + +export function hoverLineage( + edges: ReadonlyArray<{ source: string; target: string }>, + id: string +): HoverLineage { + const walk = (from: 'source' | 'target', to: 'source' | 'target') => { + const next = new Map<string, string[]>() + for (const e of edges) next.set(e[from], [...(next.get(e[from]) ?? []), e[to]]) + const seen = new Set([id]) + const stack = [id] + while (stack.length) { + for (const n of next.get(stack.pop()!) ?? []) { + if (!seen.has(n)) { + seen.add(n) + stack.push(n) + } + } + } + return seen + } + const upstream = walk('target', 'source') + const downstream = walk('source', 'target') + return { + upstream, + downstream, + hasEdge: (e) => + (upstream.has(e.source) && upstream.has(e.target)) || + (downstream.has(e.source) && downstream.has(e.target)) + } +} + +/** Ids of the edges another path already implies: an edge A → C when C can be + * reached from A through at least one other node (A → B → … → C). Edges joining + * the same two nodes don't make each other redundant. */ +export function transitivelyImpliedEdges( + edges: ReadonlyArray<{ id: string; source: string; target: string }> +): Set<string> { + const next = new Map<string, Set<string>>() + for (const e of edges) { + if (e.source === e.target) continue + next.set(e.source, (next.get(e.source) ?? new Set()).add(e.target)) + } + // Whether `to` is reachable from `from` without taking the direct step. + const reachableAround = (from: string, to: string) => { + const seen = new Set<string>([from]) + const stack = [...(next.get(from) ?? [])].filter((n) => n !== to) + for (const n of stack) seen.add(n) + while (stack.length) { + const cur = stack.pop()! + for (const n of next.get(cur) ?? []) { + if (n === to) return true + if (!seen.has(n)) { + seen.add(n) + stack.push(n) + } + } + } + return false + } + const implied = new Set<string>() + for (const e of edges) if (e.source !== e.target && reachableAround(e.source, e.target)) implied.add(e.id) + return implied +} diff --git a/frontend/src/lib/components/assets/AssetGraph/onDirectiveTargets.test.ts b/frontend/src/lib/components/assets/AssetGraph/onDirectiveTargets.test.ts new file mode 100644 index 0000000000..bcd9a2c6fd --- /dev/null +++ b/frontend/src/lib/components/assets/AssetGraph/onDirectiveTargets.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from 'vitest' +import { onDirectiveTargets } from './onDirectiveTargets' + +describe('onDirectiveTargets', () => { + it('leaves out what the script feeds, directly or not, and what already triggers it', () => { + const nodes = [ + { id: 'script:a', type: 'runnable' }, + { id: 'script:b', type: 'runnable' }, + { id: 'asset:out', type: 'asset' }, + { id: 'asset:later', type: 'asset' }, + { id: 'asset:in', type: 'asset' }, + { id: 'asset:free', type: 'asset' } + ] + const edges = [ + { source: 'script:a', target: 'asset:out', kind: 'lineage-write' }, + { source: 'asset:out', target: 'script:b', kind: 'trigger-asset' }, + { source: 'script:b', target: 'asset:later', kind: 'lineage-write' }, + { source: 'asset:in', target: 'script:a', kind: 'trigger-asset' } + ] + expect([...onDirectiveTargets(nodes, edges, 'script:a')]).toEqual(['asset:free']) + }) +}) diff --git a/frontend/src/lib/components/assets/AssetGraph/onDirectiveTargets.ts b/frontend/src/lib/components/assets/AssetGraph/onDirectiveTargets.ts new file mode 100644 index 0000000000..4fc348dd51 --- /dev/null +++ b/frontend/src/lib/components/assets/AssetGraph/onDirectiveTargets.ts @@ -0,0 +1,34 @@ +/** + * The asset nodes a script can be subscribed to (`// on <asset>`) by dragging: + * every asset except those downstream of it, whose writes it would then run on + * in a loop, and those that already trigger it. + */ +export function onDirectiveTargets( + nodes: Array<{ id: string; type: string }>, + edges: Array<{ source: string; target: string; kind: string }>, + scriptId: string +): Set<string> { + const next = new Map<string, string[]>() + for (const e of edges) { + if (e.kind === 'add-anchor') continue + next.set(e.source, [...(next.get(e.source) ?? []), e.target]) + } + const downstream = new Set<string>([scriptId]) + const stack = [scriptId] + while (stack.length) { + for (const n of next.get(stack.pop()!) ?? []) { + if (!downstream.has(n)) { + downstream.add(n) + stack.push(n) + } + } + } + const triggering = new Set( + edges.filter((e) => e.kind === 'trigger-asset' && e.target === scriptId).map((e) => e.source) + ) + return new Set( + nodes + .filter((n) => n.type === 'asset' && !downstream.has(n.id) && !triggering.has(n.id)) + .map((n) => n.id) + ) +} diff --git a/frontend/src/lib/components/assets/AssetGraph/pipelineAiHelpers.test.ts b/frontend/src/lib/components/assets/AssetGraph/pipelineAiHelpers.test.ts index d1d5c1b233..713ef8f6b2 100644 --- a/frontend/src/lib/components/assets/AssetGraph/pipelineAiHelpers.test.ts +++ b/frontend/src/lib/components/assets/AssetGraph/pipelineAiHelpers.test.ts @@ -8,7 +8,8 @@ import type { AssetGraphResponse } from './types' function makeHandle( initial: Array<[string, PipelineDraft]> = [], runnables: Array<{ path: string }> = [], - folder = 'x' + folder = 'x', + triggers: unknown[] = [] ) { let drafts = new Map(initial) let forgotten: string[] = [] @@ -16,11 +17,13 @@ function makeHandle( getFolder: () => folder, getWorkspace: () => 'w', getResolvedGraph: () => - ({ assets: [], runnables, edges: [], triggers: [] }) as unknown as AssetGraphResponse, + ({ assets: [], runnables, edges: [], triggers }) as unknown as AssetGraphResponse, getDrafts: () => drafts, setDrafts: (next) => (drafts = next), newDraftLocalId: () => 'id', - onForgetPath: (p) => forgotten.push(p) + onForgetPath: (p) => forgotten.push(p), + getTriggerDrafts: () => new Map(), + setTriggerDraft: () => true }) return { handle, drafts: () => drafts, forgotten: () => forgotten } } @@ -155,6 +158,30 @@ describe('pipeline AI direct-draft helpers', () => { expect(res.detectedWrites).toEqual(['ducklake://main/out']) }) + // The canvas draws an inactive draft's stored outputs beside its materialize + // target, so a seeded default left on a materialize node shows a phantom asset. + it('keeps no seeded or stale output on a node with a materialize target', async () => { + vi.spyOn(ScriptService, 'getScriptByPath').mockRejectedValue(new Error('404')) + const { handle, drafts } = makeHandle() + await handle.proposeNode({ + path: 'f/x/mat', + language: 'duckdb' as any, + content: '-- pipeline\n-- materialize ducklake://main/abc\nSELECT 1', + outputKind: 'ducklake' as any + }) + expect(drafts().get('f/x/mat')?.outputAssets).toBeUndefined() + + await handle.proposeNode({ + path: 'f/x/later', + language: 'duckdb' as any, + content: '-- pipeline\nSELECT 1', + outputKind: 'ducklake' as any + }) + expect(drafts().get('f/x/later')?.outputAssets?.length).toBeGreaterThan(0) + await handle.editNode('f/x/later', '-- pipeline\n-- materialize ducklake://main/abc\nSELECT 1') + expect(drafts().get('f/x/later')?.outputAssets).toBeUndefined() + }) + it('editNode rejects a path outside the open folder', async () => { const { handle, drafts } = makeHandle() await expect(handle.editNode('f/other/foo', '-- pipeline')).rejects.toThrow(/open folder/) @@ -181,4 +208,24 @@ describe('pipeline AI direct-draft helpers', () => { expect(d?.script.tag).toBe('custom') expect(d?.script.content).toBe('-- pipeline\nSELECT 2') }) + + it("does not take a flow's schedule at the same path for the script's", async () => { + const flowSchedule = { + trigger_kind: 'schedule', + runnable_kind: 'flow', + runnable_path: 'f/x/ingest', + path: 'f/x/flow_schedule' + } + const content = '# pipeline\n# on schedule\ndef main():\n return 1' + const { handle } = makeHandle( + [['f/x/ingest', draft({ script: { content, language: 'python3' } as any })]], + [], + 'x', + [flowSchedule] + ) + expect(await handle.unconfiguredTriggers('f/x/ingest')).toEqual(['schedule']) + await expect( + handle.setNodeTrigger('f/x/ingest', 'schedule', { schedule: '0 0 6 * * *', timezone: 'UTC' }) + ).resolves.toMatchObject({ path: 'f/x/ingest_schedule' }) + }) }) diff --git a/frontend/src/lib/components/assets/AssetGraph/pipelineAiHelpers.ts b/frontend/src/lib/components/assets/AssetGraph/pipelineAiHelpers.ts index 5b22a098b1..f84848ee95 100644 --- a/frontend/src/lib/components/assets/AssetGraph/pipelineAiHelpers.ts +++ b/frontend/src/lib/components/assets/AssetGraph/pipelineAiHelpers.ts @@ -9,7 +9,12 @@ import { import { normalizePipelineFolder } from '$lib/utils/pipelineFolder' import { assetUri, autoOutputAsset, type PipelineOutputKind } from './pipelineTemplates' import { parsePipelineAnnotations, scd2CurrentTargetPath } from './parsePipelineAnnotations' -import type { AssetGraphResponse } from './types' +import type { + AssetGraphResponse, + PipelineTriggerDraft, + PipelineTriggerDraftKind +} from './types' +import { defaultTriggerPath, isDraftableTriggerKind, triggerDraftKey } from './pipelineTriggerDrafts' import type { PipelineAIChatHelpers, PipelineContext, @@ -62,20 +67,26 @@ export type PipelineAiHelperDeps = { onForgetPath?: (path: string) => void /** Notify the caller a test run started so it can light up its run UI. */ onRunStarted?: (jobId: string, path: string) => void + /** Whether the folder has trigger drafts, which live beside the script drafts. */ + hasTriggerDrafts?: () => boolean + getTriggerDrafts: () => Map<string, PipelineTriggerDraft> + /** False when another trigger draft already holds the config's path. */ + setTriggerDraft: (d: PipelineTriggerDraft, previousKey?: string) => boolean } export function makePipelineScript( language: ScriptLang, scriptPath: string, content: string, - createdAt: string + createdAt: string, + summary = '' ): Script { // Cast through unknown: a local draft only needs path/language/content/schema; // the many readonly deployment fields on Script don't matter until createScript. return { hash: '', path: scriptPath, - summary: '', + summary, description: '', content, schema: emptySchema(), @@ -199,7 +210,7 @@ export function createPipelineAiHelpers(deps: PipelineAiHelperDeps): PipelineAIC path: r.path, language: draft?.script.language, unsaved: r.unsaved ?? false, - summary: draft?.script.summary || undefined, + summary: (draft ? draft.script.summary : r.summary) || undefined, writes: [...new Set(writes)], reads: [...new Set(reads)], triggers: [...new Set(triggers)] @@ -213,7 +224,36 @@ export function createPipelineAiHelpers(deps: PipelineAiHelperDeps): PipelineAIC } } + // Declared `on <kind>` bindings of a node that a trigger row or draft fills. + // Webhook and data-upload need none, so they never count as unconfigured. + function unconfiguredTriggers(path: string, content: string): PipelineTriggerDraftKind[] { + const declared = parsePipelineAnnotations(content) + .nativeTriggers.map((n) => n.kind) + .filter(isDraftableTriggerKind) + const drafted = new Set( + [...deps.getTriggerDrafts().values()] + .filter((d) => d.config.script_path === path) + .map((d) => d.kind) + ) + const deployed = new Set( + deps + .getResolvedGraph() + .triggers.filter( + (t) => + t.trigger_kind !== 'asset' && + t.runnable_kind === 'script' && + t.runnable_path === path && + t.path && + !t.missing + ) + .map((t) => t.trigger_kind) + ) + return [...new Set(declared)].filter((k) => !drafted.has(k) && !deployed.has(k)) + } + const helpers: PipelineAIChatHelpers = { + getFolder: folderName, + hasDrafts: () => deps.getDrafts().size > 0 || (deps.hasTriggerDrafts?.() ?? false), getPipelineContext: buildContext, getNodeBody: async (path) => { const draft = deps.getDrafts().get(path) @@ -227,7 +267,7 @@ export function createPipelineAiHelpers(deps: PipelineAiHelperDeps): PipelineAIC return undefined } }, - proposeNode: async ({ path, language, content, outputKind }) => { + proposeNode: async ({ path, language, content, outputKind, summary }) => { deps.ensureEditable?.() // build_pipeline_node creates a NEW node in the OPEN folder. Reject a path // outside the folder (it would silently stage into this folder's bundle) @@ -267,10 +307,13 @@ export function createPipelineAiHelpers(deps: PipelineAiHelperDeps): PipelineAIC } const inferred = await inferDraftAssets(language, content) // Fall back to a seeded output (from the declared output_kind) when the - // body doesn't yet write anything inferable. + // body doesn't yet write anything inferable. A `materialize` target is the + // output already (the canvas adds it from the annotation): a seed beside it + // would show as a second, default-named output. + const materialized = materializeWrites(content).length > 0 const seeded = inferred.writes[0] ?? - (outputKind + (outputKind && !materialized ? autoOutputAsset(outputKind as PipelineOutputKind, folderName(), language) : undefined) // Effective outputs = what actually becomes an output edge on the canvas: @@ -280,7 +323,7 @@ export function createPipelineAiHelpers(deps: PipelineAiHelperDeps): PipelineAIC const next = new Map(drafts) next.set(path, { localId: deps.newDraftLocalId(), - script: makePipelineScript(language, path, content, new Date().toISOString()), + script: makePipelineScript(language, path, content, new Date().toISOString(), summary), outputAssets, inputAssets: inferred.reads }) @@ -298,7 +341,7 @@ export function createPipelineAiHelpers(deps: PipelineAiHelperDeps): PipelineAIC ) } }, - editNode: async (path, content) => { + editNode: async (path, content, summary) => { deps.ensureEditable?.() assertInFolder(path) assertPipelineAnnotation(content) @@ -319,11 +362,19 @@ export function createPipelineAiHelpers(deps: PipelineAiHelperDeps): PipelineAIC baseScript = await ScriptService.getScriptByPath({ workspace, path }) } const inferred = await inferDraftAssets(baseScript.language, content) - const outputAssets = inferred.writes.length > 0 ? inferred.writes : existing?.outputAssets + // The stored outputs only stand in for a body that writes nothing inferable; + // with a `materialize` target the annotation is the output, so stale ones + // (a seeded default name, the target before a rename) must not linger. + const outputAssets = + inferred.writes.length > 0 + ? inferred.writes + : materializeWrites(content).length > 0 + ? undefined + : existing?.outputAssets const next = new Map(drafts) next.set(path, { localId: existing?.localId ?? deps.newDraftLocalId(), - script: { ...baseScript, content }, + script: { ...baseScript, content, ...(summary !== undefined ? { summary } : {}) }, outputAssets, inputAssets: inferred.reads }) @@ -332,12 +383,61 @@ export function createPipelineAiHelpers(deps: PipelineAiHelperDeps): PipelineAIC deps.onProposeNode?.(path) // Deployable lineage only (see proposeNode): body writes + materialize target. return { + summary: summary ?? baseScript.summary ?? '', detectedReads: inferred.reads.map(assetUri), detectedWrites: dedupeAssets([...inferred.writes, ...materializeWrites(content)]).map( assetUri ) } }, + unconfiguredTriggers: async (path) => { + const body = await helpers.getNodeBody(path) + return body ? unconfiguredTriggers(path, body.content) : [] + }, + setNodeTrigger: async (path, kind, config) => { + deps.ensureEditable?.() + assertInFolder(path) + const body = await helpers.getNodeBody(path) + if (!body) throw new Error(`No pipeline node at '${path}'. Build it first.`) + const prefix = body.language === 'python3' || body.language === 'bash' ? '#' : body.language === 'duckdb' || body.language === 'postgresql' ? '--' : '//' + if (!parsePipelineAnnotations(body.content).nativeTriggers.some((n) => n.kind === kind)) { + throw new Error( + `'${path}' does not declare \`${prefix} on ${kind}\`. Add that annotation line with edit_pipeline_node first, so the trigger is wired to the node.` + ) + } + const row = deps + .getResolvedGraph() + .triggers.find( + (t) => + t.trigger_kind === kind && + t.runnable_kind === 'script' && + t.runnable_path === path && + t.path && + !t.missing && + !(t as { draft?: boolean }).draft + ) + if (row && 'path' in row) { + throw new Error( + `'${path}' already has a deployed ${kind} trigger at '${row.path}'. Change that one instead of adding a second.` + ) + } + const existing = [...deps.getTriggerDrafts().values()].find( + (d) => d.kind === kind && d.config.script_path === path + ) + const triggerPath = + (typeof config.path === 'string' && config.path) || + existing?.config.path || + defaultTriggerPath(path, kind) + const saved = deps.setTriggerDraft( + { kind, config: { ...config, path: triggerPath, script_path: path, is_flow: false } }, + existing ? triggerDraftKey(kind, existing.config.path) : undefined + ) + if (!saved) { + throw new Error(`Another draft trigger already uses the path '${triggerPath}'. Pass a different config.path.`) + } + deps.onShowDrafts?.() + return { path: triggerPath, replaced: !!existing } + }, removeProposedNode: async (path) => { if (!deps.getDrafts().has(path)) { throw new Error(`No unsaved draft at '${path}' to discard.`) diff --git a/frontend/src/lib/components/assets/AssetGraph/pipelineAnnotationEdits.test.ts b/frontend/src/lib/components/assets/AssetGraph/pipelineAnnotationEdits.test.ts new file mode 100644 index 0000000000..8759f114b4 --- /dev/null +++ b/frontend/src/lib/components/assets/AssetGraph/pipelineAnnotationEdits.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it } from 'vitest' +import { + addTriggerDirective, + listenToAsset, + removeTriggerDirective, + stopListeningToAsset +} from './pipelineAnnotationEdits' + +const table = { kind: 'datatable' as const, path: 'main/orders' } +const lake = { kind: 'ducklake' as const, path: 'main/orders' } + +describe('pipeline annotation edits', () => { + it('adds `on` at the end of the header, in its comment style, leaving the body', () => { + const sql = '-- pipeline\n-- materialize ducklake://main/x\nSELECT 1; -- on nothing' + expect(listenToAsset(sql, table, false)).toBe( + '-- pipeline\n-- materialize ducklake://main/x\n-- on datatable://main/orders\nSELECT 1; -- on nothing' + ) + }) + + it('adds `on` next to the existing `on` lines', () => { + const sql = '-- pipeline\n-- on schedule\n-- materialize ducklake://main/x\nSELECT 1;' + expect(listenToAsset(sql, table, false)).toBe( + '-- pipeline\n-- on schedule\n-- on datatable://main/orders\n-- materialize ducklake://main/x\nSELECT 1;' + ) + }) + + it('removes an `on` line however it is spelled, options included', () => { + const py = '# pipeline\n# on datatable://main/orders debounce=60s\nprint(1)' + expect(stopListeningToAsset(py, table, true)).toBe('# pipeline\nprint(1)') + }) + + it('unmutes an auto-triggering read rather than adding `on`, and mutes it to stop', () => { + const muted = '// pipeline\n// mute ducklake://main/orders\nexport function main() {}' + expect(listenToAsset(muted, lake, true)).toBe('// pipeline\nexport function main() {}') + expect(stopListeningToAsset('// pipeline\nexport function main() {}', lake, true)).toBe( + '// pipeline\n// mute ducklake://main/orders\nexport function main() {}' + ) + }) + + it('adds `on` for an auto-triggering kind the script does not read', () => { + expect(listenToAsset('-- pipeline\nSELECT 1;', lake, false)).toBe( + '-- pipeline\n-- on ducklake://main/orders\nSELECT 1;' + ) + }) + + it('mutes only an auto-triggering asset the script reads', () => { + const sub = '-- pipeline\n-- on ducklake://main/orders\nSELECT 1;' + expect(stopListeningToAsset(sub, lake, false)).toBe('-- pipeline\nSELECT 1;') + }) + + it('adds `on` for an auto-triggering kind when every read is muted', () => { + const all = '// pipeline\n// mute all\nexport function main() {}' + expect(listenToAsset(all, lake, true)).toBe( + '// pipeline\n// mute all\n// on ducklake://main/orders\nexport function main() {}' + ) + }) + + it('adds a trigger kind once, and drops it', () => { + expect(addTriggerDirective('// pipeline\n// on webhook\nx()', 'webhook')).toBe( + '// pipeline\n// on webhook\nx()' + ) + expect(removeTriggerDirective('// pipeline\n// on kafka\nx()', 'kafka')).toBe( + '// pipeline\nx()' + ) + }) +}) diff --git a/frontend/src/lib/components/assets/AssetGraph/pipelineAnnotationEdits.ts b/frontend/src/lib/components/assets/AssetGraph/pipelineAnnotationEdits.ts new file mode 100644 index 0000000000..70ab899412 --- /dev/null +++ b/frontend/src/lib/components/assets/AssetGraph/pipelineAnnotationEdits.ts @@ -0,0 +1,149 @@ +import type { AssetKind } from '$lib/gen' +import { parsePipelineAnnotations, type PipelineAnnotations } from './parsePipelineAnnotations' + +// Edits to a pipeline script's leading annotation header (`// on …`, `// mute …`), +// the comment block `parsePipelineAnnotations` reads. Lines are kept in the +// script's own comment style, and nothing past the header is touched. + +/** Asset kind → the prefix of its `// on <ref>` spelling. Mirrors ASSET_KINDS in + * backend/parsers/windmill-parser/src/asset_parser.rs. */ +export const ASSET_REF_PREFIX: Record<AssetKind, string> = { + s3object: 's3://', + resource: '$res:', + ducklake: 'ducklake://', + datatable: 'datatable://', + volume: 'volume://', + dbt: 'dbt://' +} + +// A `// pipeline` script reading one of these kinds runs after each write to it +// unless muted, with no `// on` line (see AUTO_TRIGGER_KINDS in resolveGraph). +const AUTO_TRIGGER_KINDS: ReadonlySet<AssetKind> = new Set(['ducklake', 's3object']) + +export function assetRef(asset: { kind: AssetKind; path: string }): string { + return `${ASSET_REF_PREFIX[asset.kind]}${asset.path}` +} + +const PREFIXES = ['//', '--', '#'] + +type HeaderLine = { index: number; prefix: string; inner: string } + +/** The header: leading comment lines (blank lines allowed), up to the first code. */ +function header(lines: string[]): HeaderLine[] { + const out: HeaderLine[] = [] + for (let i = 0; i < lines.length; i++) { + const t = lines[i].trimStart() + if (t === '') continue + const prefix = PREFIXES.find((p) => t.startsWith(p)) + if (!prefix) break + out.push({ index: i, prefix, inner: t.slice(prefix.length).trim() }) + } + return out +} + +// A header line matched the way the parser reads it, so `on <ref> debounce=60s`, +// `res://` vs `$res:` spellings and dbt path quoting all count as the same line. +type LineMatch = (parsed: PipelineAnnotations) => boolean +const onAsset = + (asset: { kind: AssetKind; path: string }): LineMatch => + (p) => + p.triggerAssets.some((a) => a.kind === asset.kind && a.path === asset.path) +const muteAsset = + (asset: { kind: AssetKind; path: string }): LineMatch => + (p) => + p.muteAssets.some((a) => a.kind === asset.kind && a.path === asset.path) +const muteAll: LineMatch = (p) => p.muteAll +const onTrigger = + (kind: string): LineMatch => + (p) => + p.nativeTriggers.some((t) => t.kind === kind) + +function matches(line: HeaderLine, match: LineMatch): boolean { + return match(parsePipelineAnnotations(`${line.prefix} ${line.inner}`)) +} + +function hasDirective(content: string, match: LineMatch): boolean { + return header(content.split('\n')).some((l) => matches(l, match)) +} + +/** Adds `<prefix> <directive>` in the header's comment style: after the last line + * of the same directive (`on`, `mute`), so they stay grouped, else at its end. */ +function addDirective(content: string, directive: string): string { + const lines = content.split('\n') + const h = header(lines) + const keyword = directive.split(/\s/)[0] + const sameKind = h.filter((l) => l.inner.split(/\s/)[0] === keyword) + const after = sameKind[sameKind.length - 1] ?? h[h.length - 1] + const line = `${after?.prefix ?? '//'} ${directive}` + lines.splice(after ? after.index + 1 : 0, 0, line) + return lines.join('\n') +} + +function removeDirective(content: string, match: LineMatch): string { + const lines = content.split('\n') + const drop = new Set( + header(lines) + .filter((l) => matches(l, match)) + .map((l) => l.index) + ) + return lines.filter((_, i) => !drop.has(i)).join('\n') +} + +/** The script runs after each write to the asset: `// on <ref>`, and any + * `// mute <ref>` lifted. An auto-triggering kind it `reads` needs no `// on` + * once unmuted, unless `// mute all` still silences it. */ +export function listenToAsset( + content: string, + asset: { kind: AssetKind; path: string }, + reads: boolean +): string { + const ref = assetRef(asset) + let out = removeDirective(content, muteAsset(asset)) + const auto = reads && AUTO_TRIGGER_KINDS.has(asset.kind) && !hasDirective(out, muteAll) + if (!auto && !hasDirective(out, onAsset(asset))) out = addDirective(out, `on ${ref}`) + return out +} + +/** The script no longer runs after writes to the asset: its `// on <ref>` goes, + * and an auto-triggering kind it `reads` is muted, since the read alone would + * still trigger it. */ +export function stopListeningToAsset( + content: string, + asset: { kind: AssetKind; path: string }, + reads: boolean +): string { + const ref = assetRef(asset) + let out = removeDirective(content, onAsset(asset)) + if (reads && AUTO_TRIGGER_KINDS.has(asset.kind) && !hasDirective(out, muteAsset(asset))) { + out = addDirective(out, `mute ${ref}`) + } + return out +} + +/** Adds a `// on <trigger kind>` line (`schedule`, `webhook`, …) unless it has one. */ +export function addTriggerDirective(content: string, kind: string): string { + return hasDirective(content, onTrigger(kind)) ? content : addDirective(content, `on ${kind}`) +} + +/** Drops a `// on <trigger kind>` line (`kafka`, `schedule`, …). */ +export function removeTriggerDirective(content: string, kind: string): string { + return removeDirective(content, onTrigger(kind)) +} + +/** What each edit says it changes, for the button that applies it. */ +export function listenChangeText( + asset: { kind: AssetKind; path: string }, + reads: boolean +): string { + return reads && AUTO_TRIGGER_KINDS.has(asset.kind) + ? `Removes any \`mute ${assetRef(asset)}\` line (adds \`on ${assetRef(asset)}\` if all reads are muted)` + : `Adds \`on ${assetRef(asset)}\`` +} +export function stopListeningChangeText( + asset: { kind: AssetKind; path: string }, + reads: boolean +): string { + return reads && AUTO_TRIGGER_KINDS.has(asset.kind) + ? `Removes \`on ${assetRef(asset)}\` and adds \`mute ${assetRef(asset)}\`` + : `Removes \`on ${assetRef(asset)}\`` +} diff --git a/frontend/src/lib/components/assets/AssetGraph/pipelineAssetPrefetch.svelte.ts b/frontend/src/lib/components/assets/AssetGraph/pipelineAssetPrefetch.svelte.ts new file mode 100644 index 0000000000..004c6ab8c1 --- /dev/null +++ b/frontend/src/lib/components/assets/AssetGraph/pipelineAssetPrefetch.svelte.ts @@ -0,0 +1,164 @@ +import { untrack } from 'svelte' +import { ScriptService, type AssetKind, type ScriptLang } from '$lib/gen' +import { inferAssets } from '$lib/infer' +import { + extractReads, + extractWrites, + type AssetWithAltAccessType +} from '$lib/components/assets/lib' +import { parsePipelineAnnotations } from './parsePipelineAnnotations' +import type { AssetGraphResponse, NativeTriggerKind } from './types' +import type { PipelineEditorState } from './pipelineEditorState.svelte' + +type AssetRef = { kind: AssetKind; path: string } + +/** + * Reads the body of every deployed script of a pipeline's graph and infers its + * asset reads/writes and `// on <native trigger>` annotations, so the canvas + * draws the edges of scripts the user never opened. The open script's live + * buffer wins over its cached body. + * + * The caches are only-add and keyed by path: the derived maps iterate the + * current graph's scripts, so a renamed or deleted script drops out when the + * graph refetches. A stale value under a live path does not, so a save through + * the editor must `forget` its path for the sweep to read it again. + */ +export function usePipelineAssetPrefetch(deps: { + getWorkspace: () => string | undefined + getGraph: () => AssetGraphResponse | undefined + editor: PipelineEditorState +}) { + const pe = deps.editor + let bodies = $state<Map<string, string>>(new Map()) + // Deployed summary + language from the same fetch, for node titles and icons. + let scriptMeta = $state<Map<string, { summary?: string; language: ScriptLang }>>(new Map()) + let inferredAssets = $state<Map<string, AssetWithAltAccessType[]>>(new Map()) + let prefetching = $state(false) + // Bumped by every sweep so one started for an older graph stops writing. + let gen = 0 + + $effect(() => { + const ws = deps.getWorkspace() + const g = deps.getGraph() + if (!ws || !g) return + const sweep = ++gen + const targets = untrack(() => + g.runnables + .filter((r) => r.usage_kind === 'script') + .map((r) => r.path) + .filter((p) => !pe.drafts.has(p) && !bodies.has(p)) + ) + if (targets.length === 0) return + let i = 0 + const POOL = 6 + const worker = async () => { + while (i < targets.length && sweep === gen) { + const path = targets[i++] + try { + const s = await ScriptService.getScriptByPath({ workspace: ws, path }) + if (sweep !== gen) return + const content = s.content ?? '' + const res = await inferAssets(s.language, content) + if (sweep !== gen) return + const inferred = (res?.assets ?? []) as AssetWithAltAccessType[] + untrack(() => { + if (!bodies.has(path)) bodies = new Map(bodies).set(path, content) + if (!scriptMeta.has(path)) { + scriptMeta = new Map(scriptMeta).set(path, { + summary: s.summary || undefined, + language: s.language + }) + } + if (!inferredAssets.has(path)) { + inferredAssets = new Map(inferredAssets).set(path, inferred) + } + }) + } catch { + // Skip — that node just falls back to base-graph edges. + } + } + } + prefetching = true + const pool = Array.from({ length: Math.min(POOL, targets.length) }, () => worker()) + void Promise.all(pool).then(() => { + if (sweep === gen) prefetching = false + }) + }) + + // Both edge maps in one pass over the graph's scripts; they only differ by + // extractWrites vs extractReads over the same source. + const edges = $derived.by(() => { + const writes = new Map<string, AssetRef[]>() + const reads = new Map<string, AssetRef[]>() + const g = deps.getGraph() + if (!g) return { writes, reads } + for (const r of g.runnables) { + if (r.usage_kind !== 'script') continue + const assets = + pe.liveBodyAssets.scriptPath === r.path + ? pe.liveBodyAssets.assets + : inferredAssets.get(r.path) + if (!assets) continue + const w = extractWrites(assets) + if (w.length > 0) writes.set(r.path, w) + const rd = extractReads(assets) + if (rd.length > 0) reads.set(r.path, rd) + } + return { writes, reads } + }) + + const annotatedNativeKinds = $derived.by(() => { + const out = new Map<string, Set<NativeTriggerKind>>() + const g = deps.getGraph() + if (!g) return out + const livePath = pe.liveAnnotations.scriptPath + for (const r of g.runnables) { + if (r.usage_kind !== 'script') continue + let kinds: Set<NativeTriggerKind> + if (r.path === livePath) { + kinds = new Set(pe.liveAnnotations.annotations.nativeTriggers.map((n) => n.kind)) + } else { + const body = bodies.get(r.path) + if (!body) continue + kinds = new Set(parsePipelineAnnotations(body).nativeTriggers.map((n) => n.kind)) + } + if (kinds.size > 0) out.set(r.path, kinds) + } + return out + }) + + return { + get bodies(): ReadonlyMap<string, string> { + return bodies + }, + get scriptMeta(): ReadonlyMap<string, { summary?: string; language: ScriptLang }> { + return scriptMeta + }, + get inferredWritesByPath() { + return edges.writes + }, + get inferredReadsByPath() { + return edges.reads + }, + get annotatedNativeKindsByPath() { + return annotatedNativeKinds + }, + get prefetching() { + return prefetching + }, + /** Drop cached paths so the next sweep re-reads them (after a save). */ + forget(...paths: string[]) { + const nextBodies = new Map(bodies) + const nextMeta = new Map(scriptMeta) + const nextInferred = new Map(inferredAssets) + for (const p of paths) { + nextBodies.delete(p) + nextMeta.delete(p) + nextInferred.delete(p) + } + bodies = nextBodies + scriptMeta = nextMeta + inferredAssets = nextInferred + } + } +} diff --git a/frontend/src/lib/components/assets/AssetGraph/pipelineDataUploads.svelte.ts b/frontend/src/lib/components/assets/AssetGraph/pipelineDataUploads.svelte.ts new file mode 100644 index 0000000000..8205b5f903 --- /dev/null +++ b/frontend/src/lib/components/assets/AssetGraph/pipelineDataUploads.svelte.ts @@ -0,0 +1,87 @@ +import { untrack } from 'svelte' +import type { AssetGraphResponse } from './types' + +type Staged = { args: Record<string, any>; valid: boolean } + +// An S3Object-shaped value (the file picker writes `{ s3: '<path>' }`). +function isS3Object(v: any): boolean { + return !!v && typeof v === 'object' && !Array.isArray(v) && 's3' in v +} + +// Whether a staged value carries actual data. Covers the two shapes a +// data-upload entry takes: an S3Object (file picker → `{ s3: '<path>' }`) and +// a plain required input (e.g. a JSON array pasted into the run form). +function hasMeaningfulValue(v: any): boolean { + if (v == null) return false + if (typeof v === 'string') return v.length > 0 + if (Array.isArray(v)) return v.length > 0 + if (typeof v === 'object') + return isS3Object(v) ? typeof v.s3 === 'string' && v.s3.length > 0 : Object.keys(v).length > 0 + return true // numbers / booleans count as provided +} + +/** + * Staged run-form input for the graph's data-upload entry scripts, keyed by path. + * Lifted out of the (transient, per-selection) run form so the uploaded/entered + * data persists across selection changes: it drives each entry node's green + * "ready" state and seeds a run with that input. `valid` is the run form's + * full-schema validity (all required fields satisfied). + */ +export function usePipelineDataUploads(getGraph: () => AssetGraphResponse) { + let staged = $state<Record<string, Staged>>({}) + + // Scripts that are data-upload entry points (a `data_upload` trigger in the + // displayed graph). They can't auto-run — they need their data first. + const entryPaths = $derived( + new Set( + getGraph() + .triggers.filter((t) => t.trigger_kind === 'data_upload' && t.runnable_kind === 'script') + .map((t) => t.runnable_path) + ) + ) + + // Ready once the user actually provided its data, not just opened the form. Two + // guards: the form's own full-schema `valid` (every required field — including + // non-file ones — is satisfied), AND that any declared S3Object file field + // actually carries a file (the picker can leave an empty `{ s3: '' }` on a + // non-required file field, which `valid` alone wouldn't catch). + function isReady(path: string): boolean { + const s = staged[path] + if (!s || !s.valid) return false + const values = Object.values(s.args) + const s3s = values.filter(isS3Object) + if (s3s.length > 0) return s3s.every(hasMeaningfulValue) + return values.some(hasMeaningfulValue) + } + + const readyPaths = $derived(new Set([...entryPaths].filter((p) => isReady(p)))) + + return { + get entryPaths(): ReadonlySet<string> { + return entryPaths + }, + /** Entry scripts with their data provided — drives the green node treatment. */ + get readyPaths(): ReadonlySet<string> { + return readyPaths + }, + isReady, + argsFor: (path: string): Record<string, any> | undefined => staged[path]?.args, + // Persist the run form's args + validity, but only for data-upload entries — + // other run forms (partitioned producers) run their own way and must not be + // mistaken for a staged upload. Idempotent: the run form re-emits on every + // keystroke/validation pass, so bail when the value is unchanged — otherwise + // each emit would reassign `staged`, giving `readyPaths` a fresh Set identity + // that re-syncs the canvas and re-fires the form's emit effect + // (effect_update_depth_exceeded). + // Called from the run forms' own effects, so its reads are untracked: a form + // must not re-run because the store it just wrote to changed. + stage: (path: string, args: Record<string, any>, valid: boolean) => + untrack(() => { + if (!entryPaths.has(path)) return + const prev = staged[path] + if (prev && prev.valid === valid && JSON.stringify(prev.args) === JSON.stringify(args)) + return + staged = { ...staged, [path]: { args, valid } } + }) + } +} diff --git a/frontend/src/lib/components/assets/AssetGraph/pipelineDelete.test.ts b/frontend/src/lib/components/assets/AssetGraph/pipelineDelete.test.ts new file mode 100644 index 0000000000..1e0c77aa70 --- /dev/null +++ b/frontend/src/lib/components/assets/AssetGraph/pipelineDelete.test.ts @@ -0,0 +1,52 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { DraftService, ScriptService } from '$lib/gen' +import { planPipelineDelete } from './pipelineDelete' + +afterEach(() => vi.restoreAllMocks()) + +describe('planPipelineDelete', () => { + it("takes only the pipeline's own triggers and addresses draft-only nodes by storage key", async () => { + vi.spyOn(ScriptService, 'listRunnables').mockResolvedValue({ + items: [ + { type: 'script', path: 'f/sales/ingest', auto_kind: 'pipeline' }, + { type: 'script', path: 'f/sales/report' }, + { + type: 'script', + path: 'u/alice/draft_abc', + draft_only: true, + draft_path: 'f/sales/unpublished', + auto_kind: 'pipeline' + } + ] + } as any) + vi.spyOn(DraftService, 'getOwnDraft').mockResolvedValue(undefined as any) + const trigger = (runnable_kind: string, runnable_path: string, path: string) => ({ + trigger_kind: 'schedule', + runnable_kind, + runnable_path, + path + }) + vi.stubGlobal( + 'fetch', + vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ + triggers: [ + trigger('script', 'f/sales/ingest', 'f/sales/ingest_schedule'), + trigger('script', 'f/sales/report', 'f/sales/report_schedule'), + trigger('flow', 'f/sales/ingest', 'f/sales/flow_schedule') + ] + }) + }) + ) + + const plan = await planPipelineDelete('w', 'sales') + + expect(plan.triggers).toEqual([{ kind: 'schedule', path: 'f/sales/ingest_schedule' }]) + expect(plan.scripts).toEqual([ + { path: 'f/sales/ingest', displayPath: 'f/sales/ingest', draftOnly: false }, + { path: 'u/alice/draft_abc', displayPath: 'f/sales/unpublished', draftOnly: true } + ]) + vi.unstubAllGlobals() + }) +}) diff --git a/frontend/src/lib/components/assets/AssetGraph/pipelineDelete.ts b/frontend/src/lib/components/assets/AssetGraph/pipelineDelete.ts new file mode 100644 index 0000000000..62e8e2ea4a --- /dev/null +++ b/frontend/src/lib/components/assets/AssetGraph/pipelineDelete.ts @@ -0,0 +1,135 @@ +import { DraftService, OpenAPI, ScriptService, type RunnableItem } from '$lib/gen' +import { discardDraft } from '$lib/utils_draft_deploy' +import { PIPELINE_DRAFT_KIND, pipelineBundlePath, pipelineLocalMirrorKey } from '$lib/pipelinePaths' +import { deleteTriggerRow } from './pipelineTriggerDraftDeploy' +import type { AssetGraphResponse, NativeTriggerKind } from './types' + +export type PipelineDeleteResult = { removed: number; failures: string[] } + +/** The folder's pipeline-member scripts, deployed and draft-only alike: every one of + * them makes the home list show the pipeline, so one left behind brings it back. */ +async function listPipelineScripts(workspace: string, folder: string): Promise<RunnableItem[]> { + const out: RunnableItem[] = [] + let cursor: string | undefined + do { + const res = await ScriptService.listRunnables({ + workspace, + kinds: 'script', + pathStart: `f/${folder}/`, + includeDraftOnly: true, + perPage: 100, + cursor + }) + out.push(...res.items.filter((it) => it.auto_kind === 'pipeline')) + cursor = res.next_cursor ?? undefined + } while (cursor) + return out +} + +/** Trigger rows starting one of `scripts`. The folder graph also carries the + * triggers of the folder's ordinary scripts and flows, which are not the pipeline's. */ +async function listNativeTriggers(workspace: string, folder: string, scripts: ReadonlySet<string>) { + const res = await fetch( + `${OpenAPI.BASE ?? ''}/w/${workspace}/assets/graph?${new URLSearchParams({ folder })}`, + { credentials: 'include' } + ) + if (!res.ok) throw new Error(`GET /assets/graph → ${res.status}`) + const graph = (await res.json()) as AssetGraphResponse + return graph.triggers.flatMap((t) => + t.trigger_kind !== 'asset' && + t.runnable_kind === 'script' && + scripts.has(t.runnable_path) && + t.trigger_kind !== 'webhook' && + t.trigger_kind !== 'data_upload' && + t.path && + !t.unsaved + ? [{ kind: t.trigger_kind, path: t.path }] + : [] + ) +} + +export type PipelineDeletePlan = { + /** `path` is what the API addresses (a draft-only node's storage key); + * `displayPath` is the path the user typed for it. */ + scripts: { path: string; displayPath: string; draftOnly: boolean }[] + triggers: { kind: NativeTriggerKind; path: string }[] + /** Whether the caller has an unsaved pipeline draft for this folder. */ + hasDraft: boolean +} + +/** Everything `deletePipeline` would remove, so it can be listed before it is. */ +export async function planPipelineDelete( + workspace: string, + folder: string +): Promise<PipelineDeletePlan> { + const scripts = await listPipelineScripts(workspace, folder) + const deployed = new Set(scripts.filter((s) => !s.draft_only).map((s) => s.path)) + const [triggers, draft] = await Promise.all([ + listNativeTriggers(workspace, folder, deployed), + DraftService.getOwnDraft({ + workspace, + kind: PIPELINE_DRAFT_KIND, + path: pipelineBundlePath(folder) + }).catch(() => undefined) + ]) + return { + scripts: scripts.map((s) => ({ + path: s.path, + displayPath: (s.draft_only && s.draft_path) || s.path, + draftOnly: !!s.draft_only + })), + triggers, + hasDraft: !!draft + } +} + +/** Removes what `plan` lists: the trigger rows, the scripts (deleted when + * `hardDelete`, which the backend allows admins only, archived otherwise; a + * draft-only node is discarded) and the caller's pipeline draft. The data the + * nodes wrote (DuckLake tables, S3 objects) is left alone. Triggers go first: a + * script refused afterwards loses its trigger, but no trigger outlives the script + * it starts. */ +export async function deletePipeline( + workspace: string, + folder: string, + plan: PipelineDeletePlan, + hardDelete: boolean +): Promise<PipelineDeleteResult> { + const failures: string[] = [] + let removed = 0 + const fail = (what: string, e: any) => + failures.push(`${what}: ${e?.body ?? e?.message ?? String(e)}`) + + for (const t of plan.triggers) { + try { + if (await deleteTriggerRow(t.kind, t.path, workspace)) removed++ + } catch (e) { + fail(`${t.kind} trigger ${t.path}`, e) + } + } + for (const s of plan.scripts) { + try { + if (s.draftOnly) { + const r = await discardDraft('script', s.path, workspace, true, false, false) + if (!r.success) throw new Error(r.error) + } else if (hardDelete) { + await ScriptService.deleteScriptByPath({ workspace, path: s.path }) + } else { + await ScriptService.archiveScriptByPath({ workspace, path: s.path }) + } + removed++ + } catch (e) { + fail(s.displayPath, e) + } + } + if (plan.hasDraft) { + const bundle = await discardDraft(PIPELINE_DRAFT_KIND, pipelineBundlePath(folder), workspace, true) + if (!bundle.success) failures.push(`pipeline draft: ${bundle.error}`) + } + try { + localStorage.removeItem(pipelineLocalMirrorKey(folder)) + } catch { + // Storage unavailable: nothing was mirrored either. + } + return { removed, failures } +} diff --git a/frontend/src/lib/components/assets/AssetGraph/pipelineDeploy.svelte.ts b/frontend/src/lib/components/assets/AssetGraph/pipelineDeploy.svelte.ts new file mode 100644 index 0000000000..508b705e11 --- /dev/null +++ b/frontend/src/lib/components/assets/AssetGraph/pipelineDeploy.svelte.ts @@ -0,0 +1,230 @@ +import { DraftService, ScriptService, type Script } from '$lib/gen' +import { PIPELINE_DRAFT_KIND, pipelineBundlePath } from '$lib/pipelinePaths' +import type { PipelineTriggerDraft } from './types' +import type { Schema } from '$lib/common' +import { emptySchema } from '$lib/utils' +import { inferArgs, inferAssets } from '$lib/infer' +import type { AssetWithAltAccessType } from '$lib/components/assets/lib' +import type { PipelineDraft } from './pipelineAiHelpers' +import type { PipelineEditorState } from './pipelineEditorState.svelte' +import { deployTriggerDraft } from './pipelineTriggerDraftDeploy' + +// Deploying a pipeline's drafts: the scripts first, then the trigger drafts whose +// script is now deployed. Shared by the pipeline page's "Save all" and the AI +// session's "Deploy pipeline", so both deploy exactly the same way. + +/** Deploy one pipeline script draft; resolves to the new version's hash. */ +export async function deployPipelineScript( + draft: PipelineDraft, + workspace: string +): Promise<string> { + const script = structuredClone($state.snapshot(draft.script) as Script) + script.schema = script.schema ?? emptySchema() + try { + const result = await inferArgs(script.language, script.content, script.schema as Schema) + ;(script as any).auto_kind = result?.auto_kind || undefined + script.has_preprocessor = result?.has_preprocessor ?? false + } catch { + // Inference failures don't block deploys (the same fallback the per-pane + // save uses): createScript is the real validation gate. + } + // Re-infer the lineage from the CURRENT body. `script.assets` is a snapshot + // that isn't refreshed on edit, so a renamed/removed output would otherwise be + // re-deployed as a phantom write edge. + let assets: AssetWithAltAccessType[] = [] + try { + const inferred = await inferAssets(script.language, script.content) + if (inferred?.status !== 'error') assets = (inferred?.assets ?? []) as AssetWithAltAccessType[] + } catch { + // An unparsable body deploys with no lineage rather than the stale snapshot. + } + return await ScriptService.createScript({ + workspace, + requestBody: { + ...script, + language: script.language, + description: script.description ?? '', + // A brand-new draft has an empty hash (the backend rejects an empty hex + // string); a draft of a deployed script chains off its hash, since + // createScript rejects a parentless deploy to an occupied path. + parent_hash: script.hash ? String(script.hash) : undefined, + is_template: false, + tag: script.tag, + kind: script.kind as Script['kind'] | undefined, + lock: undefined, + assets: assets as any + } + }) +} + +// Every field a deploy sends: a draft differing from the live script in any of +// them still has something to deploy. +const DEPLOYED_FIELDS = [ + 'content', + 'language', + 'summary', + 'description', + 'tag', + 'kind', + 'labels' +] as const + +/** Whether two versions of a script agree on everything a deploy sends. */ +function sameDeployedFields(a: Partial<Script>, b: Partial<Script>): boolean { + const norm = (v: unknown) => JSON.stringify(Array.isArray(v) && v.length === 0 ? null : (v ?? null)) + return DEPLOYED_FIELDS.every( + (f) => + norm(f === 'description' ? (a[f] ?? '') : a[f]) === + norm(f === 'description' ? (b[f] ?? '') : b[f]) + ) +} + +/** Whether a draft equals the live script at its path, i.e. has nothing to deploy. */ +export async function matchesDeployedScript( + path: string, + d: PipelineDraft, + workspace: string +): Promise<boolean> { + try { + const live = await ScriptService.getScriptByPath({ workspace, path }) + return sameDeployedFields(live, d.script) + } catch { + return false + } +} + +/** + * A folder's draft bundle against what is deployed, one entry per node (and the + * trigger drafts), for a diff viewer: the unit a session reviews and deploys. + */ +export async function loadPipelineDraftDiff( + workspace: string, + folder: string +): Promise<{ before: unknown; after: unknown }> { + const row = await DraftService.getOwnDraft({ + workspace, + kind: PIPELINE_DRAFT_KIND, + path: pipelineBundlePath(folder) + }).catch(() => undefined) + const bundle = (row?.value ?? {}) as { + drafts?: Array<[string, PipelineDraft]> + triggerDrafts?: PipelineTriggerDraft[] + } + const drafts = Array.isArray(bundle.drafts) ? bundle.drafts : [] + const before: Record<string, string> = {} + const after: Record<string, string> = {} + await Promise.all( + drafts.map(async ([path, d]) => { + after[path] = d.script?.content ?? '' + const live = await ScriptService.getScriptByPath({ workspace, path }).catch(() => undefined) + if (live) before[path] = live.content + }) + ) + const triggers = (bundle.triggerDrafts ?? []).map((t) => ({ + kind: t.kind, + path: t.config.path, + script_path: t.config.script_path + })) + return { + before: { nodes: before }, + after: { nodes: after, ...(triggers.length > 0 ? { new_triggers: triggers } : {}) } + } +} + +export type PipelineDeployOutcome = { + savedPaths: string[] + /** Keys of the trigger drafts that deployed. */ + savedTriggers: string[] + /** Failures by script or trigger path. */ + errors: Map<string, string> +} + +/** + * Deploy every draft of `editor` into `workspace`, dropping from it what deployed: + * failed drafts stay so they can be fixed and retried. The open pane's unsaved + * keystrokes are deployed with their draft. + */ +export async function deployPipelineDrafts( + editor: PipelineEditorState, + workspace: string +): Promise<PipelineDeployOutcome> { + // Closing the pane lands an open deployed script's edits as its draft, so they + // deploy too. It reopens on that script once the deploy is done, unless another + // one was opened meanwhile. + const reopen = + editor.liveEditPath != undefined || editor.activeDraftPath != undefined + ? await editor.closePane() + : undefined + const entries = [...editor.drafts.entries()] + const errors = new Map<string, string>() + const savedPaths: string[] = [] + const hashes = new Map<string, string>() + // Parallel: every createScript is independent, and one bad body must not block + // the others. + const results = await Promise.allSettled( + entries.map(([, d]) => deployPipelineScript(d, workspace)) + ) + for (let i = 0; i < results.length; i++) { + const r = results[i] + const [path, d] = entries[i] + if (r.status === 'fulfilled') { + savedPaths.push(path) + if (r.value) hashes.set(path, r.value) + continue + } + // A refused draft that equals the deployed script has nothing left to deploy. + // A duplicate refusal alone does not prove it: it is checked against every + // past version, not just the live one. + if (await matchesDeployedScript(path, d, workspace)) { + savedPaths.push(path) + continue + } + const msg = String((r.reason as any)?.body ?? (r.reason as any)?.message ?? r.reason) + errors.set( + path, + /same hash/i.test(msg) + ? 'This is the content of an earlier version, which cannot be deployed again as is. Change anything in it (a comment will do) to deploy it.' + : msg + ) + } + + // A trigger's `script_path` must already exist, so triggers whose script is + // still an undeployed draft stay drafts. + const ready = [...editor.triggerDrafts].filter( + ([, d]) => !editor.drafts.has(d.config.script_path) || savedPaths.includes(d.config.script_path) + ) + const triggerResults = await Promise.all(ready.map(([, d]) => deployTriggerDraft(d, workspace))) + const savedTriggers: string[] = [] + triggerResults.forEach((ok, i) => { + const [key, d] = ready[i] + if (ok) savedTriggers.push(key) + else errors.set(d.config.path, `Could not create the ${d.kind} trigger, see the notification`) + }) + for (const key of savedTriggers) editor.discardTriggerDraft(key) + + if (savedPaths.length > 0) { + // A draft edited again while it deployed (its node reopened from the canvas) + // keeps the newer edits, now on top of the version just deployed; only a draft + // still holding exactly what was sent is done. + const sent = new Map(entries.map(([p, d]) => [p, d.script])) + const next = new Map<string, PipelineDraft>() + for (const [k, d] of editor.drafts) { + if (!savedPaths.includes(k)) { + next.set(k, d) + continue + } + const open = editor.liveContent.scriptPath === k ? editor.liveContent.content : undefined + const now = open === undefined ? d.script : { ...d.script, content: open } + const was = sent.get(k) + if (was && sameDeployedFields(now, was)) continue + const hash = hashes.get(k) + next.set(k, hash ? { ...d, script: { ...d.script, hash } } : d) + } + editor.drafts = next + } + if (reopen && editor.activeDraftPath === undefined && editor.selection === undefined) { + if (editor.drafts.has(reopen)) editor.activeDraftPath = reopen + else editor.selection = { kind: 'runnable', runnable_kind: 'script', path: reopen } + } + return { savedPaths, savedTriggers, errors } +} diff --git a/frontend/src/lib/components/assets/AssetGraph/pipelineDeploy.test.ts b/frontend/src/lib/components/assets/AssetGraph/pipelineDeploy.test.ts new file mode 100644 index 0000000000..53df48717a --- /dev/null +++ b/frontend/src/lib/components/assets/AssetGraph/pipelineDeploy.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it, vi } from 'vitest' + +const createScript = vi.fn() +vi.mock('$lib/gen', () => ({ + ScriptService: { createScript: (a: unknown) => createScript(a) }, + DraftService: {} +})) +vi.mock('$lib/infer', () => ({ + inferArgs: async () => undefined, + inferAssets: async () => ({ status: 'ok', assets: [] }) +})) +vi.mock('./pipelineTriggerDraftDeploy', () => ({ deployTriggerDraft: async () => true })) + +const { deployPipelineDrafts } = await import('./pipelineDeploy.svelte') +const { PipelineEditorState } = await import('./pipelineEditorState.svelte') + +const draft = (content: string) => ({ + localId: 'pe-1', + script: { path: 'f/x/n', language: 'duckdb', content, hash: 'aaaa' } as any +}) + +describe('deployPipelineDrafts', () => { + it('drops a draft once what it holds is deployed', async () => { + const pe = new PipelineEditorState() + pe.drafts = new Map([['f/x/n', draft('SELECT 2')]]) + createScript.mockResolvedValueOnce('bbbb') + await deployPipelineDrafts(pe, 'ws') + expect(pe.drafts.has('f/x/n')).toBe(false) + }) + + it('keeps edits made while the deploy was in flight, on top of the new version', async () => { + const pe = new PipelineEditorState() + pe.drafts = new Map([['f/x/n', draft('SELECT 2')]]) + createScript.mockImplementationOnce(async () => { + pe.drafts = new Map([['f/x/n', draft('SELECT 3')]]) + return 'bbbb' + }) + await deployPipelineDrafts(pe, 'ws') + expect(pe.drafts.get('f/x/n')?.script.content).toBe('SELECT 3') + expect(pe.drafts.get('f/x/n')?.script.hash).toBe('bbbb') + }) +}) + +describe('deployPipelineDrafts metadata', () => { + it('keeps a summary edited while the deploy was in flight', async () => { + const pe = new PipelineEditorState() + pe.drafts = new Map([['f/x/n', draft('SELECT 2')]]) + createScript.mockImplementationOnce(async () => { + const d = draft('SELECT 2') + pe.drafts = new Map([['f/x/n', { ...d, script: { ...d.script, summary: 'Renamed' } }]]) + return 'bbbb' + }) + await deployPipelineDrafts(pe, 'ws') + expect(pe.drafts.get('f/x/n')?.script.summary).toBe('Renamed') + }) +}) diff --git a/frontend/src/lib/components/assets/AssetGraph/pipelineEditorState.svelte.ts b/frontend/src/lib/components/assets/AssetGraph/pipelineEditorState.svelte.ts index 086abc1bf8..6f9a109f5f 100644 --- a/frontend/src/lib/components/assets/AssetGraph/pipelineEditorState.svelte.ts +++ b/frontend/src/lib/components/assets/AssetGraph/pipelineEditorState.svelte.ts @@ -1,6 +1,8 @@ +import { tick } from 'svelte' import type { AssetKind, Script } from '$lib/gen' import type { AssetWithAltAccessType } from '$lib/components/assets/lib' -import type { AssetGraphSelection } from './types' +import type { AssetGraphSelection, PipelineTriggerDraft } from './types' +import { defaultTriggerPath, triggerDraftKey } from './pipelineTriggerDrafts' import { parsePipelineAnnotations, type ColumnLineage, @@ -26,11 +28,18 @@ type LiveBodyAssets = { assets: AssetWithAltAccessType[] columnLineage?: ColumnLineage[] } -type LiveContent = { scriptPath: string | undefined; content: string } +type LiveContent = { + scriptPath: string | undefined + content: string + /** The deployed script the buffer was opened from; unset for a draft. */ + base?: Script +} export class PipelineEditorState { /** In-flight drafts keyed by script path (manual + AI-staged). */ drafts = $state<Map<string, PipelineDraft>>(new Map()) + /** Undeployed triggers keyed by `triggerDraftKey`, persisted in the same bundle. */ + triggerDrafts = $state<Map<string, PipelineTriggerDraft>>(new Map()) /** Draft open in the details pane (mutually exclusive with `selection`). */ activeDraftPath = $state<string | undefined>(undefined) /** The persisted node/asset selected on the canvas. */ @@ -51,23 +60,22 @@ export class PipelineEditorState { * autosave hydrate when persistence is enabled. */ loadedFromDbDraft = $state(false) - /** Folder this state is scoped to. Used by the in-session preview (where one - * instance is reused across editor hide/show) to detect a retarget to a - * different folder and reset, so stale drafts don't bleed across folders. */ + /** Folder this state is scoped to. The route page compares it on a folder + * switch and resets, so one folder's drafts don't bleed into the next. */ folder = $state<string | undefined>(undefined) /** True once the DB draft bundle for the current folder has been hydrated - * into this instance. Gated per-instance (not per component mount) so the - * in-session preview hydrates ONCE when its runtime is fresh and then keeps - * the in-memory drafts across editor hide/show — re-reading the DB on every - * remount would race a not-yet-flushed autosave and drop a just-staged draft. - * Reset to false on a folder retarget so the new folder re-hydrates. */ + * into this instance. Gated per-instance (not per component mount) so an AI + * session's folder hydrates ONCE and then keeps its in-memory drafts across + * editor remounts — re-reading the DB on every remount would race a + * not-yet-flushed autosave and drop a just-staged draft. `reset` clears it + * so a new folder re-hydrates. */ hydratedFromDb = $state(false) - /** Clear all in-flight state. Used when the session preview retargets a - * different pipeline folder (a same-folder remount keeps the drafts). */ + /** Clear all in-flight state, for the route page switching folders. */ reset = () => { this.drafts = new Map() + this.triggerDrafts = new Map() this.activeDraftPath = undefined this.selection = undefined this.clearLiveOverlays() @@ -84,6 +92,18 @@ export class PipelineEditorState { return `pe-${this.#nextDraftLocalId}` } + // A deployed script with unsaved edits is autosaved as a draft before the pane + // promotes it, so both must give it the same id. + #promotedLocalIds = new Map<string, string>() + promotedDraftLocalId = (path: string): string => { + let id = this.#promotedLocalIds.get(path) + if (!id) { + id = this.newDraftLocalId() + this.#promotedLocalIds.set(path, id) + } + return id + } + handleAnnotationsChange = (scriptPath: string | undefined, annotations: PipelineAnnotations) => { this.liveAnnotations = { scriptPath, annotations } } @@ -94,8 +114,34 @@ export class PipelineEditorState { ) => { this.liveBodyAssets = { scriptPath, assets, columnLineage } } - handleContentChange = (scriptPath: string | undefined, content: string) => { - this.liveContent = { scriptPath, content } + handleContentChange = (scriptPath: string | undefined, content: string, base?: Script) => { + this.liveContent = { scriptPath, content, base } + } + + /** The open deployed script's unsaved edits, which live only in `liveContent` + * until its pane closes: the path, or undefined when there are none. */ + get liveEditPath(): string | undefined { + const { scriptPath, content, base } = this.liveContent + if (scriptPath == undefined || !base || this.drafts.has(scriptPath)) return undefined + return content !== (base.content ?? '') ? scriptPath : undefined + } + + /** Closes the open pane and waits for its edits to land as a draft, as closing + * it by hand does: what is deployed or discarded next then includes them, and + * no pane is left holding a stale copy. Returns the path the pane was on. */ + closePane = async (): Promise<string | undefined> => { + const path = + this.activeDraftPath ?? (this.selection?.kind === 'runnable' ? this.selection.path : undefined) + if (this.activeDraftPath === undefined && this.selection === undefined) return undefined + this.activeDraftPath = undefined + this.selection = undefined + // The pane unmounts on the next flush; its save-back commits a microtask later. + await tick() + await new Promise<void>((resolve) => queueMicrotask(resolve)) + // Its buffer now lives in the draft; left here, autosave would serialize it + // again once that draft is deployed or discarded. + this.clearLiveOverlays() + return path } clearLiveOverlays = () => { @@ -125,6 +171,72 @@ export class PipelineEditorState { next.delete(path) this.drafts = next this.forgetPath(path) + this.discardTriggerDraftsFor(path) + } + + /** Summary and labels of a script draft, edited from the pane header. */ + setDraftMeta = (path: string, meta: { summary: string; labels: string[] | undefined }) => { + const d = this.drafts.get(path) + if (!d) return + this.drafts = new Map(this.drafts).set(path, { + ...d, + script: { ...d.script, summary: meta.summary, labels: meta.labels } + }) + } + + /** Add or replace a trigger draft; `previousKey` is the entry being edited, which + * a rename drops. False, and nothing changes, when the path is another draft's: + * both would deploy to one trigger. */ + setTriggerDraft = (d: PipelineTriggerDraft, previousKey?: string): boolean => { + const key = triggerDraftKey(d.kind, d.config.path) + if (key !== previousKey && this.triggerDrafts.has(key)) return false + const next = new Map(this.triggerDrafts) + if (previousKey) next.delete(previousKey) + next.set(key, d) + this.triggerDrafts = next + return true + } + + discardTriggerDraft = (key: string) => { + if (!this.triggerDrafts.has(key)) return + const next = new Map(this.triggerDrafts) + next.delete(key) + this.triggerDrafts = next + } + + /** A trigger draft cannot outlive the script draft it was configured with: + * deploying it would target a path nothing is deployed at. */ + discardTriggerDraftsFor = (scriptPath: string) => { + const next = new Map( + [...this.triggerDrafts].filter(([, d]) => d.config.script_path !== scriptPath) + ) + if (next.size !== this.triggerDrafts.size) this.triggerDrafts = next + } + + /** Follow a script draft rename, keeping default `<script>_<kind>` names in step. */ + /** Returns the trigger path another draft already holds, and changes nothing, + * when a renamed default name would land on it. */ + retargetTriggerDrafts = (oldScriptPath: string, newScriptPath: string): string | undefined => { + const moved = new Map<string, PipelineTriggerDraft>() + const kept = new Map<string, PipelineTriggerDraft>() + for (const [k, d] of this.triggerDrafts) { + if (d.config.script_path !== oldScriptPath) { + kept.set(k, d) + continue + } + const path = + d.config.path === defaultTriggerPath(oldScriptPath, d.kind) + ? defaultTriggerPath(newScriptPath, d.kind) + : d.config.path + moved.set(triggerDraftKey(d.kind, path), { + ...d, + config: { ...d.config, path, script_path: newScriptPath } + }) + } + if (moved.size === 0) return undefined + for (const [k, d] of moved) if (kept.has(k)) return d.config.path + this.triggerDrafts = new Map([...kept, ...moved]) + return undefined } /** Commit body edits + inferred outputs back into the drafts Map on pane @@ -147,7 +259,7 @@ export class PipelineEditorState { if (!snapshot.script) return const next = new Map(this.drafts) next.set(p, { - localId: this.newDraftLocalId(), + localId: this.promotedDraftLocalId(p), script: snapshot.script, outputAssets: snapshot.writes.length > 0 ? snapshot.writes : undefined, inputAssets: snapshot.reads diff --git a/frontend/src/lib/components/assets/AssetGraph/pipelineEditorState.test.ts b/frontend/src/lib/components/assets/AssetGraph/pipelineEditorState.test.ts index 2ec06bc8cc..09cec13a37 100644 --- a/frontend/src/lib/components/assets/AssetGraph/pipelineEditorState.test.ts +++ b/frontend/src/lib/components/assets/AssetGraph/pipelineEditorState.test.ts @@ -104,3 +104,72 @@ describe('PipelineEditorState.handleDraftPersist — read capture', () => { expect(pe.drafts.get('f/x/n')?.inputAssets).toBeUndefined() }) }) + +describe('PipelineEditorState trigger drafts', () => { + it('follow their script draft: renamed with it, discarded with it', () => { + const pe = new PipelineEditorState() + pe.drafts = new Map([['f/x/n', draft('SELECT 1')]]) + pe.setTriggerDraft({ kind: 'kafka', config: { path: 'f/x/n_kafka', script_path: 'f/x/n' } }) + pe.setTriggerDraft({ kind: 'schedule', config: { path: 'f/x/nightly', script_path: 'f/x/n' } }) + + pe.retargetTriggerDrafts('f/x/n', 'f/x/m') + // A default `<script>_<kind>` name follows the script; a chosen one stays. + expect([...pe.triggerDrafts.keys()].sort()).toEqual([ + 'kafka:f/x/m_kafka', + 'schedule:f/x/nightly' + ]) + expect([...pe.triggerDrafts.values()].every((d) => d.config.script_path === 'f/x/m')).toBe(true) + + pe.drafts = new Map([['f/x/m', draft('SELECT 1')]]) + pe.discardDraft('f/x/m') + expect(pe.triggerDrafts.size).toBe(0) + }) + + it('refuse a path another draft holds, but let a draft keep its own', () => { + const pe = new PipelineEditorState() + const a = { kind: 'kafka' as const, config: { path: 'f/x/k', script_path: 'f/x/a' } } + expect(pe.setTriggerDraft(a)).toBe(true) + expect( + pe.setTriggerDraft({ kind: 'kafka', config: { path: 'f/x/k', script_path: 'f/x/b' } }) + ).toBe(false) + expect(pe.triggerDrafts.get('kafka:f/x/k')?.config.script_path).toBe('f/x/a') + expect(pe.setTriggerDraft({ ...a, config: { ...a.config, topics: ['t'] } }, 'kafka:f/x/k')).toBe( + true + ) + }) + + it('refuse a script rename that moves a default name onto another draft', () => { + const pe = new PipelineEditorState() + pe.setTriggerDraft({ kind: 'kafka', config: { path: 'f/x/a_kafka', script_path: 'f/x/a' } }) + pe.setTriggerDraft({ kind: 'kafka', config: { path: 'f/x/b_kafka', script_path: 'f/x/c' } }) + expect(pe.retargetTriggerDrafts('f/x/a', 'f/x/b')).toBe('f/x/b_kafka') + expect([...pe.triggerDrafts.keys()].sort()).toEqual(['kafka:f/x/a_kafka', 'kafka:f/x/b_kafka']) + }) +}) + +describe('PipelineEditorState.liveEditPath', () => { + const base = { path: 'f/x/n', language: 'duckdb', content: 'SELECT 1' } as PipelineDraft['script'] + + it('counts an open deployed script with unsaved edits, until it has a draft', () => { + const pe = new PipelineEditorState() + pe.liveContent = { scriptPath: 'f/x/n', content: 'SELECT 1', base } + expect(pe.liveEditPath).toBeUndefined() + pe.liveContent = { scriptPath: 'f/x/n', content: 'SELECT 2', base } + expect(pe.liveEditPath).toBe('f/x/n') + pe.drafts = new Map([['f/x/n', draft('SELECT 2')]]) + expect(pe.liveEditPath).toBeUndefined() + }) +}) + +describe('PipelineEditorState.closePane', () => { + it("leaves no open buffer behind for autosave to bring back once the draft is gone", async () => { + const pe = new PipelineEditorState() + const base = { path: 'f/x/n', language: 'duckdb', content: 'SELECT 1' } as PipelineDraft['script'] + pe.selection = { kind: 'runnable', runnable_kind: 'script', path: 'f/x/n' } + pe.liveContent = { scriptPath: 'f/x/n', content: 'SELECT 2', base } + expect(await pe.closePane()).toBe('f/x/n') + expect(pe.selection).toBeUndefined() + expect(pe.liveEditPath).toBeUndefined() + expect(pe.liveContent.scriptPath).toBeUndefined() + }) +}) diff --git a/frontend/src/lib/components/assets/AssetGraph/pipelineLanguages.ts b/frontend/src/lib/components/assets/AssetGraph/pipelineLanguages.ts index 26d3e24d84..b50491620f 100644 --- a/frontend/src/lib/components/assets/AssetGraph/pipelineLanguages.ts +++ b/frontend/src/lib/components/assets/AssetGraph/pipelineLanguages.ts @@ -4,7 +4,7 @@ import type { ScriptLang } from '$lib/gen' // actually reach for first: duckdb for in-place SQL on parquet/s3 (the // default), bun for ergonomic data wrangling, python for ML/pandas, then // the sql dialects for warehouse-resident transforms. Everything else -// (bash/go/deno) sits below — still creatable, just not the default +// (bash/go) sits below — still creatable, just not the default // suggestion. export const PIPELINE_LANGUAGES: Array<{ label: string; lang: ScriptLang }> = [ { label: 'DuckDB', lang: 'duckdb' }, @@ -16,6 +16,5 @@ export const PIPELINE_LANGUAGES: Array<{ label: string; lang: ScriptLang }> = [ { label: 'MySQL', lang: 'mysql' }, { label: 'MS SQL', lang: 'mssql' }, { label: 'Bash', lang: 'bash' }, - { label: 'Go', lang: 'go' }, - { label: 'Deno', lang: 'deno' } + { label: 'Go', lang: 'go' } ] diff --git a/frontend/src/lib/components/assets/AssetGraph/pipelineTriggerDraftDeploy.ts b/frontend/src/lib/components/assets/AssetGraph/pipelineTriggerDraftDeploy.ts new file mode 100644 index 0000000000..3b37ac43a5 --- /dev/null +++ b/frontend/src/lib/components/assets/AssetGraph/pipelineTriggerDraftDeploy.ts @@ -0,0 +1,89 @@ +import { usedTriggerKinds } from '$lib/stores' +import { formatCron } from '$lib/utils' +import { saveScheduleFromCfg } from '$lib/components/flows/scheduleUtils' +import { saveEmailTriggerFromCfg } from '$lib/components/triggers/email/utils' +import { saveKafkaTriggerFromCfg } from '$lib/components/triggers/kafka/utils' +import { saveMqttTriggerFromCfg } from '$lib/components/triggers/mqtt/utils' +import { saveAmqpTriggerFromCfg } from '$lib/components/triggers/amqp/utils' +import { saveNatsTriggerFromCfg } from '$lib/components/triggers/nats/utils' +import { savePostgresTriggerFromCfg } from '$lib/components/triggers/postgres/utils' +import { saveSqsTriggerFromCfg } from '$lib/components/triggers/sqs/utils' +import { saveGcpTriggerFromCfg } from '$lib/components/triggers/gcp/utils' +import { + AmqpTriggerService, + EmailTriggerService, + GcpTriggerService, + KafkaTriggerService, + MqttTriggerService, + NatsTriggerService, + PostgresTriggerService, + ScheduleService, + SqsTriggerService +} from '$lib/gen' +import type { NativeTriggerKind, PipelineTriggerDraft } from './types' + +/** Creates the trigger through the same helper its editor saves with; that helper + * reports the outcome as a toast and resolves to whether it succeeded. */ +export function deployTriggerDraft(d: PipelineTriggerDraft, workspace: string): Promise<boolean> { + const cfg = d.config + switch (d.kind) { + case 'schedule': + return saveScheduleFromCfg({ ...cfg, schedule: formatCron(cfg.schedule) }, false, workspace) + case 'email': + return saveEmailTriggerFromCfg('', cfg, false, workspace, false, usedTriggerKinds) + case 'kafka': + return saveKafkaTriggerFromCfg('', cfg, false, workspace, usedTriggerKinds) + case 'mqtt': + return saveMqttTriggerFromCfg('', cfg, false, workspace, usedTriggerKinds) + case 'amqp': + return saveAmqpTriggerFromCfg('', cfg, false, workspace, usedTriggerKinds) + case 'nats': + return saveNatsTriggerFromCfg('', cfg, false, workspace, usedTriggerKinds) + case 'postgres': + return savePostgresTriggerFromCfg('', cfg, false, workspace, usedTriggerKinds) + case 'sqs': + return saveSqsTriggerFromCfg('', cfg, false, workspace, usedTriggerKinds) + case 'gcp': + return saveGcpTriggerFromCfg('', cfg, false, workspace, usedTriggerKinds) + } +} + +/** Deletes a deployed trigger row. False for the kinds that have none (webhook, + * data upload). */ +export async function deleteTriggerRow( + kind: NativeTriggerKind, + path: string, + workspace: string +): Promise<boolean> { + switch (kind) { + case 'schedule': + await ScheduleService.deleteSchedule({ workspace, path }) + return true + case 'kafka': + await KafkaTriggerService.deleteKafkaTrigger({ workspace, path }) + return true + case 'mqtt': + await MqttTriggerService.deleteMqttTrigger({ workspace, path }) + return true + case 'amqp': + await AmqpTriggerService.deleteAmqpTrigger({ workspace, path }) + return true + case 'nats': + await NatsTriggerService.deleteNatsTrigger({ workspace, path }) + return true + case 'postgres': + await PostgresTriggerService.deletePostgresTrigger({ workspace, path }) + return true + case 'sqs': + await SqsTriggerService.deleteSqsTrigger({ workspace, path }) + return true + case 'gcp': + await GcpTriggerService.deleteGcpTrigger({ workspace, path }) + return true + case 'email': + await EmailTriggerService.deleteEmailTrigger({ workspace, path }) + return true + default: + return false + } +} diff --git a/frontend/src/lib/components/assets/AssetGraph/pipelineTriggerDrafts.ts b/frontend/src/lib/components/assets/AssetGraph/pipelineTriggerDrafts.ts new file mode 100644 index 0000000000..7fd2998923 --- /dev/null +++ b/frontend/src/lib/components/assets/AssetGraph/pipelineTriggerDrafts.ts @@ -0,0 +1,26 @@ +import type { PipelineTriggerDraftKind } from './types' + +export const DRAFTABLE_TRIGGER_KINDS: readonly PipelineTriggerDraftKind[] = [ + 'schedule', + 'email', + 'kafka', + 'mqtt', + 'amqp', + 'nats', + 'postgres', + 'sqs', + 'gcp' +] + +export function isDraftableTriggerKind(kind: string): kind is PipelineTriggerDraftKind { + return (DRAFTABLE_TRIGGER_KINDS as readonly string[]).includes(kind) +} + +/** Drafts are keyed by kind too: two kinds may share a trigger path. */ +export function triggerDraftKey(kind: string, path: string): string { + return `${kind}:${path}` +} + +export function defaultTriggerPath(scriptPath: string, kind: PipelineTriggerDraftKind): string { + return `${scriptPath}_${kind}` +} diff --git a/frontend/src/lib/components/assets/AssetGraph/resolveGraph.test.ts b/frontend/src/lib/components/assets/AssetGraph/resolveGraph.test.ts index c57687d78b..6d38a8c119 100644 --- a/frontend/src/lib/components/assets/AssetGraph/resolveGraph.test.ts +++ b/frontend/src/lib/components/assets/AssetGraph/resolveGraph.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest' import { resolveGraph, computeMutedReadKeys, + pipelineNodeErrors, dbtAssociations, type ResolveGraphInput } from './resolveGraph' @@ -492,6 +493,49 @@ describe('resolveGraph', () => { expect(r.edges.some((e) => e.asset_path === 'main/out' && e.access_type === 'w')).toBe(true) }) + it('drops a persisted asset the open script renamed away, unless something still uses it', () => { + const write = (runnable_path: string, asset_path: string) => ({ + runnable_path, + runnable_kind: 'script' as const, + asset_kind: 's3object' as const, + asset_path, + access_type: 'w' as const + }) + const base = baseGraph({ + assets: [ + { kind: 's3object', path: '/old.json' }, + { kind: 's3object', path: '/shared.json' }, + { kind: 's3object', path: '/unreferenced.json' } + ], + runnables: [ + { path: 'f/x/prod', usage_kind: 'script' }, + { path: 'f/x/other', usage_kind: 'script' } + ], + edges: [write('f/x/prod', '/old.json'), write('f/x/prod', '/shared.json')], + triggers: [ + { + trigger_kind: 'asset', + asset_kind: 's3object', + asset_path: '/shared.json', + runnable_kind: 'script', + runnable_path: 'f/x/other' + } + ] + }) + const r = resolveGraph( + input({ + base, + liveAnnotations: { scriptPath: 'f/x/prod', annotations: ann() }, + liveBodyAssets: { scriptPath: 'f/x/prod', assets: [s3('/new.json', 'w')] } + }) + ) + expect(r.assets.map((a) => a.path).sort()).toEqual([ + '/new.json', + '/shared.json', + '/unreferenced.json' + ]) + }) + it('editing a saved scd2 producer keeps both the base and _current persisted write edges', () => { // Deploy persists a write to both `main/dim` and `main/dim_current`. // Opening the producer for editing must not judge the companion `_current` @@ -656,6 +700,31 @@ describe('resolveGraph', () => { }) }) + it('a trigger draft stands in for its draft script’s missing trigger of that kind', () => { + const drafts = new Map([['f/x/new', { script: { content: '// on schedule\n// on kafka' } }]]) + const r = resolveGraph( + input({ + drafts, + triggerDrafts: [ + { kind: 'schedule', config: { path: 'f/x/new_schedule', script_path: 'f/x/new' } } + ] + }) + ) + expect(r.triggers.filter((t) => t.trigger_kind === 'kafka')).toEqual([ + expect.objectContaining({ runnable_path: 'f/x/new', missing: true }) + ]) + expect(r.triggers.filter((t) => t.trigger_kind === 'schedule')).toEqual([ + { + trigger_kind: 'schedule', + path: 'f/x/new_schedule', + runnable_kind: 'script', + runnable_path: 'f/x/new', + unsaved: true, + draft: true + } + ]) + }) + it('macro edges: base passes through; live `// use` adds an unsaved via_use edge', () => { const base = baseGraph({ runnables: [ @@ -884,11 +953,11 @@ describe('live buffer overlays (open script)', () => { access_type: 'w', unsaved: true }) - // …the stale write edge is dropped, but the deployed dataset node stays. + // …the stale write edge is dropped, and with nothing else using it, so is the node. expect( r.edges.filter((e) => e.asset_path === 'main/orders' && e.runnable_path === 'f/x/prod') ).toEqual([]) - expect(r.assets).toContainEqual({ kind: 'ducklake', path: 'main/orders' }) + expect(r.assets).not.toContainEqual({ kind: 'ducklake', path: 'main/orders' }) }) it('open saved script: unchanged materialize target dedups against the persisted write edge', () => { @@ -1083,9 +1152,7 @@ describe('dbtAssociations', () => { it('counts only what the project materializes as its transforms', () => { const { writesByOwner } = dbtAssociations(runnables, edges) // Hovering the project highlights the models it builds, not its inputs. - expect([...(writesByOwner.get('script:f/a/dbtproj') ?? [])]).toEqual([ - 'asset:dbt:wh/s/model_a' - ]) + expect([...(writesByOwner.get('script:f/a/dbtproj') ?? [])]).toEqual(['asset:dbt:wh/s/model_a']) }) it('ignores runnables that are not dbt', () => { @@ -1162,8 +1229,160 @@ describe('dbtAssociations with two writers of one relation', () => { writeBy('f/a/downstream') ]) expect(writesByOwner.get('script:f/a/upstream')).toEqual(new Set(['asset:dbt:wh/s/shared'])) - expect(writesByOwner.get('script:f/a/downstream')).toEqual( - new Set(['asset:dbt:wh/s/shared']) + expect(writesByOwner.get('script:f/a/downstream')).toEqual(new Set(['asset:dbt:wh/s/shared'])) + }) +}) + +describe('pipelineNodeErrors', () => { + const edge = (runnable_path: string, asset_path: string, access_type: 'r' | 'w') => ({ + runnable_path, + runnable_kind: 'script' as const, + asset_kind: 'ducklake' as const, + asset_path, + access_type + }) + const graph = baseGraph({ + assets: [ + { kind: 'ducklake', path: 'main/orphan' }, + { kind: 'ducklake', path: 'main/produced' }, + { kind: 'ducklake', path: 'main/external' } + ], + runnables: [ + { path: 'f/x/prod', usage_kind: 'script' }, + { path: 'f/x/cons', usage_kind: 'script' } + ], + edges: [ + edge('f/x/prod', 'main/produced', 'w'), + edge('f/x/cons', 'main/produced', 'r'), + edge('f/x/cons', 'main/external', 'r') + ] + }) + + it('flags an unused asset, and a `// on` with no producer and its script, but not a plain read', () => { + const onRefs = (...paths: string[]) => + paths.map((path) => ({ kind: 'ducklake' as const, path })) + const none = pipelineNodeErrors(graph, new Map()) + expect([...none.assets.keys()]).toEqual(['ducklake:main/orphan']) + expect(none.scripts.size).toBe(0) + const errors = pipelineNodeErrors( + graph, + new Map([['f/x/cons', onRefs('main/produced', 'main/external')]]) ) + // The subscriber is at fault, not the asset nothing writes. + expect([...errors.assets.keys()]).toEqual(['ducklake:main/orphan']) + expect([...errors.scripts.keys()]).toEqual(['f/x/cons']) + expect([...errors.unwritten.keys()]).toEqual(['ducklake:main/external']) + }) + + it('flags a pipeline script nothing starts, but not a macro library or a triggered one', () => { + const g = baseGraph({ + runnables: [ + { path: 'f/x/stray', usage_kind: 'script', in_pipeline: true }, + { path: 'f/x/lib', usage_kind: 'script', in_pipeline: true, macros: [{ name: 'm' }] }, + { path: 'f/x/timed', usage_kind: 'script', in_pipeline: true } + ] as any, + triggers: [ + { + trigger_kind: 'schedule', + path: 'f/x/timed_schedule', + runnable_kind: 'script', + runnable_path: 'f/x/timed' + } + ] + }) + expect([...pipelineNodeErrors(g, new Map()).untriggered.keys()]).toEqual(['f/x/stray']) + }) + + it('flags a script only started by reads of assets nothing writes', () => { + const g = baseGraph({ + assets: [{ kind: 'ducklake', path: 'main/raw' }], + runnables: [{ path: 'f/x/reader', usage_kind: 'script', in_pipeline: true }] as any, + edges: [ + { + runnable_path: 'f/x/reader', + runnable_kind: 'script', + asset_kind: 'ducklake', + asset_path: 'main/raw', + access_type: 'r' + } + ], + triggers: [ + { + trigger_kind: 'asset', + asset_kind: 'ducklake', + asset_path: 'main/raw', + runnable_kind: 'script', + runnable_path: 'f/x/reader' + } + ] + }) + expect(pipelineNodeErrors(g, new Map()).untriggered.get('f/x/reader')).toBe('unwritten-inputs') + expect( + pipelineNodeErrors(g, new Map(), new Set(['ducklake:main/raw'])).untriggered.size + ).toBe(0) + }) + + it('does not count a flow write as starting an asset-triggered script', () => { + const g = baseGraph({ + assets: [{ kind: 'ducklake', path: 'main/raw' }], + runnables: [ + { path: 'f/x/reader', usage_kind: 'script', in_pipeline: true }, + { path: 'f/x/loader', usage_kind: 'flow' } + ] as any, + edges: [ + { + runnable_path: 'f/x/loader', + runnable_kind: 'flow', + asset_kind: 'ducklake', + asset_path: 'main/raw', + access_type: 'w' + } + ], + triggers: [ + { + trigger_kind: 'asset', + asset_kind: 'ducklake', + asset_path: 'main/raw', + runnable_kind: 'script', + runnable_path: 'f/x/reader' + } + ] + } as any) + expect(pipelineNodeErrors(g, new Map()).untriggered.get('f/x/reader')).toBe('unwritten-inputs') + }) + + it('clears a subscription the workspace writes outside the pipeline', () => { + const errors = pipelineNodeErrors( + graph, + new Map([['f/x/cons', [{ kind: 'ducklake' as const, path: 'main/external' }]]]), + new Set(['ducklake:main/external']) + ) + expect(errors.scripts.size).toBe(0) + expect(errors.unwritten.size).toBe(0) + }) + + it('treats dbt models as used and written by their (hidden) project, but not dbt sources', () => { + const dbt = (path: string, resource_type: string) => ({ + kind: 'dbt' as const, + path, + dbt: { unique_id: `x.${path}`, resource_type } as any + }) + const errors = pipelineNodeErrors( + baseGraph({ + assets: [dbt('mart', 'model'), dbt('raw', 'source')], + runnables: [{ path: 'f/x/s', usage_kind: 'script' }] + }), + new Map([ + [ + 'f/x/s', + [ + { kind: 'dbt', path: 'mart' }, + { kind: 'dbt', path: 'raw' } + ] + ] + ]) + ) + expect([...errors.unwritten.keys()]).toEqual(['dbt:raw']) + expect([...errors.scripts.keys()]).toEqual(['f/x/s']) }) }) diff --git a/frontend/src/lib/components/assets/AssetGraph/resolveGraph.ts b/frontend/src/lib/components/assets/AssetGraph/resolveGraph.ts index 5c8aa697a4..b178de3387 100644 --- a/frontend/src/lib/components/assets/AssetGraph/resolveGraph.ts +++ b/frontend/src/lib/components/assets/AssetGraph/resolveGraph.ts @@ -1,4 +1,9 @@ -import type { AssetGraphMacroEdge, AssetGraphResponse, NativeTriggerKind } from './types' +import type { + AssetGraphMacroEdge, + AssetGraphResponse, + NativeTriggerKind, + PipelineTriggerDraft +} from './types' import { mergeColumnLineage, parsePipelineAnnotations, @@ -46,6 +51,8 @@ export type ResolveGraphInput = { * annotation has no matching trigger row in `base.triggers`. */ annotatedNativeKindsByPath: Map<string, Set<NativeTriggerKind>> + /** Undeployed triggers; each stands in for its script's missing trigger of that kind. */ + triggerDrafts?: Iterable<PipelineTriggerDraft> } /** Mutable bag the sequential passes accumulate the resolved graph into. */ @@ -264,16 +271,200 @@ export function resolveGraph(input: ResolveGraphInput): AssetGraphResponse { // there is nothing to show (also keeps the no-macros response shape // byte-identical to before the feature). const macroEdges = resolveMacroEdges(input) + const triggers = withTriggerDrafts( + [...baseTriggers, ...acc.extraTriggers], + input.triggerDrafts ?? [] + ) return { ...base, - assets: acc.assets, + assets: dropOrphanedAssets(acc.assets, base, acc.edges, triggers), runnables: acc.runnables, edges: acc.edges, - triggers: [...baseTriggers, ...acc.extraTriggers], + triggers, ...(macroEdges.length > 0 || base.macro_edges ? { macro_edges: macroEdges } : {}) } } +function withTriggerDrafts( + triggers: AssetGraphResponse['triggers'], + triggerDrafts: Iterable<PipelineTriggerDraft> +): AssetGraphResponse['triggers'] { + const drafts = [...triggerDrafts] + if (drafts.length === 0) return triggers + const drafted = new Set(drafts.map((d) => `${d.kind}:${d.config.script_path}`)) + return [ + ...triggers.filter( + (t) => + !( + t.trigger_kind !== 'asset' && + t.missing && + t.runnable_kind === 'script' && + drafted.has(`${t.trigger_kind}:${t.runnable_path}`) + ) + ), + ...drafts.map((d) => ({ + trigger_kind: d.kind, + path: d.config.path, + runnable_kind: 'script' as const, + runnable_path: d.config.script_path, + unsaved: true, + draft: true, + ...(d.kind === 'schedule' + ? { schedule: d.config.schedule as string, timezone: d.config.timezone as string } + : {}), + ...(d.config.summary ? { summary: d.config.summary as string } : {}) + })) + ] +} + +/** Why a node is red, and what the Fix actions act on. */ +export type PipelineNodeErrors = { + /** `kind:path` → reason. */ + assets: Map<string, string> + /** Script path → reason. */ + scripts: Map<string, string> + /** Subscribed assets nothing writes: `kind:path` → the asset and its subscribers. */ + unwritten: Map<string, { asset: { kind: AssetKind; path: string }; subscribers: string[] }> + /** Script path → the unwritten asset it runs on (its first, when several). */ + waitsOn: Map<string, { kind: AssetKind; path: string }> + /** Pipeline scripts nothing starts → why: no trigger at all, or only asset + * triggers on assets nothing writes (an auto-triggering read included). */ + untriggered: Map<string, 'no-trigger' | 'unwritten-inputs'> + /** Assets some asset trigger waits on that nothing in the pipeline writes: the + * ones to look up across the workspace for `writtenElsewhere`. */ + unwrittenTriggerAssets: Set<string> +} + +/** + * Nodes the pipeline cannot work with, with the reason. Assets (keyed + * `kind:path`): one nothing uses at all. Scripts (keyed by path): one + * subscribed (`// on <asset>`) to an asset nothing writes, in the pipeline or, + * per `writtenElsewhere`, by a script anywhere else in the workspace, since the subscription can never fire; the asset itself is + * fine, and is reported in `unwritten`. A body read of an external asset is fine and is not passed here: + * only the explicit `// on` annotations, per script path, count as subscriptions. + */ +export function pipelineNodeErrors( + graph: AssetGraphResponse, + explicitOnByPath: Map<string, Array<{ kind: AssetKind; path: string }>>, + writtenElsewhere: ReadonlySet<string> = new Set() +): PipelineNodeErrors { + const referenced = referencedAssetKeys(graph) + // Only a script's write fires an asset trigger: a flow's never does. + const written = new Set( + graph.edges + .filter( + (e) => e.runnable_kind === 'script' && (e.access_type === 'w' || e.access_type === 'rw') + ) + .map((e) => `${e.asset_kind}:${e.asset_path}`) + ) + for (const k of writtenElsewhere) written.add(k) + // The dbt project's own edges are hidden from the pipeline graph (see + // `hideDbtRunnables`), so its relations are judged by their provenance: the + // project uses every one, and materializes all but its sources. + for (const a of graph.assets) { + if (!a.dbt) continue + referenced.add(`${a.kind}:${a.path}`) + if (a.dbt.resource_type !== 'source') written.add(`${a.kind}:${a.path}`) + } + const errors = new Map<string, string>() + const scriptErrors = new Map<string, string>() + const unwritten: PipelineNodeErrors['unwritten'] = new Map() + const waitsOn: PipelineNodeErrors['waitsOn'] = new Map() + for (const a of graph.assets) { + const key = `${a.kind}:${a.path}` + if (!referenced.has(key)) errors.set(key, 'nothing in the pipeline uses it') + } + const scripts = new Set( + graph.runnables.filter((r) => r.usage_kind === 'script').map((r) => r.path) + ) + for (const [path, refs] of explicitOnByPath) { + if (!scripts.has(path)) continue + for (const ref of refs) { + const key = `${ref.kind}:${ref.path}` + if (written.has(key)) continue + const entry = unwritten.get(key) ?? { asset: ref, subscribers: [] } + if (!entry.subscribers.includes(path)) entry.subscribers.push(path) + unwritten.set(key, entry) + if (!scriptErrors.has(path)) { + scriptErrors.set(path, `runs on ${ref.path}, which nothing writes`) + waitsOn.set(path, ref) + } + } + } + // A pipeline script nothing starts runs only by hand. An asset trigger starts + // it only if something writes that asset, which covers the automatic trigger + // of a ducklake/s3 read too. dbt projects and macro libraries are never + // started on their own, so they are left out. + const assetKey = (t: { asset_kind: AssetKind; asset_path: string }) => + `${t.asset_kind}:${t.asset_path}` + const unwrittenTriggerAssets = new Set<string>() + const hasTrigger = new Set<string>() + const started = new Set<string>() + for (const t of graph.triggers) { + hasTrigger.add(t.runnable_path) + if (t.trigger_kind !== 'asset') started.add(t.runnable_path) + else if (written.has(assetKey(t))) started.add(t.runnable_path) + else unwrittenTriggerAssets.add(assetKey(t)) + } + for (const k of unwritten.keys()) unwrittenTriggerAssets.add(k) + const untriggered: PipelineNodeErrors['untriggered'] = new Map() + for (const r of graph.runnables) { + if (r.usage_kind !== 'script' || !r.in_pipeline || r.dbt || r.macros?.length) continue + if (started.has(r.path) || scriptErrors.has(r.path)) continue + const why = hasTrigger.has(r.path) ? 'unwritten-inputs' : 'no-trigger' + untriggered.set(r.path, why) + scriptErrors.set( + r.path, + why === 'no-trigger' + ? 'nothing starts it: it has no trigger' + : 'nothing starts it: nothing writes the assets it runs after' + ) + } + return { + assets: errors, + scripts: scriptErrors, + unwritten, + waitsOn, + untriggered, + unwrittenTriggerAssets + } +} + +function referencedAssetKeys( + graph: Pick<AssetGraphResponse, 'edges' | 'triggers' | 'test_edges' | 'dbt_edges'> +): Set<string> { + const keys = new Set<string>() + for (const e of graph.edges) keys.add(`${e.asset_kind}:${e.asset_path}`) + for (const t of graph.triggers) + if (t.trigger_kind === 'asset') keys.add(`${t.asset_kind}:${t.asset_path}`) + for (const e of graph.test_edges ?? []) keys.add(`${e.asset_kind}:${e.asset_path}`) + for (const e of graph.dbt_edges ?? []) { + keys.add(`dbt:${e.from_asset_path}`) + keys.add(`dbt:${e.to_asset_path}`) + } + return keys +} + +/** + * The backend only returns assets something references, so a deployed asset + * whose every edge and trigger the draft/live overlays stripped — an output the + * open script renamed — would linger as an edgeless node until the deploy + * lands. Assets that were already unreferenced in `base` are left alone. + */ +function dropOrphanedAssets( + assets: AssetGraphResponse['assets'], + base: AssetGraphResponse, + edges: AssetGraphResponse['edges'], + triggers: AssetGraphResponse['triggers'] +): AssetGraphResponse['assets'] { + const before = referencedAssetKeys(base) + const after = referencedAssetKeys({ ...base, edges, triggers }) + return assets.filter((a) => { + const key = `${a.kind}:${a.path}` + return !before.has(key) || after.has(key) + }) +} + /** * Macro-library → consumer edges: the deployed base edges, with `// use` * declarations of overlaid scripts (drafts + the open buffer) taking over @@ -848,7 +1039,6 @@ function overlayInferredLineage(acc: Accumulator, input: ResolveGraphInput) { overlayLineage(inferredReadsByPath, 'r') } - /** dbt project ↔ relation association, for a graph that does NOT draw it. * * A dbt script owns every relation of its project, so drawing one edge per diff --git a/frontend/src/lib/components/assets/AssetGraph/types.ts b/frontend/src/lib/components/assets/AssetGraph/types.ts index 023f71e218..4ee7aa0216 100644 --- a/frontend/src/lib/components/assets/AssetGraph/types.ts +++ b/frontend/src/lib/components/assets/AssetGraph/types.ts @@ -6,6 +6,12 @@ export type GraphUsageKind = 'script' | 'flow' export interface AssetGraphAssetNode { kind: AssetKind path: string + // Filled in client-side: the node is misconfigured (see `pipelineNodeErrors`). + error?: string + // Filled in client-side: no script in the workspace writes it, so a step + // downstream of it would never run on its writes (a flow's write fires no + // asset trigger). + never_written?: boolean // Fork workspaces only: 'fork' when this ducklake asset was materialized in // the fork itself, 'deferred' when reads fall back to the parent workspace's // current table via a defer view. Absent outside forks / for other kinds / @@ -70,6 +76,12 @@ export interface DbtDataTest { export interface AssetGraphRunnableNode { path: string usage_kind: GraphUsageKind + // Filled in client-side (not sent by the backend): the canvas titles the + // node with the summary over the path, and shows the language's icon. + summary?: string + language?: import('$lib/gen').ScriptLang + // Why the script is misconfigured, when it is (see `pipelineNodeErrors`). + error?: string // Script has `// pipeline` annotation. Drives the pipeline-member // visual state; unrelated to what the script actually writes (that's // parsed separately into lineage edges). @@ -170,6 +182,17 @@ export type NativeTriggerKind = | 'gcp' | 'data_upload' +export type PipelineTriggerDraftKind = Exclude<NativeTriggerKind, 'webhook' | 'data_upload'> + +/** A trigger configured in the pipeline editor but not deployed yet. It lives only + * in the pipeline's draft bundle, never as a workspace trigger draft, and is + * created when the pipeline is saved. `config` is what the kind's editor saves + * (for a schedule, a `NewSchedule`). */ +export type PipelineTriggerDraft = { + kind: PipelineTriggerDraftKind + config: Record<string, any> & { path: string; script_path: string } +} + export type AssetGraphTrigger = | { trigger_kind: 'asset' @@ -192,6 +215,13 @@ export type AssetGraphTrigger = // the canvas renders a red placeholder with a "Create trigger" // affordance instead of a fully-wired source. missing?: boolean + // A pipeline-local `PipelineTriggerDraft`: `path` is the trigger it + // will be deployed as, and no row exists yet. + draft?: boolean + // A schedule's cron, zone and summary, filled in client-side, for the node's labels. + schedule?: string + timezone?: string + summary?: string } // Macro-library → consumer edge: the consumer calls `macro_names` of diff --git a/frontend/src/lib/components/assets/AssetGraph/upstreamScriptItems.ts b/frontend/src/lib/components/assets/AssetGraph/upstreamScriptItems.ts new file mode 100644 index 0000000000..43090adb48 --- /dev/null +++ b/frontend/src/lib/components/assets/AssetGraph/upstreamScriptItems.ts @@ -0,0 +1,32 @@ +import type { Item } from '$lib/utils' +import type { ScriptLang } from '$lib/gen' +import LanguageIcon from '$lib/components/common/languageIcons/LanguageIcon.svelte' +import { Code2 } from 'lucide-svelte' + +export type UpstreamScript = { path: string; summary?: string; language?: ScriptLang } + +/** A menu of the scripts that produce an asset, to pick the one to open. */ +export function upstreamScriptItems( + scripts: UpstreamScript[], + onPick: (path: string) => void +): Item[] { + return scripts.map((s) => ({ + displayName: s.summary || s.path, + description: s.summary ? s.path : undefined, + ...(s.language + ? { icon: LanguageIcon, iconProps: { lang: s.language, width: 14, height: 14 } } + : { icon: Code2 }), + action: () => onPick(s.path) + })) +} + +/** An upstream trigger the asset pane can open, and how. */ +export type UpstreamTriggerAction = { label: string; detail?: string; onOpen: () => void } + +export function upstreamTriggerItems(triggers: UpstreamTriggerAction[]): Item[] { + return triggers.map((t) => ({ + displayName: t.label, + description: t.detail, + action: () => t.onOpen() + })) +} diff --git a/frontend/src/lib/components/common/alert/Alert.svelte b/frontend/src/lib/components/common/alert/Alert.svelte index 7d22320867..b7639e1104 100644 --- a/frontend/src/lib/components/common/alert/Alert.svelte +++ b/frontend/src/lib/components/common/alert/Alert.svelte @@ -17,6 +17,8 @@ bgClass?: string | undefined bgStyle?: string | undefined iconClass?: string | undefined + /** Drop the type's icon; the text starts at the alert's edge. */ + hideIcon?: boolean iconStyle?: string | undefined titleClass?: string | undefined titleStyle?: string | undefined @@ -41,6 +43,7 @@ bgClass = undefined, bgStyle = undefined, iconClass = undefined, + hideIcon = false, iconStyle = undefined, titleClass = undefined, titleStyle = undefined, @@ -78,14 +81,16 @@ <div class="flex flex-row items-center"> <!-- shrink-0: the badge's min-content width is the 16px icon, so without it a narrow container squeezes the circle into an oval. --> - <div class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full"> - <SvelteComponent - class={twMerge(classes[type].iconClass, iconClass)} - style={iconStyle} - size={16} - /> - </div> - <div class={twMerge('ml-1 w-full')}> + {#if !hideIcon} + <div class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full"> + <SvelteComponent + class={twMerge(classes[type].iconClass, iconClass)} + style={iconStyle} + size={16} + /> + </div> + {/if} + <div class={twMerge(!hideIcon && 'ml-1', 'w-full')}> {#if hasTitleRow} <div class={twMerge('w-full flex flex-row items-center justify-between')}> <span diff --git a/frontend/src/lib/components/common/confirmationModal/DraftEditorModals.svelte b/frontend/src/lib/components/common/confirmationModal/DraftEditorModals.svelte index 20c29286b5..63e6b13994 100644 --- a/frontend/src/lib/components/common/confirmationModal/DraftEditorModals.svelte +++ b/frontend/src/lib/components/common/confirmationModal/DraftEditorModals.svelte @@ -15,7 +15,6 @@ import OtherUsersDraftsModal, { type OtherDraftUser } from './OtherUsersDraftsModal.svelte' import { UserDraftDbSyncer } from '$lib/userDraftDbSyncer.svelte' import { sendUserToast } from '$lib/toast' - import { base } from '$app/paths' import { goto } from '$app/navigation' import StaleDraftModal from './StaleDraftModal.svelte' import ConfirmationModal from './ConfirmationModal.svelte' @@ -163,7 +162,7 @@ } const target = destination ?? newPath sendUserToast(`This item was moved to ${target}. You are now editing it there.`) - await goto(`${base}/${seg}/${target}`) + await goto(`/${seg}/${target}`) }) }) </script> diff --git a/frontend/src/lib/components/common/confirmationModal/OtherUsersDraftsModal.svelte b/frontend/src/lib/components/common/confirmationModal/OtherUsersDraftsModal.svelte index 49356d888e..b6ec78f336 100644 --- a/frontend/src/lib/components/common/confirmationModal/OtherUsersDraftsModal.svelte +++ b/frontend/src/lib/components/common/confirmationModal/OtherUsersDraftsModal.svelte @@ -7,7 +7,8 @@ */ import { DraftService, type UserDraftItemKind } from '$lib/gen' import { sendUserToast } from '$lib/toast' - import { Users, Pencil, GitCompareArrows, Wrench } from 'lucide-svelte' + import { Users, Pencil, GitCompareArrows, Wrench, Trash2 } from 'lucide-svelte' + import ConfirmationModal from './ConfirmationModal.svelte' import Modal2 from '$lib/components/common/modal/Modal2.svelte' import Button from '$lib/components/common/button/Button.svelte' import Tooltip from '$lib/components/Tooltip.svelte' @@ -17,6 +18,10 @@ import { OtherUserDraftLoad } from '$lib/components/otherUserDraftLoad.svelte' import { displayDate } from '$lib/utils' import { userStore } from '$lib/stores' + import { armRestartOnFirstInteraction } from '$lib/userDraftToast' + import { UserDraft } from '$lib/userDraft.svelte' + import { UserDraftDbSyncer } from '$lib/userDraftDbSyncer.svelte' + import { goto } from '$app/navigation' export type OtherDraftUser = { username?: string | null; draft_saved_at?: string } @@ -54,8 +59,70 @@ let diffDrawer: DiffDrawer | undefined = $state(undefined) let migrateOpen = $state(false) - // Legacy (no-owner) drafts can only be resolved by workspace admins / superadmins. - const canMigrateLegacy = $derived(!!$userStore?.is_admin || !!$userStore?.is_super_admin) + // One owner's draft, or every draft at the path. + let deleting = $state<OtherDraftUser | 'all' | undefined>(undefined) + let deleteBusy = $state(false) + + // Legacy (no-owner) drafts can only be resolved by workspace admins / superadmins, + // and only they can delete a draft that belongs to someone else. + const isAdmin = $derived(!!$userStore?.is_admin || !!$userStore?.is_super_admin) + + async function deleteDraft(target: OtherDraftUser | 'all') { + const username = target === 'all' ? undefined : target.username + if (target !== 'all' && !username) return + deleteBusy = true + const query = { workspace, itemKind, path } + try { + // A path-wide delete takes our own draft too. Mute autosave and let any save + // already in flight land first: one committing after the delete would put the + // draft back for the reload below to read. + if (target === 'all') { + UserDraft.stopSync(itemKind, path, { workspace }) + await UserDraftDbSyncer.quiesce(query) + } + await DraftService.deleteDraftForUser({ + workspace, + kind: itemKind, + path, + username: username ?? undefined + }) + } catch (e) { + if (target === 'all') { + UserDraft.restartSync(itemKind, path, { workspace }) + // `quiesce` cancelled the timer of an edit still waiting to save. + void UserDraftDbSyncer.flush(query, { honorAutosaveToggle: true }) + } + sendUserToast(`Could not delete draft: ${e.body ?? e.message}`, true) + return + } finally { + deleteBusy = false + } + sendUserToast(username ? `Deleted ${username}'s draft` : `Deleted all drafts at ${path}`) + deleting = undefined + isOpen = false + + // Drop the editor's copy of our draft as well, or its next write would save + // it right back. Autosave re-arms on the next interaction. + if (target === 'all') { + UserDraft.remove(itemKind, path, { workspace }) + await UserDraftDbSyncer.flush(query) + armRestartOnFirstInteraction(workspace, itemKind, path) + } + // Nothing is left at a never-deployed path once its last draft is gone, so + // there is no item to reload the editor on. + const lastDraftGone = + target === 'all' || + (!hasOwnDraft && otherDraftsUsers.every((o) => ownerKey(o) === ownerKey(target))) + if (draftOnly && lastDraftGone) { + await goto('/') + return + } + try { + await onReload?.() + } catch (e) { + sendUserToast(`Could not reload the editor: ${e.body ?? e.message}`, true) + } + } function ownerLabel(owner: OtherDraftUser): string { return owner.username ?? 'Legacy draft' @@ -184,7 +251,7 @@ > Load </Button> - {#if !owner.username && canMigrateLegacy} + {#if !owner.username && isAdmin} <Button variant="default" size="xs" @@ -193,12 +260,35 @@ > Migrate </Button> + {:else if owner.username && isAdmin} + <Button + variant="default" + unifiedSize="sm" + destructive + startIcon={{ icon: Trash2 }} + disabled={busyFor !== null} + onclick={() => (deleting = owner)} + > + Delete + </Button> {/if} </li> {/each} </ul> - <div class="flex justify-end"> + <div class="flex justify-end gap-2"> + {#if isAdmin} + <Button + variant="default" + unifiedSize="md" + destructive + startIcon={{ icon: Trash2 }} + disabled={busyFor !== null} + onclick={() => (deleting = 'all')} + > + Delete all drafts + </Button> + {/if} <Button variant="default" size="sm" on:click={() => (isOpen = false)}>Close</Button> </div> </div> @@ -206,6 +296,29 @@ <DiffDrawer bind:this={diffDrawer} isFlow={itemKind === 'flow'} /> +<ConfirmationModal + open={deleting !== undefined} + title={deleting === 'all' ? 'Delete all drafts?' : `Delete ${deleting?.username}'s draft?`} + confirmationText="Delete" + loading={deleteBusy} + onConfirmed={() => { + if (deleting) void deleteDraft(deleting) + }} + onCanceled={() => (deleting = undefined)} +> + <span class="text-sm"> + {#if deleting === 'all'} + This permanently deletes every draft at + <span class="font-medium text-primary">{path}</span>, yours included. All unsaved work there + is lost and can't be recovered. + {:else} + This permanently deletes the draft {deleting?.username} has at + <span class="font-medium text-primary">{path}</span>. Their unsaved work there is lost and + can't be recovered. + {/if} + </span> +</ConfirmationModal> + <MigrateLegacyDraftModal bind:isOpen={migrateOpen} {workspace} diff --git a/frontend/src/lib/components/common/contextmenu/fromMenuItems.ts b/frontend/src/lib/components/common/contextmenu/fromMenuItems.ts new file mode 100644 index 0000000000..1ba6c0bac8 --- /dev/null +++ b/frontend/src/lib/components/common/contextmenu/fromMenuItems.ts @@ -0,0 +1,18 @@ +import type { Item } from '$lib/utils' +import type { ContextMenuItem } from './ContextMenu.svelte' + +/** A dropdown's items as the same entries of a right-click menu. */ +export function contextMenuItemsFromMenu(items: Item[]): ContextMenuItem[] { + return items.flatMap((item) => [ + ...(item.separatorTop ? [{ id: `${item.displayName}-divider`, label: '', divider: true }] : []), + { + id: item.displayName, + label: item.displayName, + icon: item.icon, + disabled: item.disabled, + type: item.type, + shortcut: item.shortcut, + onClick: item.action as (() => void) | undefined + } + ]) +} diff --git a/frontend/src/lib/components/common/fileDownload/FileDownload.svelte b/frontend/src/lib/components/common/fileDownload/FileDownload.svelte index c1a29fae70..7f9187da62 100644 --- a/frontend/src/lib/components/common/fileDownload/FileDownload.svelte +++ b/frontend/src/lib/components/common/fileDownload/FileDownload.svelte @@ -1,6 +1,5 @@ <script lang="ts"> import { Download } from 'lucide-svelte' - import { base } from '$lib/base' import { downloadViaClient, shouldDownloadViaClient } from '$lib/utils/downloadFile' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' @@ -26,7 +25,7 @@ s3object?.storage ? `&storage=${s3object.storage}` : '' }${appPath && s3object?.presigned ? `&${s3object?.presigned}` : ''}` ) - let href = $derived(`${base}/api${apiPath}`) + let href = $derived(`/api${apiPath}`) const sharedClass = `relative center-center flex w-full text-center font-normal text-primary text-sm border border-dashed border-gray-400 hover:border-blue-500 diff --git a/frontend/src/lib/components/common/languageIcons/LanguageIcon.svelte b/frontend/src/lib/components/common/languageIcons/LanguageIcon.svelte index 617f5206dc..7635b900bb 100644 --- a/frontend/src/lib/components/common/languageIcons/LanguageIcon.svelte +++ b/frontend/src/lib/components/common/languageIcons/LanguageIcon.svelte @@ -28,6 +28,7 @@ import RIcon from '$lib/components/icons/RIcon.svelte' import ClaudeIcon from '$lib/components/icons/ClaudeIcon.svelte' import DbtIcon from '$lib/components/icons/DbtIcon.svelte' + import { Pi } from 'lucide-svelte' interface Props { lang: @@ -41,6 +42,7 @@ | 'powershell' | 'bunnative' | 'claudesandbox' + | 'pisandbox' width?: number height?: number scale?: number @@ -50,7 +52,10 @@ let { lang, width = 30, height = 30, scale = 1, size = undefined, ...rest }: Props = $props() - const languageLabel: Record<Script['language'] | 'bunnative' | 'claudesandbox', String> = { + const languageLabel: Record< + Script['language'] | 'bunnative' | 'claudesandbox' | 'pisandbox', + String + > = { python3: 'Python', deno: 'TypeScript', go: 'Go', @@ -76,12 +81,21 @@ ruby: 'Ruby', rlang: 'R', dbt: 'dbt', - claudesandbox: 'Claude Sandbox' + claudesandbox: 'Claude Sandbox', + pisandbox: 'Pi Sandbox' // for related places search: ADD_NEW_LANG } const langToComponent: Record< - SupportedLanguage | 'pgsql' | 'javascript' | 'fetch' | 'docker' | 'powershell' | 'bunnative' | 'claudesandbox', + | SupportedLanguage + | 'pgsql' + | 'javascript' + | 'fetch' + | 'docker' + | 'powershell' + | 'bunnative' + | 'claudesandbox' + | 'pisandbox', any > = { go: GoIcon, @@ -114,7 +128,8 @@ rlang: RIcon, duckdb: DuckDbIcon, dbt: DbtIcon, - claudesandbox: TypeScriptIcon + claudesandbox: TypeScriptIcon, + pisandbox: TypeScriptIcon // for related places search: ADD_NEW_LANG } @@ -166,4 +181,14 @@ /> </div> {/if} + {#if lang === 'pisandbox'} + <div + class="absolute -top-1.5 -right-1.5 bg-surface rounded-full flex items-center justify-center text-primary" + style={`width: ${width * scale * subIconScale}px; height: ${ + height * scale * subIconScale + }px;`} + > + <Pi size={width * scale * (subIconScale - 0.1)} /> + </div> + {/if} </div> diff --git a/frontend/src/lib/components/common/radioCard/RadioCard.svelte b/frontend/src/lib/components/common/radioCard/RadioCard.svelte index f9b7f675a4..6e7aa67ef8 100644 --- a/frontend/src/lib/components/common/radioCard/RadioCard.svelte +++ b/frontend/src/lib/components/common/radioCard/RadioCard.svelte @@ -10,6 +10,7 @@ onSelect, disabled = false, icon = undefined, + badge = undefined, showRadio = true, class: className = '' }: { @@ -25,6 +26,8 @@ disabled?: boolean /** Optional leading icon, rendered after the radio */ icon?: Snippet + /** Optional badge rendered right after the label */ + badge?: Snippet /** Draw the radio glyph. Turn it off where the card itself is the only * control and the border and tint already say which one is picked — the dot * is then a second, redundant answer to the same question. The group still @@ -51,8 +54,10 @@ // (FileExplorer, TriggersTable, RunnableRow, ArtifactVersionPicker). selected ? 'border-border-selected bg-surface-accent-selected' - : 'border-border-light hover:bg-surface-hover', - disabled && 'opacity-50 cursor-not-allowed', + : 'border-border-light enabled:hover:bg-surface-hover', + // `disabled:` variants, not plain utilities: the global `button:disabled` + // rule sets opacity and cursor and outranks a single class. + 'disabled:opacity-50 disabled:cursor-not-allowed', className )} > @@ -68,7 +73,10 @@ <div class="shrink-0 mt-0.5">{@render icon()}</div> {/if} <div class="flex-1 min-w-0"> - <div class="text-xs font-semibold text-emphasis">{label}</div> + <div class="flex items-center gap-2 text-xs font-semibold text-emphasis"> + {label} + {@render badge?.()} + </div> {#if describedBySnippet} <div class="text-xs font-normal text-secondary mt-0.5"> {@render (description as Snippet)()} diff --git a/frontend/src/lib/components/common/slack/SlackConnectionStatus.svelte b/frontend/src/lib/components/common/slack/SlackConnectionStatus.svelte index 8658c462ab..d79491b0fc 100644 --- a/frontend/src/lib/components/common/slack/SlackConnectionStatus.svelte +++ b/frontend/src/lib/components/common/slack/SlackConnectionStatus.svelte @@ -1,7 +1,6 @@ <script lang="ts"> import { Badge, Button } from '$lib/components/common' import { Plug, RotateCw, Unplug } from 'lucide-svelte' - import { base } from '$lib/base' interface Props { isConnected: boolean | undefined @@ -16,8 +15,8 @@ // Connection URLs based on mode let connectUrl = $derived( mode === 'instance' - ? `${base}/api/oauth/connect_slack?instance=true` - : `${base}/workspace_settings?tab=slack` + ? '/api/oauth/connect_slack?instance=true' + : '/workspace_settings?tab=slack' ) </script> diff --git a/frontend/src/lib/components/common/table/AgentRow.svelte b/frontend/src/lib/components/common/table/AgentRow.svelte index ecde985be4..05c15a582a 100644 --- a/frontend/src/lib/components/common/table/AgentRow.svelte +++ b/frontend/src/lib/components/common/table/AgentRow.svelte @@ -1,5 +1,4 @@ <script lang="ts"> - import { base } from '$lib/base' import Dropdown from '$lib/components/DropdownV2.svelte' import SharedBadge from '$lib/components/SharedBadge.svelte' import DraftBadge from '$lib/components/DraftBadge.svelte' @@ -14,8 +13,10 @@ import ChatFlowBadge from '$lib/components/flows/ChatFlowBadge.svelte' import { keepsManagedMemory } from '$lib/components/flows/agentFormFields' import { agentMenuItems, deleteAgent } from '$lib/components/flows/agentActions' + import AgentHistory from '$lib/components/flows/AgentHistory.svelte' import { getDeployUiSettings } from '$lib/components/home/deploy_ui' import Row from './Row.svelte' + import { selectMenuItems, type RowSelection } from './rowSelection' /** * A home-page row for a saved agent. The agent is an `ai_agent` resource, so the row opens the @@ -30,6 +31,7 @@ depth?: number menuOpen: boolean keyboardSelected?: boolean + rowSelection?: RowSelection } let { @@ -40,7 +42,8 @@ deleteConfirmedCallback = $bindable(), depth = 0, menuOpen = $bindable(), - keyboardSelected = false + keyboardSelected = false, + rowSelection = undefined }: Props = $props() const dispatch = createEventDispatcher() @@ -49,11 +52,19 @@ if (await deleteAgent($workspaceStore!, path)) dispatch('change') } - let editHref = $derived(`${base}/agents/edit/${agent.path}`) + let editHref = $derived(`/agents/edit/${agent.path}`) // A draft-only agent has nothing deployed for its page to run, so it opens in the editor. - let rowHref = $derived(agent.draft_only ? editHref : `${base}/agents/get/${agent.path}`) + let rowHref = $derived(agent.draft_only ? editHref : `/agents/get/${agent.path}`) + let history: AgentHistory | undefined = $state(undefined) </script> +<AgentHistory + bind:this={history} + path={agent.path} + canRestore={agent.canWrite} + onRestored={() => dispatch('change')} +/> + {#snippet chatBadge()} <ChatFlowBadge title="Managed memory on: this agent opens as a conversation" /> {/snippet} @@ -67,8 +78,9 @@ path={agent.draft_path ?? agent.path} summary={agent.description} workspaceId={agent.workspace_id ?? $workspaceStore ?? ''} - canFavorite={false} + canFavorite={!agent.draft_only} {depth} + {rowSelection} > {#snippet badges()} <SharedBadge canWrite={agent.canWrite} extraPerms={agent.extra_perms} /> @@ -99,21 +111,25 @@ </span> {/if} <Dropdown - items={async () => - agentMenuItems({ + items={async () => [ + ...selectMenuItems(rowSelection), + ...agentMenuItems({ deployUiSettings: await getDeployUiSettings(), path: agent.path, canWrite: agent.canWrite, draftOnly: Boolean(agent.draft_only), wsSpecific: agent.ws_specific, + operator: $userStore?.operator, onPermissions: () => shareModal.openDrawer?.(agent.path, 'resource'), onDeploy: () => deploymentDrawer.openDrawer(agent.path, 'resource'), + onHistory: () => history?.open(), onDelete: (event) => { const { path } = agent if (event?.shiftKey) remove(path) else deleteConfirmedCallback = () => remove(path) } - })} + }) + ]} on:open={() => { menuOpen = true }} diff --git a/frontend/src/lib/components/common/table/AppRow.svelte b/frontend/src/lib/components/common/table/AppRow.svelte index bd881a31b7..a318c1f412 100644 --- a/frontend/src/lib/components/common/table/AppRow.svelte +++ b/frontend/src/lib/components/common/table/AppRow.svelte @@ -1,5 +1,4 @@ <script lang="ts"> - import { base } from '$lib/base' import Dropdown from '$lib/components/DropdownV2.svelte' import type MoveDrawer from '$lib/components/MoveDrawer.svelte' import SharedBadge from '$lib/components/SharedBadge.svelte' @@ -7,6 +6,7 @@ import type ShareModal from '$lib/components/ShareModal.svelte' import { AppService, type ListableApp } from '$lib/gen' import { userStore, userWorkspaces, workspaceStore } from '$lib/stores' + import { useOperatorBuilderApps } from '$lib/operatorWriteRights' import { UserDraftDbSyncer } from '$lib/userDraftDbSyncer.svelte' import { createEventDispatcher } from 'svelte' import Button from '../button/Button.svelte' @@ -68,6 +68,7 @@ }: Props = $props() const dispatch = createEventDispatcher() + const operatorBuilderApps = useOperatorBuilderApps() let appExport: { open: (path: string, rawApp?: boolean) => void } | undefined = $state(undefined) let appDeploymentHistory: AppDeploymentHistory | undefined = $state(undefined) @@ -106,8 +107,8 @@ <Row href={app.draft_only - ? `${base}/apps${app.raw_app ? '_raw' : ''}/edit/${app.path}` - : `${base}/apps${app.raw_app ? '_raw' : ''}/get/${app.path}`} + ? `/apps${app.raw_app ? '_raw' : ''}/edit/${app.path}` + : `/apps${app.raw_app ? '_raw' : ''}/get/${app.path}`} kind="app" {keyboardSelected} {marked} @@ -159,24 +160,22 @@ {/snippet} {#snippet actions()} <span class="hidden md:inline-flex gap-x-1"> - {#if !$userStore?.operator} - {#if showEditButton && app.canWrite} - <div> - <Button - aiId={`edit-app-button-${app.summary?.length > 0 ? app.summary : app.path}`} - aiDescription={`Edits the app ${app.summary?.length > 0 ? app.summary : app.path}`} - variant="subtle" - wrapperClasses="w-20" - startIcon={{ icon: Pen }} - href="{base}/apps{app.raw_app ? '_raw' : ''}/edit/{app.path}" - > - Edit - </Button> - </div> - {/if} - {#if !isCloudHosted() && editInForkAllowed($workspaceStore, $userWorkspaces) && (!showEditButton || !app.canWrite)} - <EditInForkButton itemType={app.raw_app ? 'raw_app' : 'app'} path={app.path} /> - {/if} + {#if showEditButton && app.canWrite} + <div> + <Button + aiId={`edit-app-button-${app.summary?.length > 0 ? app.summary : app.path}`} + aiDescription={`Edits the app ${app.summary?.length > 0 ? app.summary : app.path}`} + variant="subtle" + wrapperClasses="w-20" + startIcon={{ icon: Pen }} + href="/apps{app.raw_app ? '_raw' : ''}/edit/{app.path}" + > + Edit + </Button> + </div> + {/if} + {#if !$userStore?.operator && !isCloudHosted() && editInForkAllowed($workspaceStore, $userWorkspaces) && (!showEditButton || !app.canWrite)} + <EditInForkButton itemType={app.raw_app ? 'raw_app' : 'app'} path={app.path} /> {/if} </span> <Dropdown @@ -224,7 +223,7 @@ // list endpoint only surfaces own/legacy draft-only rows), so // discarding it never requires write permission on the path. disabled: !showEditButton, - hide: $userStore?.operator + hide: $userStore?.operator && !($operatorBuilderApps && app.raw_app) }, { displayName: $userStore?.operator ? 'View JSON' : 'View/Edit JSON', @@ -240,7 +239,7 @@ { displayName: 'Duplicate/Fork', icon: GitFork, - href: `${base}/apps${app.raw_app ? '_raw' : ''}/add?template=${path}`, + href: `/apps${app.raw_app ? '_raw' : ''}/add?template=${path}`, disabled: !showEditButton, hide: $userStore?.operator }, @@ -287,7 +286,7 @@ displayName: 'Deployments', icon: History, action: () => appDeploymentHistory?.open(), - hide: $userStore?.operator + hide: $userStore?.operator && !($operatorBuilderApps && app.raw_app) }, { displayName: 'Permissions', @@ -295,7 +294,7 @@ action: () => { shareModal.openDrawer && shareModal.openDrawer(path, 'app') }, - hide: $userStore?.operator + hide: $userStore?.operator && !($operatorBuilderApps && app.raw_app) }, { displayName: 'Copy path', @@ -341,7 +340,7 @@ }, type: 'delete', disabled: !canEdit, - hide: $userStore?.operator + hide: $userStore?.operator && !($operatorBuilderApps && app.raw_app) } ] }} diff --git a/frontend/src/lib/components/common/table/FlowRow.svelte b/frontend/src/lib/components/common/table/FlowRow.svelte index ca8648baed..65690121ab 100644 --- a/frontend/src/lib/components/common/table/FlowRow.svelte +++ b/frontend/src/lib/components/common/table/FlowRow.svelte @@ -1,6 +1,5 @@ <script lang="ts"> import { goto } from '$lib/navigation' - import { base } from '$lib/base' import Dropdown from '$lib/components/DropdownV2.svelte' import type MoveDrawer from '$lib/components/MoveDrawer.svelte' import ScheduleEditor from '$lib/components/triggers/schedules/ScheduleEditor.svelte' @@ -9,7 +8,7 @@ import type ShareModal from '$lib/components/ShareModal.svelte' import { FlowService, type Flow } from '$lib/gen' import { userStore, userWorkspaces, workspaceStore } from '$lib/stores' - import { useOperatorBuilderFlows } from '$lib/operatorWriteRights' + import { useEditRights } from '$lib/operatorWriteRights' import { UserDraftDbSyncer } from '$lib/userDraftDbSyncer.svelte' import { createEventDispatcher } from 'svelte' import Badge from '../badge/Badge.svelte' @@ -43,7 +42,7 @@ import EditInForkButton from './EditInForkButton.svelte' import { isCloudHosted } from '$lib/cloud' - const operatorBuilderFlows = useOperatorBuilderFlows() + const editRights = useEditRights() interface Props { flow: Flow & { @@ -125,7 +124,7 @@ let scheduleEditor: ScheduleEditor | undefined = $state(undefined) let flowHistory: FlowHistory | undefined = $state(undefined) - let hideForOperator = $derived($userStore?.operator && !$operatorBuilderFlows) + let hideForOperator = $derived(!editRights.roleCanAuthor('flow')) </script> {#if menuOpen} @@ -141,8 +140,8 @@ aiId={`flow-row-${flow.path}`} aiDescription={`Button to access the form to run the flow ${flow.summary ?? flow.path}`} href={flow.draft_only - ? `${base}/flows/edit/${flow.path}` - : `${base}/flows/get/${flow.path}?workspace=${$workspaceStore}`} + ? `/flows/edit/${flow.path}` + : `/flows/get/${flow.path}?workspace=${$workspaceStore}`} kind="flow" workspaceId={flow.workspace_id ?? $workspaceStore ?? ''} {keyboardSelected} @@ -200,7 +199,7 @@ wrapperClasses="w-20" unifiedSize="md" startIcon={{ icon: Pen }} - href="{base}/flows/edit/{flow.path}" + href="/flows/edit/{flow.path}" aiId={`edit-flow-button-${flow.summary?.length > 0 ? flow.summary : flow.path}`} aiDescription={`Edits the flow ${flow.summary?.length > 0 ? flow.summary : flow.path}`} > @@ -264,12 +263,12 @@ { displayName: 'View runs', icon: List, - href: `${base}/runs/${path}` + href: `/runs/${path}` }, { displayName: 'Duplicate/Fork', icon: GitFork, - href: `${base}/flows/add?template=${path}`, + href: `/flows/add?template=${path}`, disabled: !showEditButton, hide: hideForOperator }, @@ -287,7 +286,7 @@ { displayName: 'Audit logs', icon: Eye, - href: `${base}/audit_logs?resource=${path}`, + href: `/audit_logs?resource=${path}`, hide: $userStore?.operator }, { diff --git a/frontend/src/lib/components/common/table/PipelineRow.svelte b/frontend/src/lib/components/common/table/PipelineRow.svelte new file mode 100644 index 0000000000..334c8fb5fd --- /dev/null +++ b/frontend/src/lib/components/common/table/PipelineRow.svelte @@ -0,0 +1,154 @@ +<script lang="ts"> + import Dropdown from '$lib/components/DropdownV2.svelte' + import ConfirmationModal from '../confirmationModal/ConfirmationModal.svelte' + import { + deletePipeline, + planPipelineDelete, + type PipelineDeletePlan + } from '$lib/components/assets/AssetGraph/pipelineDelete' + import { userStore, workspaceStore } from '$lib/stores' + import { sendUserToast } from '$lib/toast' + import { Loader2, Trash } from 'lucide-svelte' + import Row from './Row.svelte' + + interface Props { + folder: string + depth?: number + /** Shown instead of `f/<folder>`, e.g. under the folder's own tree node. */ + label?: string + onDeleted?: () => void + } + + let { folder, depth = 0, label, onDeleted }: Props = $props() + + let confirmOpen = $state(false) + let deleting = $state(false) + let plan = $state<PipelineDeletePlan | undefined>(undefined) + let planError = $state<string | undefined>(undefined) + // The backend deletes scripts for admins only; everyone else archives them. + let hardDelete = $derived(!!($userStore?.is_admin || $userStore?.is_super_admin)) + + async function openConfirm() { + const ws = $workspaceStore + if (!ws) return + plan = undefined + planError = undefined + confirmOpen = true + try { + plan = await planPipelineDelete(ws, folder) + } catch (e: any) { + planError = e?.body ?? e?.message ?? String(e) + } + } + + async function confirmDelete() { + const ws = $workspaceStore + if (!ws || !plan) return + deleting = true + try { + const { removed, failures } = await deletePipeline(ws, folder, plan, hardDelete) + // Loaded on demand: the home list should not pull in the session runtime. + const { forgetDeletedPipeline } = await import( + '$lib/components/sessions/sessionRuntime.svelte' + ) + forgetDeletedPipeline(ws, folder) + if (failures.length) { + sendUserToast(`Pipeline f/${folder} was only partly removed`, true, [], failures.join('\n')) + } else { + sendUserToast(`Removed pipeline f/${folder} (${removed} item${removed === 1 ? '' : 's'})`) + } + onDeleted?.() + } catch (e: any) { + sendUserToast(`Could not remove pipeline f/${folder}: ${e?.body ?? e?.message ?? e}`, true) + } finally { + deleting = false + confirmOpen = false + } + } +</script> + +<Row + kind="data_pipeline" + marked={undefined} + href="/pipeline/{encodeURIComponent(folder)}" + workspaceId={$workspaceStore ?? ''} + path={`f/${folder}`} + summary={label ?? `Pipeline · ${folder}`} + canFavorite={false} + {depth} +> + {#snippet actions()} + {#if !$userStore?.operator} + <Dropdown + items={[ + { + displayName: 'Delete', + icon: Trash, + type: 'delete', + action: () => void openConfirm() + } + ]} + /> + {/if} + {/snippet} +</Row> + +<ConfirmationModal + open={confirmOpen} + title="Delete pipeline f/{folder}" + confirmationText={hardDelete ? 'Delete' : 'Archive'} + loading={deleting} + confirmDisabled={!plan} + trashbin={hardDelete} + on:canceled={() => (confirmOpen = false)} + on:confirmed={confirmDelete} +> + <div class="flex flex-col gap-3 text-xs"> + {#if planError} + <span class="text-red-600 dark:text-red-400">Could not list the pipeline: {planError}</span> + {:else if !plan} + <span class="flex items-center gap-2 text-secondary"> + <Loader2 size={14} class="animate-spin" /> Listing what this removes… + </span> + {:else} + {#if plan.scripts.some((s) => !s.draftOnly)} + {@render group( + hardDelete ? 'Scripts deleted' : 'Scripts archived', + plan.scripts.filter((s) => !s.draftOnly).map((s) => s.displayPath) + )} + {/if} + {#if plan.scripts.some((s) => s.draftOnly)} + {@render group( + 'Draft scripts discarded', + plan.scripts.filter((s) => s.draftOnly).map((s) => s.displayPath) + )} + {/if} + {#if plan.triggers.length} + {@render group( + 'Triggers deleted', + plan.triggers.map((t) => `${t.path} (${t.kind})`) + )} + {/if} + {#if plan.hasDraft} + {@render group('Unsaved pipeline changes discarded', ['Your pipeline draft'])} + {/if} + {#if !plan.scripts.length && !plan.triggers.length && !plan.hasDraft} + <span class="text-secondary">Nothing left to remove in this pipeline.</span> + {/if} + <span class="text-secondary"> + The tables and files the pipeline wrote are kept, and so is the folder f/{folder}. + </span> + {/if} + </div> +</ConfirmationModal> + +{#snippet group(title: string, entries: string[])} + <div class="flex flex-col gap-1"> + <span class="font-semibold text-emphasis">{title} ({entries.length})</span> + <ul class="max-h-40 overflow-auto rounded-md border bg-surface-secondary px-3 py-1.5"> + {#each entries as entry (entry)} + <li class="font-mono text-2xs text-primary truncate">{entry}</li> + {/each} + </ul> + </div> +{/snippet} diff --git a/frontend/src/lib/components/common/table/RawAppRow.svelte b/frontend/src/lib/components/common/table/RawAppRow.svelte index ff31eb1aea..be1c9f0150 100644 --- a/frontend/src/lib/components/common/table/RawAppRow.svelte +++ b/frontend/src/lib/components/common/table/RawAppRow.svelte @@ -1,5 +1,4 @@ <script lang="ts"> - import { base } from '$lib/base' import Dropdown from '$lib/components/DropdownV2.svelte' import SharedBadge from '$lib/components/SharedBadge.svelte' import type ShareModal from '$lib/components/ShareModal.svelte' @@ -33,7 +32,7 @@ </script> <Row - href="{base}/apps_raw/get/{app.path}" + href="/apps_raw/get/{app.path}" kind="raw_app" {keyboardSelected} {marked} diff --git a/frontend/src/lib/components/common/table/Row.svelte b/frontend/src/lib/components/common/table/Row.svelte index 76cd30640a..01fb70e118 100644 --- a/frontend/src/lib/components/common/table/Row.svelte +++ b/frontend/src/lib/components/common/table/Row.svelte @@ -211,7 +211,7 @@ <!-- The icon slot itself: the kind icon until the row is hovered (or selection mode is on), the checkbox from then on. Both are stacked in a fixed 16px box and swapped with visibility so nothing shifts. --> - <div class="shrink relative w-4 h-4"> + <div class="shrink-0 relative w-4 h-4"> <div class={twMerge( 'absolute inset-0', @@ -260,12 +260,12 @@ </div> {/if} - {#if canFavorite && (kind == 'app' || kind == 'raw_app' || kind == 'script' || kind == 'flow')} - <div class="center-center h-full text-xs font-semibold text-secondary w-9"> + {#if canFavorite && (kind == 'app' || kind == 'raw_app' || kind == 'script' || kind == 'flow' || kind == 'agent')} + <div class="center-center h-full text-xs font-semibold text-secondary w-9 shrink-0"> <Star {kind} {path} {workspaceId} {summary} /> </div> {:else} - <div class="w-9"></div> + <div class="w-9 shrink-0"></div> {/if} <div data-row-actions class="flex gap-1 items-center justify-end pr-2"> @@ -275,25 +275,26 @@ {#snippet rowContent(withIcon: boolean)} {#if withIcon} - <div class="shrink"> + <div class="shrink-0"> <RowIcon {kind} {triggerKind} /> </div> {/if} <div class="grow min-w-0"> - <div - class={twMerge( - 'text-emphasis flex-wrap text-left text-xs font-semibold', - titleBadge ? 'inline-flex items-center gap-2' : '' - )} - > + <div class="text-emphasis flex items-center gap-2 text-left text-xs font-semibold"> {#if customSummary} - {@render customSummary?.()} - {:else if marked} - {@html marked} + <div class="min-w-0">{@render customSummary()}</div> {:else} - {!summary || summary.length == 0 ? displayPath : summary} + <span class="truncate" title={summary || displayPath}> + {#if marked} + {@html marked} + {:else} + {!summary || summary.length == 0 ? displayPath : summary} + {/if} + </span> + {/if} + {#if titleBadge} + <span class="shrink-0">{@render titleBadge()}</span> {/if} - {@render titleBadge?.()} </div> <div class="text-hint text-3xs truncate text-left font-normal" title={path}> {#if pathDisplay} diff --git a/frontend/src/lib/components/common/table/ScriptRow.svelte b/frontend/src/lib/components/common/table/ScriptRow.svelte index 938086a0e8..7ba327f343 100644 --- a/frontend/src/lib/components/common/table/ScriptRow.svelte +++ b/frontend/src/lib/components/common/table/ScriptRow.svelte @@ -1,6 +1,5 @@ <script lang="ts"> import { goto } from '$lib/navigation' - import { base } from '$lib/base' import Dropdown from '$lib/components/DropdownV2.svelte' import type MoveDrawer from '$lib/components/MoveDrawer.svelte' import ScheduleEditor from '$lib/components/triggers/schedules/ScheduleEditor.svelte' @@ -157,8 +156,8 @@ aiId={`script-run-button-${script.path}`} aiDescription={`Button to access the form to run the script ${script.summary ?? script.path}`} href={script.draft_only || (script.auto_kind === 'lib' && script.kind !== 'preprocessor') - ? `${base}/scripts/edit/${script.path}` - : `${base}/scripts/get/${script.hash}?workspace=${$workspaceStore}`} + ? `/scripts/edit/${script.path}` + : `/scripts/get/${script.hash}?workspace=${$workspaceStore}`} kind="script" {keyboardSelected} {marked} @@ -261,7 +260,7 @@ wrapperClasses="w-20" unifiedSize="md" startIcon={{ icon: Pen }} - href="{base}/scripts/edit/{script.path}" + href="/scripts/edit/{script.path}" > Edit </Button> @@ -351,7 +350,7 @@ { displayName: 'Duplicate/Fork', icon: GitFork, - href: `${base}/scripts/add?template=${script.path}`, + href: `/scripts/add?template=${script.path}`, disabled: !showEditButton, hide: $userStore?.operator }, @@ -391,7 +390,7 @@ { displayName: 'View runs', icon: List, - href: `${base}/runs/${script.path}` + href: `/runs/${script.path}` }, { displayName: 'Versions', @@ -403,7 +402,7 @@ { displayName: 'Audit logs', icon: Eye, - href: `${base}/audit_logs?resource=${script.path}`, + href: `/audit_logs?resource=${script.path}`, hide: $userStore?.operator }, { diff --git a/frontend/src/lib/components/common/teams/TeamsConnectionStatus.svelte b/frontend/src/lib/components/common/teams/TeamsConnectionStatus.svelte index ce368e93b9..64b9269f3d 100644 --- a/frontend/src/lib/components/common/teams/TeamsConnectionStatus.svelte +++ b/frontend/src/lib/components/common/teams/TeamsConnectionStatus.svelte @@ -1,7 +1,6 @@ <script lang="ts"> import { Badge, Button } from '$lib/components/common' import { Plug, RotateCw, Unplug } from 'lucide-svelte' - import { base } from '$lib/base' interface Props { isConnected: boolean | undefined @@ -15,7 +14,7 @@ // Connection URLs based on mode let connectUrl = $derived( - mode === 'instance' ? `${base}/#superadmin-settings` : `${base}/workspace_settings?tab=teams` + mode === 'instance' ? `/#superadmin-settings` : `/workspace_settings?tab=teams` ) </script> diff --git a/frontend/src/lib/components/copilot/AIFormAssistant.svelte b/frontend/src/lib/components/copilot/AIFormAssistant.svelte index b4526f1153..48a46ad182 100644 --- a/frontend/src/lib/components/copilot/AIFormAssistant.svelte +++ b/frontend/src/lib/components/copilot/AIFormAssistant.svelte @@ -8,7 +8,6 @@ import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' import { copilotInfo } from '$lib/aiStore' import { logFeatureUsage } from '$lib/utils/featureUsage' - import { pageHref } from '$lib/components/sessions/previewPaths' interface Props { /** Unset for a viewer who cannot edit the item: the card then offers no way to the editor. */ @@ -45,7 +44,7 @@ const sessionSource = $derived( path ? { - page: () => pageHref(`/${runnableType}s/get/${path}`), + page: () => `/${runnableType}s/get/${path}`, workspaceId: $operatingWorkspace ?? undefined, beforeOpen: logAsked } diff --git a/frontend/src/lib/components/copilot/CronGen.svelte b/frontend/src/lib/components/copilot/CronGen.svelte index 94715a0f18..5e54136f07 100644 --- a/frontend/src/lib/components/copilot/CronGen.svelte +++ b/frontend/src/lib/components/copilot/CronGen.svelte @@ -5,7 +5,6 @@ import Popover from '$lib/components/meltComponents/Popover.svelte' import { sendUserToast } from '$lib/toast' - import { base } from '$lib/base' import type { ChatCompletionMessageParam } from 'openai/resources/index.mjs' import { copilotInfo } from '$lib/aiStore' import { untrack } from 'svelte' @@ -83,8 +82,7 @@ <Popover floatingConfig={{ strategy: 'absolute', placement: 'bottom-end' }}> {#snippet trigger()} <Button - color={genLoading ? 'red' : 'light'} - size="xs" + unifiedSize="md" nonCaptureEvent={!genLoading} startIcon={{ icon: Wand2 }} iconOnly @@ -132,7 +130,7 @@ <div class="block text-primary"> <p class="text-sm" >Enable Windmill AI in the <a - href="{base}/workspace_settings?tab=ai" + href="/workspace_settings?tab=ai" target="_blank" class="inline-flex flex-row items-center gap-1" >workspace settings <ExternalLink size={16} /></a diff --git a/frontend/src/lib/components/copilot/FlowInlineScriptAIButton.svelte b/frontend/src/lib/components/copilot/FlowInlineScriptAIButton.svelte index 29ce045042..45df865c11 100644 --- a/frontend/src/lib/components/copilot/FlowInlineScriptAIButton.svelte +++ b/frontend/src/lib/components/copilot/FlowInlineScriptAIButton.svelte @@ -3,7 +3,6 @@ import Popover from '$lib/components/meltComponents/Popover.svelte' import Button from '../common/button/Button.svelte' import { ExternalLink, WandSparkles } from 'lucide-svelte' - import { base } from '$lib/base' import { twMerge } from 'tailwind-merge' import { aiChatManager, AIMode } from './chat/AIChatManager.svelte' import { chatState } from './chat/sharedChatState.svelte' @@ -97,7 +96,7 @@ <div class="p-4"> <p class="text-sm"> Enable Windmill AI in the <a - href="{base}/workspace_settings?tab=ai" + href="/workspace_settings?tab=ai" target="_blank" class="inline-flex flex-row items-center gap-1" > diff --git a/frontend/src/lib/components/copilot/RegexGen.svelte b/frontend/src/lib/components/copilot/RegexGen.svelte index f399726988..32fdc4a5f1 100644 --- a/frontend/src/lib/components/copilot/RegexGen.svelte +++ b/frontend/src/lib/components/copilot/RegexGen.svelte @@ -1,7 +1,6 @@ <script lang="ts"> import { run } from 'svelte/legacy' - import { base } from '$lib/base' import { Button } from '../common' import { getNonStreamingMetadataCompletion } from './lib' @@ -172,7 +171,7 @@ {:else} <p class="text-sm"> Enable Windmill AI in the <a - href="{base}/workspace_settings?tab=ai" + href="/workspace_settings?tab=ai" target="_blank" class="inline-flex flex-row items-center gap-1" > diff --git a/frontend/src/lib/components/copilot/ResourceGen.svelte b/frontend/src/lib/components/copilot/ResourceGen.svelte index 2fc3cfa646..0d21635e77 100644 --- a/frontend/src/lib/components/copilot/ResourceGen.svelte +++ b/frontend/src/lib/components/copilot/ResourceGen.svelte @@ -4,7 +4,6 @@ import { getNonStreamingMetadataCompletion } from './lib' import Popover from '$lib/components/meltComponents/Popover.svelte' import { sendUserToast } from '$lib/toast' - import { base } from '$lib/base' import type { ChatCompletionMessageParam } from 'openai/resources/index.mjs' import { copilotInfo } from '$lib/aiStore' import type { Schema } from '$lib/common' @@ -175,7 +174,7 @@ <div class="block text-primary"> <p class="text-sm" >Enable Windmill AI in the <a - href="{base}/workspace_settings?tab=ai" + href="/workspace_settings?tab=ai" target="_blank" class="inline-flex flex-row items-center gap-1" >workspace settings <ExternalLink size={16} /></a diff --git a/frontend/src/lib/components/copilot/ScriptFix.svelte b/frontend/src/lib/components/copilot/ScriptFix.svelte index 78c4804cc8..bc6fca10d5 100644 --- a/frontend/src/lib/components/copilot/ScriptFix.svelte +++ b/frontend/src/lib/components/copilot/ScriptFix.svelte @@ -1,5 +1,4 @@ <script lang="ts"> - import { base } from '$lib/base' import { Button } from '../common' import { SUPPORTED_LANGUAGES } from './lib' @@ -139,7 +138,7 @@ <p class="text-sm" >Enable Windmill AI in the <a class="inline-flex flex-row items-center gap-1" - href="{base}/workspace_settings?tab=ai" + href="/workspace_settings?tab=ai" target="_blank">workspace settings</a ></p ></div diff --git a/frontend/src/lib/components/copilot/ScriptGen.svelte b/frontend/src/lib/components/copilot/ScriptGen.svelte index fea738b8f1..4b141ec228 100644 --- a/frontend/src/lib/components/copilot/ScriptGen.svelte +++ b/frontend/src/lib/components/copilot/ScriptGen.svelte @@ -1,5 +1,4 @@ <script lang="ts"> - import { base } from '$lib/base' import { Button } from '../common' import { MAX_SCHEMA_LENGTH, SUPPORTED_LANGUAGES, addThousandsSeparator, copilot } from './lib' @@ -528,7 +527,7 @@ {:else} <p class="text-sm"> Enable Windmill AI in the <a - href="{base}/workspace_settings?tab=ai" + href="/workspace_settings?tab=ai" target="_blank" class="inline-flex flex-row items-center gap-1" > diff --git a/frontend/src/lib/components/copilot/StepInputsGen.svelte b/frontend/src/lib/components/copilot/StepInputsGen.svelte index c9ef616aa5..2fd93866d3 100644 --- a/frontend/src/lib/components/copilot/StepInputsGen.svelte +++ b/frontend/src/lib/components/copilot/StepInputsGen.svelte @@ -1,5 +1,4 @@ <script lang="ts"> - import { base } from '$lib/base' import YAML from 'yaml' import { yamlStringifyExceptKeys } from './utils' import { sliceModules } from '../flows/flowStateUtils.svelte' @@ -252,7 +251,7 @@ input_name2: expression2 {#if !$copilotInfo.enabled} Enable Windmill AI in the{' '} <a - href="{base}/workspace_settings?tab=ai" + href="/workspace_settings?tab=ai" target="_blank" class="inline-flex flex-row items-center gap-1" > diff --git a/frontend/src/lib/components/copilot/chat/AIButton.svelte b/frontend/src/lib/components/copilot/chat/AIButton.svelte index 7420e8d6b7..8b23237ebf 100644 --- a/frontend/src/lib/components/copilot/chat/AIButton.svelte +++ b/frontend/src/lib/components/copilot/chat/AIButton.svelte @@ -1,5 +1,4 @@ <script lang="ts"> - import { base } from '$lib/base' import { copilotInfo } from '$lib/aiStore' import { aiUserDisabled } from '$lib/stores' import Popover from '$lib/components/meltComponents/Popover.svelte' @@ -50,7 +49,7 @@ {:else} <p class="text-sm" >Enable Windmill AI in the <a - href="{base}/workspace_settings?tab=ai" + href="/workspace_settings?tab=ai" target="_blank" class="inline-flex flex-row items-center gap-1" >workspace settings <ExternalLink size={16} /></a diff --git a/frontend/src/lib/components/copilot/chat/AIChat.svelte b/frontend/src/lib/components/copilot/chat/AIChat.svelte index fd95613f2e..301a8dba54 100644 --- a/frontend/src/lib/components/copilot/chat/AIChat.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChat.svelte @@ -7,7 +7,6 @@ import { getAiChatManager } from './aiChatManagerContext' const aiChatManager = getAiChatManager() - import { base } from '$lib/base' import HideButton from '$lib/components/apps/editor/settingsPanel/HideButton.svelte' import { SUPPORTED_CHAT_SCRIPT_LANGUAGES } from './script/core' import { copilotInfo } from '$lib/aiStore' @@ -74,7 +73,7 @@ : $aiUserDisabled ? 'Windmill AI is disabled in your account settings' : isAdmin - ? `Enable Windmill AI in your [workspace settings](${base}/workspace_settings?tab=ai) to use this chat` + ? 'Enable Windmill AI in your [workspace settings](/workspace_settings?tab=ai) to use this chat' : 'Ask an admin to enable Windmill AI in this workspace to use this chat' : aiChatManager.mode === AIMode.SCRIPT && aiChatManager.scriptEditorOptions?.lang && diff --git a/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte b/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte index d5406aeca2..1060a64110 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChatDisplay.svelte @@ -71,7 +71,6 @@ import { sendUserToast } from '$lib/toast' import Alert from '$lib/components/common/alert/Alert.svelte' import { copilotInfo } from '$lib/aiStore' - import { base } from '$lib/base' const MAX_YOLO_TOOLTIP_TOOLS = 8 const chatHost = getChatViewHost() @@ -713,7 +712,7 @@ unifiedSize="2xs" variant="accent" startIcon={{ icon: KeyRound }} - href="{base}/workspace_settings?tab=ai" + href="/workspace_settings?tab=ai" > Add your own API key </Button> @@ -733,7 +732,7 @@ unifiedSize="2xs" variant="default" startIcon={{ icon: KeyRound }} - href="{base}/workspace_settings?tab=ai" + href="/workspace_settings?tab=ai" > Configure your API key </Button> @@ -1107,16 +1106,13 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. --> </Tooltip> {:else if canAttachFiles} <DropdownV2 - items={async () => { - // Both submenus fetch on the menu's first open, so they start - // together: awaited inline they queue, and the whole menu — - // attachments included — waits out two round trips. + items={() => { const closeMenu = () => (plusMenuOpen = false) const inGlobal = chatHost.mode === AIMode.GLOBAL - const [skillItems, mcpItems] = await Promise.all([ - inGlobal ? skillsMenu.items(closeMenu) : undefined, - inGlobal ? mcpMenu.items(closeMenu) : undefined - ]) + if (inGlobal) { + skillsMenu.refresh() + mcpMenu.refresh() + } return [ { displayName: 'Attach file or image', @@ -1156,23 +1152,24 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. --> } ] : []), - ...(skillItems + ...(inGlobal ? [ { displayName: 'Skills', icon: BookOpen, separatorTop: true, - submenuItems: skillItems - } - ] - : []), - ...(mcpItems - ? [ + // Getters so the submenus fill in when their fetch lands + // rather than the whole menu waiting on it. + get submenuItems() { + return skillsMenu.items(closeMenu) + } + }, { displayName: 'MCP connections', icon: Plug, - separatorTop: !skillItems, - submenuItems: mcpItems + get submenuItems() { + return mcpMenu.items(closeMenu) + } } ] : []) diff --git a/frontend/src/lib/components/copilot/chat/AIChatInput.svelte b/frontend/src/lib/components/copilot/chat/AIChatInput.svelte index bcea3a26d6..41ea788fac 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatInput.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChatInput.svelte @@ -50,6 +50,7 @@ type AttachedBlob } from './blobUtils' import { MessageDraft } from './messageDraft.svelte' + import { useSessionPermissions } from '$lib/components/sessions/sessionPermissions.svelte' import ExpandableImage, { isImageViewerOpen } from '$lib/components/common/image/ExpandableImage.svelte' @@ -134,10 +135,28 @@ 'Refactor a script to add error handling', 'List my workspace flows and scripts' ] - const globalSuggestion = - GLOBAL_PLACEHOLDER_SUGGESTIONS[ - Math.floor(Math.random() * GLOBAL_PLACEHOLDER_SUGGESTIONS.length) - ] + // An operator authors nothing, so nothing above is theirs to ask for; one with the + // workspace's builder right can compose flows out of deployed scripts as well. + const OPERATOR_PLACEHOLDER_SUGGESTIONS = [ + 'List my workspace flows and scripts', + 'Show the runs that failed today and why', + 'Find the script that sends a report and run it', + 'Rerun the last failed run of a flow' + ] + const BUILDER_PLACEHOLDER_SUGGESTIONS = [ + ...OPERATOR_PLACEHOLDER_SUGGESTIONS, + 'Compose a flow that chains two deployed scripts' + ] + const permissions = useSessionPermissions(() => chatHost.operatingWorkspace) + const suggestionPick = Math.random() + const globalSuggestion = $derived.by(() => { + const pool = permissions.canOpenEditor('script') + ? GLOBAL_PLACEHOLDER_SUGGESTIONS + : permissions.canOpenEditor('flow') + ? BUILDER_PLACEHOLDER_SUGGESTIONS + : OPERATOR_PLACEHOLDER_SUGGESTIONS + return pool[Math.floor(suggestionPick * pool.length)] + }) // Generate mode-specific placeholder const modePlaceholder = $derived.by(() => { diff --git a/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts b/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts index 8b0c346244..8bbc45721d 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts +++ b/frontend/src/lib/components/copilot/chat/AIChatManager.svelte.ts @@ -25,6 +25,7 @@ import { type ToolCallbacks, type ToolDisplayMessage, type UserQuestionDisplay, + type RunFormAnswer, type RunFormDisplay, type RunFormDraft, type ChatJob, @@ -49,10 +50,14 @@ import { import type { ScriptLintResult } from './shared' import { navigatorTools, prepareNavigatorSystemMessage } from './navigator/core' import { loadApiTools } from './api/apiTools' -import { prepareScriptUserMessage } from './script/core' +import { + prepareScriptUserMessage, + resolveResourceTypeSync, + type ResourceTypeSync +} from './script/core' import { prepareNavigatorUserMessage } from './navigator/core' import { sendUserToast } from '$lib/toast' -import { workspaceAIClients, getStreamedCompletionText } from '../lib' +import { AI_PROVIDERS, workspaceAIClients, getStreamedCompletionText } from '../lib' import { logFeatureUsage } from '$lib/utils/featureUsage' import { modelSupportsVision } from '../modelConfig' import { getEffectiveModelContextWindow } from '../modelConfig' @@ -168,7 +173,11 @@ import type { ArtifactVersionTarget } from '$lib/components/sessions/previewRout import { appendAttachedFilesRoster } from './files/fileTools' import { ENTER_PLAN_MODE_TOOL, EXIT_PLAN_MODE_TOOL } from './planMode' import { PlanModeController, type PlanModeHost } from './planModeController.svelte' -import { navigationOperatorBuilderFlows } from '$lib/operatorWriteRights' +import { + navigationOperatorBuilderApps, + navigationOperatorBuilderFlows, + navigationOperatorBuilderRights +} from '$lib/operatorWriteRights' // Compaction of the stored history: once the projected request size // (contextTokens — the provider's report when current, a fresh chars/4 @@ -220,7 +229,7 @@ const settledRunForm = (runForm: RunFormDisplay): RunFormDisplay => type PendingRunForm = { /** Absent once the loop is no longer waiting: a card restored from history still mounts * its form and still holds edits, but nothing is left to receive them. */ - resolve?: (args: Record<string, any> | undefined) => void + resolve?: (answer: RunFormAnswer | undefined) => void draft: RunFormDraft submitting: boolean } @@ -242,12 +251,12 @@ const WEB_SEARCH_ERROR_HINT = const REASONING_SUMMARY_WARNED_STORAGE_KEY = 'ai-chat-reasoning-summary-unverified-warned' function providerDisplayName(provider: string): string { - return provider === 'azure_openai' ? 'Azure OpenAI' : 'OpenAI' + return AI_PROVIDERS[provider as keyof typeof AI_PROVIDERS]?.label ?? 'OpenAI' } function reasoningSummaryUnavailableMessage(provider: string): string { const verifyHint = - provider === 'azure_openai' + provider === 'azure_openai' || provider === 'azure_foundry' ? 'To display it, verify your organization with your provider, then reload this page.' : 'To display it, verify your organization in the OpenAI platform settings (Settings > General), then reload this page.' return `This model is reasoning, but your ${providerDisplayName(provider)} organization is not verified to generate reasoning summaries, so its thinking stays hidden. ${verifyHint}` @@ -301,7 +310,9 @@ export function supportsPlanMode(mode: AIMode): boolean { return PLAN_MODES.has(mode) } +const isOperatorBuilder = fromStore(navigationOperatorBuilderRights) const isOperatorBuilderFlows = fromStore(navigationOperatorBuilderFlows) +const isOperatorBuilderApps = fromStore(navigationOperatorBuilderApps) export function isAIModeVisible(mode: AIMode): boolean { return mode !== AIMode.GLOBAL || isGlobalAiEnabled() @@ -501,11 +512,17 @@ export class AIChatManager implements ChatViewHost { skipResponsesApi = $state(false) mode = $state<AIMode>(AIMode.NAVIGATOR) - pipelineAiChatHelpers = $state<PipelineAIChatHelpers | undefined>(undefined) + // One per mounted pipeline editor; a session can have several folders open. + #pipelineEditors = new Set<PipelineAIChatHelpers>() // Resolved when a pipeline editor registers its tools. open_preview(pipeline) // awaits this so the model's next build_pipeline_node call can't race ahead of // the async canvas mount and hit "Unknown tool call". - #pipelineHelpersWaiters = new Set<() => void>() + #pipelineHelpersWaiters = new Set<(helpers: PipelineAIChatHelpers) => void>() + // A session's pipeline editor unmounts whenever another tab takes the preview + // panel. Its tools stay offered for every folder the session opened, and a call + // reopens the tab through this, so a page shown in between costs no failed call. + #pipelineReopener: ((folder: string) => void) | undefined = undefined + #openedPipelineFolders = new Set<string>() readonly isOpen = $derived(chatState.size > 0) savedSize = $state<number>(0) instructions = $state<string>('') @@ -570,6 +587,23 @@ export class AIChatManager implements ChatViewHost { * chat card holds. Unset outside a session: a chat-bound form has nowhere else to go, * so the card hides the control rather than offering a tab that cannot run. */ openRunForm?: (a: { toolCallId: string; label: string }) => void + /** Show a DEPLOYED run's item on its own page. With `carries`, that page is handed this + * call: it opens its own form on what the call proposed, and the job its Run starts is + * the one the tool follows. Without it the page is only opened to look at — a + * conversational flow's page has no form to confirm on — and the card keeps the run. Set + * only where that page can be shown, a session's preview panel, so the card hides the + * control elsewhere. */ + openRunOnDeployedPage?: (a: { + toolCallId: string + kind: 'script' | 'flow' + path: string + summary: string + carries: boolean + /** Re-point a tab already on that page, and answer `false` rather than opening one. + * For handing a call to a page the reader already has in front of them: a tab showing + * something else, a run included, has no form to confirm this call on. */ + onlyIfAlreadyOpen?: boolean + }) => boolean closeRunForm?: (toolCallId: string) => void /** Hands that tab from the form to the run it just started, in place: the tab keeps its * position in the strip and stays active if it was. */ @@ -579,11 +613,16 @@ export class AIChatManager implements ChatViewHost { workspace: string label: string }) => void - /** Whether the panel holds this call's pending form. Answered off the session's tab list, - * so it stays true while the user is on another tab, and per call rather than "the open - * one". Read from a `$derived` — the reader subscribes to the tab list through the call. - * The card hides its form on it, which is what keeps exactly one mounted per call. */ + /** Whether the panel holds this call's pending form, on either surface. Answered off the + * session's tab list, so it stays true while the user is on another tab, and per call + * rather than "the open one". Read from a `$derived` — the reader subscribes to the tab + * list through the call. The card folds its row on it, and a started job takes over + * whichever surface was waiting. */ isRunFormInPreview?: (toolCallId: string) => boolean + /** Whether the panel holds this call on the chat's own form, as opposed to on the item's + * page. The card's form is exclusive with this one alone: it is the same draft, and two + * mounts of it each reorder the schema SchemaForm edits in place. */ + isRunFormTabOpen?: (toolCallId: string) => boolean openArtifact?: (artifactId: string, name: string, version?: ArtifactVersionTarget) => void closeArtifact?: (artifactId: string) => void #loading = $state<boolean>(false) @@ -900,6 +939,15 @@ export class AIChatManager implements ChatViewHost { await this.#persistModifiedItems() } + // Record the items deploying a chat-modified item produced — a pipeline's + // scripts — so a fork review selects exactly them. Persisted at once, like a + // discard: the deploy can run outside any turn. + async recordDeployedItems(itemKind: UserDraftItemKind, storagePaths: string[]) { + if (!this.modifiedItems || storagePaths.length === 0) return + for (const p of storagePaths) this.modifiedItems.add(maskKey(itemKind, p)) + await this.#persistModifiedItems() + } + // Move a mask entry to the path a draft actually deployed to. A draft-only // flow/app parks at a synthetic `draft_{uuid}` storage path and deploys to // its chosen path — without the move, the existence check at the synthetic @@ -1438,20 +1486,23 @@ export class AIChatManager implements ChatViewHost { .map((s) => ({ ...s, kind: 'skill' as const })) ]) - // The flow and script builders both write code, which the backend refuses from an operator - // with the builder right: leaving them reachable would only produce work that cannot be + // The flow, app and script builders all write code, which the backend refuses from an + // operator with builder rights: leaving them reachable would only produce work that cannot be // deployed. allowedModes: Record<AIMode, boolean> = $derived({ script: this.flowAiChatHelpers === undefined && this.scriptEditorOptions !== undefined && !this.disabledModes.script && - !isOperatorBuilderFlows.current, + !isOperatorBuilder.current, flow: this.flowAiChatHelpers !== undefined && !this.disabledModes.flow && !isOperatorBuilderFlows.current, - app: this.appAiChatHelpers !== undefined && !this.disabledModes.app, + app: + this.appAiChatHelpers !== undefined && + !this.disabledModes.app && + !isOperatorBuilderApps.current, navigator: !this.disabledModes.navigator, ask: !this.disabledModes.ask, API: !this.disabledModes.API, @@ -2003,7 +2054,7 @@ export class AIChatManager implements ChatViewHost { toolId: string, form: RunFormDisplay, opts?: { autoAccepted?: boolean } - ): Promise<Record<string, any> | undefined> => { + ): Promise<RunFormAnswer | undefined> => { // The tool reads the schema before it asks, so a stop during that read drains the // callbacks and settles the card before this runs. Installing one then would park // the turn on a form the settled card no longer renders, leaving nothing able to @@ -2020,15 +2071,32 @@ export class AIChatManager implements ChatViewHost { // Ahead of the wait, not of the stop above: the caller settled this form before // attaching it, so its card renders no fields and nothing here could ever resolve. if (opts?.autoAccepted) { - return Promise.resolve(form.args) + return Promise.resolve({ kind: 'args' as const, args: form.args }) } // Seeded from the caller's copy, before the card renders: the file arguments on // `displayMessages` are redacted, so a draft built from those would open the form on // the marker rather than on the bytes the model proposed. const entry = this.#runFormEntry(toolId, form) - return new Promise((resolve) => { + const answer = new Promise<RunFormAnswer | undefined>((resolve) => { this.#runForms.set(toolId, { ...entry, resolve }) }) + // A tab already on this item's deployed page is where the reader would be sent anyway, + // so the call goes there without waiting to be asked: declining a proposal and having + // the agent propose another leaves that page open, and the second proposal belongs on + // it. Only a tab already there — opening one for every proposed run would take the + // panel away from whatever the reader is doing. After the resolve above is installed, + // since the page reads the call back through `isRunFormPending`. + if (form.kind === 'run' && form.path && !form.conversational) { + this.openRunOnDeployedPage?.({ + toolCallId: toolId, + kind: form.runnableKind === 'flow' ? 'flow' : 'script', + path: form.path, + summary: form.summary || form.path, + carries: true, + onlyIfAlreadyOpen: true + }) + } + return answer } /** @@ -2056,6 +2124,10 @@ export class AIChatManager implements ChatViewHost { markRunFormStarted = (toolId: string) => this.#patchRunForm(toolId, { started: true }) + // Nothing to patch on the card — it already carries the tool's own error — so this exists + // for the surfaces that confirmed the run and would otherwise wait forever for a job. + markRunFormEnded = (toolId: string) => this.closeRunForm?.(toolId) + // A form restored from history has an entry once it mounts, but no resolve: the loop // that opened it is gone. isRunFormPending = (toolId: string): boolean => !!this.#runForms.get(toolId)?.resolve @@ -2089,10 +2161,34 @@ export class AIChatManager implements ChatViewHost { * leaving its submit button spinning on a run that will never start. */ handleRunFormSubmit = (toolId: string, args: Record<string, any>): boolean => { if (!this.isRunFormPending(toolId)) return false - this.#settleRunForm(toolId, args) + this.#settleRunForm(toolId, { kind: 'args', args }) return true } + /** The reader ran the item on its own page; the tool follows that job rather than + * starting one. False when the call is no longer waiting. */ + handleRunFormJob = ( + toolId: string, + jobId: string, + args: Record<string, any>, + schema: Record<string, any> + ): boolean => { + if (!this.isRunFormPending(toolId)) return false + // Snapshotted for the same reason the draft is: these are `$state` proxies off the + // page's own form, which keeps editing them after the run. + this.#settleRunForm(toolId, { + kind: 'job', + jobId, + args: ($state.snapshot(args) ?? {}) as Record<string, any>, + schema: ($state.snapshot(schema) ?? {}) as Record<string, any> + }) + return true + } + + /** What a parked form is waiting on, for a surface opening its own form on the same call. */ + pendingRunFormArgs = (toolId: string): Record<string, any> | undefined => + this.#runForms.get(toolId)?.draft?.args + handleRunFormCancel = (toolId: string) => { // The card's own copy is settled here rather than only in the tool's fn, which a form // restored from history no longer has: Cancel is that card's one way out, and while it @@ -2115,9 +2211,10 @@ export class AIChatManager implements ChatViewHost { */ #settleRunForm = ( toolId: string, - submitted: Record<string, any> | undefined, + answer: RunFormAnswer | undefined, card?: (runForm: RunFormDisplay) => Partial<ToolDisplayMessage> ) => { + const submitted = answer?.args const entry = this.#runForms.get(toolId) // Its draft holds whatever was typed into the form, a minted password included. this.#runForms.delete(toolId) @@ -2131,7 +2228,7 @@ export class AIChatManager implements ChatViewHost { submitted ? { submitted: true } : { canceled: true }, cancelledArgs ? (runForm) => ({ ...card?.(runForm), parameters: cancelledArgs }) : card ) - entry?.resolve?.(submitted) + entry?.resolve?.(answer) } /** @@ -2492,8 +2589,27 @@ export class AIChatManager implements ChatViewHost { // Public because it is purely local, unlike `changeMode(GLOBAL)`, which also // fires the three network refreshes. + setPipelineReopener = (reopen: (folder: string) => void) => { + this.#pipelineReopener = reopen + } + + #pipelineFolders = (): string[] => [ + ...new Set([ + ...[...this.#pipelineEditors].map((p) => p.getFolder()), + ...(this.#pipelineReopener ? this.#openedPipelineFolders : []) + ]) + ] + + #ensurePipeline = async (folder: string): Promise<PipelineAIChatHelpers | undefined> => { + const find = () => [...this.#pipelineEditors].find((p) => p.getFolder() === folder) + const live = find() + if (live || !this.#pipelineReopener) return live + this.#pipelineReopener(folder) + return (await this.waitForPipelineHelpers(folder)) ? find() : undefined + } + configureGlobalMode = () => { - const pipeline = this.pipelineAiChatHelpers + const hasPipelines = this.#pipelineFolders().length > 0 const opts = this.globalAssemblyOpts() const baseHelpers: GlobalToolHelpers = { // A session targets its own fixed (possibly forked) workspace, so capture it for @@ -2525,7 +2641,14 @@ export class AIChatManager implements ChatViewHost { } } this.#assembledTools = assembleGlobalTools(opts) - this.helpers = pipeline ? { ...baseHelpers, pipeline } : baseHelpers + this.helpers = hasPipelines + ? { + ...baseHelpers, + pipelines: () => [...this.#pipelineEditors], + pipelineFolders: this.#pipelineFolders, + ensurePipeline: this.#ensurePipeline + } + : baseHelpers this.systemMessage = assembleGlobalSystemMessage(getCustomPromptParts(AIMode.GLOBAL), opts) this.syncArtifactsSession() } @@ -2538,7 +2661,7 @@ export class AIChatManager implements ChatViewHost { mcpServers: this.mcpServers, access: this.sessionAccess, sessionContext: this.sessionContextResolver?.(), - pipelineContext: this.pipelineAiChatHelpers?.getPipelineContext() + pipelineFolders: this.#pipelineFolders() }) // Fetch the workspace's AI skills and, if GLOBAL mode is still active, rebuild @@ -2630,6 +2753,9 @@ export class AIChatManager implements ChatViewHost { this.systemMessage = { ...target, content: `${target.content}\n\n${section}` } } + /** Resolved per send with the rest of the pre-flight; see `resolveResourceTypeSync`. */ + resourceTypeSync: ResourceTypeSync | undefined = undefined + // Same shape as refreshGlobalSkills. Re-resolved per send rather than once for the // session's life: the operating workspace can change between sends, and a transient // failure resolves fail-open, so the next message re-asks rather than keeping that answer. @@ -3136,7 +3262,8 @@ export class AIChatManager implements ChatViewHost { this.contextManager.getSelectedContext(), { workspace: this.operatingWorkspace, - activePreview: this.activePreviewResolver?.() + activePreview: this.activePreviewResolver?.(), + resourceTypeSync: this.resourceTypeSync } ) } @@ -3666,7 +3793,10 @@ export class AIChatManager implements ChatViewHost { this.refreshGlobalSkills(this.operatingWorkspace ?? ''), this.refreshGlobalFolderInstructions(this.operatingWorkspace ?? ''), this.refreshMcpServers(this.operatingWorkspace ?? ''), - this.refreshSessionAccess(this.operatingWorkspace ?? '') + this.refreshSessionAccess(this.operatingWorkspace ?? ''), + resolveResourceTypeSync(this.operatingWorkspace ?? '', this.messages).then((sync) => { + this.resourceTypeSync = sync + }) ]) } // Stop/Escape during the beforeSend pre-flight aborted this send before any @@ -3956,7 +4086,8 @@ export class AIChatManager implements ChatViewHost { workspace: this.operatingWorkspace, activePreview: this.activePreviewResolver?.(), images: sentImages, - files: files + files: files, + resourceTypeSync: this.resourceTypeSync }) break case AIMode.APP: @@ -4147,6 +4278,7 @@ export class AIChatManager implements ChatViewHost { requestUserQuestion: this.requestUserQuestion, requestRunArgs: this.requestRunArgs, markRunFormStarted: this.markRunFormStarted, + markRunFormEnded: this.markRunFormEnded, onItemModified: (kind, path) => this.recordModifiedItem(kind, path), onItemDeployed: (kind, from, to) => void this.renameModifiedItem(kind, from, to), onItemDiscarded: (kind, path) => void this.removeModifiedItem(kind, path), @@ -4870,19 +5002,18 @@ export class AIChatManager implements ChatViewHost { // AI edits apply directly as drafts, so there is nothing to auto-accept. // Returns a cleanup that tears the registration back down. setPipelineHelpers = (pipelineHelpers: PipelineAIChatHelpers) => { - this.pipelineAiChatHelpers = pipelineHelpers + this.#pipelineEditors.add(pipelineHelpers) + this.#openedPipelineFolders.add(pipelineHelpers.getFolder()) untrack(() => { if (this.mode === AIMode.GLOBAL) { this.configureGlobalMode() } }) // The pipeline tools are now registered — release anything awaiting them. - const waiters = [...this.#pipelineHelpersWaiters] - this.#pipelineHelpersWaiters.clear() - waiters.forEach((resolve) => resolve()) + ;[...this.#pipelineHelpersWaiters].forEach((notify) => notify(pipelineHelpers)) return () => { - this.pipelineAiChatHelpers = undefined + this.#pipelineEditors.delete(pipelineHelpers) untrack(() => { if (this.mode === AIMode.GLOBAL) { this.configureGlobalMode() @@ -4892,15 +5023,16 @@ export class AIChatManager implements ChatViewHost { } /** - * Await the pipeline editor's tool registration. Resolves `true` immediately - * when a pipeline editor is already mounted, or when the next one registers; - * resolves `false` after `timeoutMs` if none registers (e.g. a backgrounded - * session whose preview tab is not mounted, or a closed tab). Callers must - * treat `false` as "tools NOT available" rather than silently reporting - * success — the open_preview handler surfaces that to the model. + * Await the tool registration of the pipeline editor for `folder` (any folder + * when unset). Resolves `true` immediately when one is already mounted, or when + * it registers; resolves `false` after `timeoutMs` if none registers (e.g. a + * session whose runtime is not mounted, or a closed tab). Callers must treat + * `false` as "tools NOT available" rather than silently reporting success — + * the open_preview handler surfaces that to the model. */ - waitForPipelineHelpers = (timeoutMs = 8000): Promise<boolean> => { - if (this.pipelineAiChatHelpers) return Promise.resolve(true) + waitForPipelineHelpers = (folder?: string, timeoutMs = 8000): Promise<boolean> => { + const matches = (p: PipelineAIChatHelpers) => folder === undefined || p.getFolder() === folder + if ([...this.#pipelineEditors].some(matches)) return Promise.resolve(true) return new Promise<boolean>((resolve) => { let settled = false const finish = (registered: boolean) => { @@ -4909,7 +5041,9 @@ export class AIChatManager implements ChatViewHost { this.#pipelineHelpersWaiters.delete(onRegister) resolve(registered) } - const onRegister = () => finish(true) + const onRegister = (p: PipelineAIChatHelpers) => { + if (matches(p)) finish(true) + } this.#pipelineHelpersWaiters.add(onRegister) setTimeout(() => finish(false), timeoutMs) }) diff --git a/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts b/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts index dbb3ac51e3..d8056e778f 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts +++ b/frontend/src/lib/components/copilot/chat/AIChatManager.test.ts @@ -24,7 +24,6 @@ vi.mock('$app/navigation', () => ({ afterNavigate: vi.fn(), beforeNavigate: vi.fn() })) -vi.mock('$app/paths', () => ({ base: '', assets: '' })) const mocks = vi.hoisted(() => ({ getCurrentModel: vi.fn(), @@ -331,6 +330,54 @@ describe('AIChatManager run form', () => { }) }) + // Only a deployed item has a page with a form to confirm on: a test run executes the + // draft being written, and a chat-enabled flow's page is a conversation. Routing either + // there would park the call on a page that can never answer it. + it('hands a deployed run to a page already open, and nothing else', async () => { + const manager = new AIChatManager() + const routed: any[] = [] + manager.openRunOnDeployedPage = (a) => { + routed.push(a) + return true + } + + void manager.requestRunArgs('call_run', { + path: 'f/a/b', + kind: 'run', + runnableKind: 'flow', + summary: 'Plain flow', + schema: {}, + args: {} + }) + void manager.requestRunArgs('call_test', { + path: 'f/a/b', + kind: 'test', + schema: {}, + args: {} + }) + void manager.requestRunArgs('call_chat', { + path: 'f/a/c', + kind: 'run', + conversational: true, + schema: {}, + args: {} + }) + + expect(routed).toEqual([ + { + toolCallId: 'call_run', + kind: 'flow', + path: 'f/a/b', + summary: 'Plain flow', + carries: true, + // Never opens a tab of its own: the reader did not ask for one here. + onlyIfAlreadyOpen: true + } + ]) + // Routed after the form is installed, so the page finds the call the moment it mounts. + expect(manager.isRunFormPending('call_run')).toBe(true) + }) + // Stopping the turn is the form's other way out, and it settles cards through // settledToolDisplay rather than through #settleRunForm. it('settles a stopped form on what it held too', () => { @@ -4329,11 +4376,15 @@ describe('DOM selector chips scoped by app path', () => { describe('AIChatManager.waitForPipelineHelpers', () => { function fakePipelineHelpers(): PipelineAIChatHelpers { return { + getFolder: () => 'f', + hasDrafts: () => false, getPipelineContext: () => ({ folder: 'f', mode: 'edit', nodes: [], assets: [] }), getNodeBody: async () => undefined, proposeNode: async () => ({ path: '', detectedReads: [], detectedWrites: [] }), editNode: async () => ({ detectedReads: [], detectedWrites: [] }), removeProposedNode: async () => {}, + unconfiguredTriggers: async () => [], + setNodeTrigger: async () => ({ path: '', replaced: false }), testNode: async () => undefined } } @@ -4341,13 +4392,13 @@ describe('AIChatManager.waitForPipelineHelpers', () => { it('resolves true immediately when a pipeline editor is already registered', async () => { const manager = new AIChatManager() manager.setPipelineHelpers(fakePipelineHelpers()) - await expect(manager.waitForPipelineHelpers(1000)).resolves.toBe(true) + await expect(manager.waitForPipelineHelpers(undefined, 1000)).resolves.toBe(true) }) it('resolves true once a pipeline editor registers', async () => { const manager = new AIChatManager() let outcome: boolean | undefined - const wait = manager.waitForPipelineHelpers(1000).then((v) => (outcome = v)) + const wait = manager.waitForPipelineHelpers(undefined, 1000).then((v) => (outcome = v)) await Promise.resolve() expect(outcome).toBeUndefined() manager.setPipelineHelpers(fakePipelineHelpers()) @@ -4355,12 +4406,24 @@ describe('AIChatManager.waitForPipelineHelpers', () => { expect(outcome).toBe(true) }) + it('waits for the editor of the requested folder, not any editor', async () => { + const manager = new AIChatManager() + manager.setPipelineHelpers(fakePipelineHelpers()) + let outcome: boolean | undefined + const wait = manager.waitForPipelineHelpers('sales', 1000).then((v) => (outcome = v)) + await Promise.resolve() + expect(outcome).toBeUndefined() + manager.setPipelineHelpers({ ...fakePipelineHelpers(), getFolder: () => 'sales' }) + await wait + expect(outcome).toBe(true) + }) + // The false result is the signal the open_preview handler needs: a backgrounded // session's editor never mounts, so it must report "tools unavailable" rather // than silently claim success. it('resolves false after the timeout when no editor ever registers', async () => { const manager = new AIChatManager() - await expect(manager.waitForPipelineHelpers(10)).resolves.toBe(false) + await expect(manager.waitForPipelineHelpers(undefined, 10)).resolves.toBe(false) }) }) diff --git a/frontend/src/lib/components/copilot/chat/AIChatModelSettings.svelte b/frontend/src/lib/components/copilot/chat/AIChatModelSettings.svelte index 7bf1d99693..d11375b89b 100644 --- a/frontend/src/lib/components/copilot/chat/AIChatModelSettings.svelte +++ b/frontend/src/lib/components/copilot/chat/AIChatModelSettings.svelte @@ -22,7 +22,6 @@ } from '$lib/aiStore' import { WorkspaceService, type AIProvider, type AIProviderModel } from '$lib/gen' import { sendUserToast } from '$lib/toast' - import { base } from '$lib/base' import { getAiChatManager } from './aiChatManagerContext' import { thinkingPreferences } from './thinkingPreferences.svelte' import { @@ -47,7 +46,7 @@ }: { promptSettings?: boolean } = $props() const aiChatManager = getAiChatManager() - const AI_SETTINGS_HREF = `${base}/workspace_settings?tab=ai` + const AI_SETTINGS_HREF = '/workspace_settings?tab=ai' let providerModel = $derived( ($copilotSessionModel ?? diff --git a/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte b/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte index 5d825bd5c8..324082e3e0 100644 --- a/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte +++ b/frontend/src/lib/components/copilot/chat/AssistantInstructionsSection.svelte @@ -20,7 +20,6 @@ writes whichever of the two changed, including the tab that is not on screen. import { userStore, type UserExt } from '$lib/stores' import { getUserExt } from '$lib/user' import { sendUserToast } from '$lib/toast' - import { base } from '$lib/base' import { Building2, ExternalLink, User } from 'lucide-svelte' import { untrack } from 'svelte' import { getAiChatManager } from './aiChatManagerContext' @@ -50,7 +49,7 @@ writes whichever of the two changed, including the tab that is not on screen. const aiChatManager = getAiChatManager() // The section acts on `ws`, which in a session is not the nav workspace, so the link // has to name it or it opens settings the user may not administer. - let aiSettingsHref = $derived(`${base}/workspace_settings?workspace=${ws}&tab=ai`) + let aiSettingsHref = $derived(`/workspace_settings?workspace=${ws}&tab=ai`) let mode = $derived(aiChatManager.mode) let tab = $state<'workspace' | 'user'>('workspace') diff --git a/frontend/src/lib/components/copilot/chat/AssistantMessage.svelte b/frontend/src/lib/components/copilot/chat/AssistantMessage.svelte index b6455980a3..ce931213b5 100644 --- a/frontend/src/lib/components/copilot/chat/AssistantMessage.svelte +++ b/frontend/src/lib/components/copilot/chat/AssistantMessage.svelte @@ -15,7 +15,6 @@ import DisplayResult from '$lib/components/DisplayResult.svelte' import { Bot, ExternalLink } from 'lucide-svelte' import CopyButton from '$lib/components/common/button/CopyButton.svelte' - import { base } from '$lib/base' import { displayDate, truncateRev } from '$lib/utils' interface Props { @@ -35,7 +34,7 @@ // the browser — so the job link is absent rather than empty elsewhere. const jobId = $derived(message.role === 'assistant' ? message.jobId : undefined) const createdAt = $derived(message.role === 'assistant' ? message.createdAt : undefined) - const runHref = $derived(jobId ? `${base}/run/${jobId}?workspace=${workspace}` : undefined) + const runHref = $derived(jobId ? `/run/${jobId}?workspace=${workspace}` : undefined) // Today's answers show the time alone; the day earns its place only on a conversation // read back later. Resolved at render, so a chat left open across midnight keeps // yesterday's format until it is reopened. @@ -99,6 +98,7 @@ }) const candidatePaths = $derived(extractCandidatePaths(message.content)) + const reasoningPlugins = [gfmPlugin(), { renderer: { a: LinkRenderer } }] const rendererPlugin = { renderer: { pre: CodeDisplay, @@ -159,7 +159,7 @@ labelClass="truncate" contentClass="font-main text-secondary {markdownProse.xs}" > - <Markdown md={reasoning} plugins={[gfmPlugin()]} /> + <Markdown md={reasoning} plugins={reasoningPlugins} /> </ChatCollapsibleCard> {/if} diff --git a/frontend/src/lib/components/copilot/chat/AssistantPermissionsSection.svelte b/frontend/src/lib/components/copilot/chat/AssistantPermissionsSection.svelte new file mode 100644 index 0000000000..ee7b4a689c --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/AssistantPermissionsSection.svelte @@ -0,0 +1,86 @@ +<!-- +@component +The Permissions section of the assistant settings modal: what the user's role lets them create +and edit in the chat's workspace, next to what the assistant can make for them from the chat. +The assistant acts with the user's own rights, but its write tools go through drafts, so for +operators the second column is narrower. +--> +<script lang="ts"> + import { Badge, Section } from '$lib/components/common' + import { Check, Minus } from 'lucide-svelte' + import { userWorkspaces } from '$lib/stores' + import { useActingUser } from '$lib/actingUser.svelte' + import { capitalize } from '$lib/utils/capitalize' + import { OPERATOR_SETTINGS_LOCATION, permissionRows, roleName } from './assistantPermissions' + + let { ws }: { ws: string } = $props() + + const acting = useActingUser(() => ws) + + let user = $derived(acting.current) + let operatorSettings = $derived($userWorkspaces.find((w) => w.id === ws)?.operator_settings) + let role = $derived(user ? roleName(user) : undefined) + let rows = $derived(user ? permissionRows(user, operatorSettings) : []) + let chatNarrower = $derived(rows.some((r) => r.user && !r.assistant)) +</script> + +<Section + label="Permissions" + description="What you can create and edit in this workspace, and what the assistant can make for you from this chat." + class="flex flex-col gap-4" +> + {#snippet action()} + {#if role} + <Badge color={role === 'operator' ? 'yellow' : 'gray'}>{capitalize(role)}</Badge> + {/if} + {/snippet} + + {#if !user} + <p class="text-xs text-secondary"> + {acting.resolved(ws) + ? 'Your role in this workspace could not be read.' + : 'Checking your role…'} + </p> + {:else} + <div class="grid max-w-sm grid-cols-[1fr_auto_auto] gap-x-6 gap-y-1.5 text-xs"> + <span class="text-2xs text-secondary">Create and edit</span> + <span class="text-2xs text-secondary text-center">You</span> + <span class="text-2xs text-secondary text-center">From this chat</span> + {#snippet cell(allowed: boolean)} + <span class="flex justify-center"> + {#if allowed} + <Check size={14} class="text-primary" aria-hidden="true" /> + {:else} + <Minus size={14} class="text-hint" aria-hidden="true" /> + {/if} + <span class="sr-only">{allowed ? 'Allowed' : 'Not allowed'}</span> + </span> + {/snippet} + {#each rows as row (row.label)} + <span class="text-primary">{row.label}</span> + {@render cell(row.user)} + {@render cell(row.assistant)} + {/each} + </div> + + <div class="flex flex-col gap-2 text-xs text-secondary"> + {#if chatNarrower} + <p> + The assistant acts as you, with your rights, but it saves every change as a draft before + deploying it, and your role can't save drafts of everything you can edit. Make those on + their own pages instead. + </p> + {/if} + <p>Anyone in the workspace can run the scripts and flows they can see.</p> + <p> + Items in folders you can't read are hidden from you and from the assistant. Someone with + access to the folder can run them. + </p> + {#if role === 'operator'} + <p> + A workspace admin can give operators more rights in {OPERATOR_SETTINGS_LOCATION}. + </p> + {/if} + </div> + {/if} +</Section> diff --git a/frontend/src/lib/components/copilot/chat/AssistantSettingsModal.svelte b/frontend/src/lib/components/copilot/chat/AssistantSettingsModal.svelte index 5c8eda40ad..534e550b89 100644 --- a/frontend/src/lib/components/copilot/chat/AssistantSettingsModal.svelte +++ b/frontend/src/lib/components/copilot/chat/AssistantSettingsModal.svelte @@ -10,7 +10,13 @@ The trigger sits in the composer next to the model pill; `open(section)` is for callers that already know which section they mean, such as the "+" menu's Manage entries. --> <script lang="ts" module> - export type AssistantSettingsSection = 'tools' | 'skills' | 'instructions' | 'mcp' | 'files' + export type AssistantSettingsSection = + | 'tools' + | 'skills' + | 'instructions' + | 'mcp' + | 'files' + | 'permissions' </script> <script lang="ts"> @@ -21,6 +27,7 @@ callers that already know which section they mean, such as the "+" menu's Manage Paperclip, Plug, ScrollText, + ShieldCheck, SlidersHorizontal } from 'lucide-svelte' import Button from '$lib/components/common/button/Button.svelte' @@ -35,6 +42,7 @@ callers that already know which section they mean, such as the "+" menu's Manage import AssistantInstructionsSection from './AssistantInstructionsSection.svelte' import AssistantMcpSection from './AssistantMcpSection.svelte' import AssistantFilesSection from './AssistantFilesSection.svelte' + import AssistantPermissionsSection from './AssistantPermissionsSection.svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' // Prefilled title marks the issue as AI Sessions feedback for triage. @@ -71,7 +79,8 @@ callers that already know which section they mean, such as the "+" menu's Manage skills: skillsBusy, instructions: instructionsBusy, mcp: mcpBusy, - files: filesBusy + files: filesBusy, + permissions: false }) let blockingSection = $derived<AssistantSettingsSection | undefined>( busyBySection[section] @@ -121,7 +130,8 @@ callers that already know which section they mean, such as the "+" menu's Manage { id: 'mcp', label: 'MCP connections', icon: Plug, count: mcpCount }, // The count is what is readable rather than what is attached: a locked folder under // a heading about what the assistant can use would say the opposite of the truth. - { id: 'files', label: 'Files & folders', icon: Paperclip, count: fileCount } + { id: 'files', label: 'Files & folders', icon: Paperclip, count: fileCount }, + { id: 'permissions', label: 'Permissions', icon: ShieldCheck } ]) /** Opens on `target`, or back on whichever section was last read. */ @@ -267,6 +277,11 @@ callers that already know which section they mean, such as the "+" menu's Manage <div class="{section === 'files' ? 'block' : 'hidden'} grow min-h-0 overflow-y-auto pr-2"> <AssistantFilesSection bind:count={fileCount} bind:blocksClose={filesBusy} /> </div> + <div + class="{section === 'permissions' ? 'block' : 'hidden'} grow min-h-0 overflow-y-auto pr-2" + > + <AssistantPermissionsSection {ws} /> + </div> </div> </div> </Modal2> diff --git a/frontend/src/lib/components/copilot/chat/JobsSegment.svelte b/frontend/src/lib/components/copilot/chat/JobsSegment.svelte index b8a59d5bc9..31fce8fd6e 100644 --- a/frontend/src/lib/components/copilot/chat/JobsSegment.svelte +++ b/frontend/src/lib/components/copilot/chat/JobsSegment.svelte @@ -8,7 +8,6 @@ import JobStatusIcon from '$lib/components/runs/JobStatusIcon.svelte' import FlowStatusWaitingForEvents from '$lib/components/FlowStatusWaitingForEvents.svelte' import { ChevronUp, Hourglass, ThumbsUp, TimerOff } from 'lucide-svelte' - import { base } from '$lib/base' import { slide } from 'svelte/transition' import { JobService, type Job } from '$lib/gen' import { msToReadableTime } from '$lib/utils' @@ -211,7 +210,7 @@ } function runHref(job: ChatJob): string { - return `${base}/run/${job.jobId}?workspace=${job.workspace}` + return `/run/${job.jobId}?workspace=${job.workspace}` } function openRun(job: ChatJob) { diff --git a/frontend/src/lib/components/copilot/chat/RunScriptCard.svelte b/frontend/src/lib/components/copilot/chat/RunScriptCard.svelte index ca5e717891..b58ea838bf 100644 --- a/frontend/src/lib/components/copilot/chat/RunScriptCard.svelte +++ b/frontend/src/lib/components/copilot/chat/RunScriptCard.svelte @@ -10,7 +10,6 @@ import { msToReadableTime } from '$lib/utils' import JobArgs from '$lib/components/JobArgs.svelte' import { JobService, type CompletedJob, type Job } from '$lib/gen' - import { base } from '$lib/base' import { getAiChatManager } from './aiChatManagerContext' import ChatCollapsibleCard from './ChatCollapsibleCard.svelte' import RunArgsFormDisplay from './RunArgsFormDisplay.svelte' @@ -102,7 +101,16 @@ canceled || (chatJob !== undefined && ['success', 'failure', 'canceled'].includes(chatJob.status))) ) - const running = $derived(!pending && !settled) + // The form is answered but no job exists yet: the round trip that creates it, or a start + // that is about to fail. Saying Running here would claim a job before there is one. + const starting = $derived(!pending && !settled && !ran) + const running = $derived(!pending && !settled && ran) + // A new job is registered as `queued` with no snapshot, so until the first poll returns one + // its status is a placeholder, not something seen: the row keeps saying Starting. + const unseen = $derived(running && !chatJob?.job) + // The job exists but no worker has taken it. Still `running` for everything that only needs + // a live job (cancel, logs); only the row tells the two apart. As fresh as the last poll. + const waiting = $derived(running && !unseen && chatJob?.status === 'queued') // The job the card is about has not been read yet, or could not be: no pane has anything // to show, but the call's own result still has. const jobPending = $derived(Boolean(inspected) && !inspectedJob) @@ -170,7 +178,17 @@ // Inspecting is done the moment the tool returned, whatever the run it looked at is // still doing — the tense belongs to the call, not to its subject. const verb = $derived( - inspected ? 'Inspected' : running ? verbs.present : settled && ran ? verbs.past : verbs.future + inspected + ? 'Inspected' + : starting || unseen + ? 'Starting' + : waiting + ? '' + : running + ? verbs.present + : settled && ran + ? verbs.past + : verbs.future ) // Being cancelled is an outcome like any other, and it is the one the card has to say out @@ -205,14 +223,31 @@ const autoTab = $derived(hasOutcome ? 'outcome' : ran ? 'logs' : 'input') const activeTab = $derived(steered && tabs.some((t) => t.value === steered) ? steered : autoTab) + // The panel mounts the chat's own form on this call, so the card must not mount a second + // one: two views binding the one draft would each reorder the schema SchemaForm edits in + // place. Only the form is exclusive. A run shows in both, and collapsing the row or + // closing the tab is the user's own way out of seeing it twice. + const formInPreview = $derived( + pending && (aiChatManager.isRunFormTabOpen?.(message.tool_call_id) ?? false) + ) + // A deployed page holding the call builds its own form from a copy of the proposal, so it + // shares no draft and this card keeps a working one. The row folds instead, and expanding + // it is how the reader runs from the transcript without going to the page. + const carriedByPage = $derived( + pending && !formInPreview && (aiChatManager.isRunFormInPreview?.(message.tool_call_id) ?? false) + ) + // Keyed by call id: a bare flag would carry one card's collapse onto the next message // reusing this instance. Open by default, since the run is what was asked for — // except for an inspection, which is usually a step in the reasoning rather than // the answer, and which pays a fetch for being opened. A run cancelled before it started - // is closed too: the row already says Cancelled, and there is no run to show. + // is closed too: the row already says Cancelled, and there is no run to show. So is a call + // whose page is on screen, which is the copy the reader is looking at. let toggled = $state<{ id: string; open: boolean } | undefined>(undefined) const expanded = $derived( - toggled?.id === message.tool_call_id ? toggled.open : !inspected && (ran || !canceled) + toggled?.id === message.tool_call_id + ? toggled.open + : !inspected && (ran || !canceled) && !carriedByPage ) $effect(() => { @@ -267,14 +302,6 @@ } }) - // The panel mounts the chat's own form on this call, so the card must not mount a second - // one: two views binding the one draft would each reorder the schema SchemaForm edits in - // place. Only the form is exclusive. A run shows in both, and collapsing the row or - // closing the tab is the user's own way out of seeing it twice. - const formInPreview = $derived( - pending && (aiChatManager.isRunFormInPreview?.(message.tool_call_id) ?? false) - ) - // The three moments a run moves the card — a tab arrives, the selection follows it, the body // changes under it — are staggered rather than landing in one frame, which is what makes the // card followable. A tab already on screen when the card mounts never arrived, so a settled @@ -331,12 +358,28 @@ // keeps no timers at all. let now = $state(Date.now()) $effect(() => { - if (!running || !chatJob) return + if (!running || unseen || waiting || !chatJob) return + // `now` last moved whenever the card mounted or a previous run stopped ticking, so the + // job's first frame would otherwise read as a negative elapsed time. + now = Date.now() const timer = setInterval(() => (now = Date.now()), 500) return () => clearInterval(timer) }) - const elapsed = $derived(chatJob ? msToReadableTime(now - chatJob.createdAt, 2) : '') + // The clock counts from when a worker took the job, as `duration_ms` does, so the time in the + // queue never shows as run time. The server's own `started_at - created_at` is added to the + // local creation time rather than reading `started_at` against the browser's clock, which + // can be off from the server's by more than the run lasts. + const runStartedAt = $derived.by(() => { + if (!chatJob) return undefined + const j = chatJob.job + const queuedMs = + j?.started_at && j.created_at ? Date.parse(j.started_at) - Date.parse(j.created_at) : NaN + return chatJob.createdAt + (Number.isFinite(queuedMs) ? Math.max(0, queuedMs) : 0) + }) + const elapsed = $derived( + runStartedAt !== undefined ? msToReadableTime(Math.max(0, now - runStartedAt), 2) : '' + ) const duration = $derived( chatJob?.durationMs !== undefined ? msToReadableTime(chatJob.durationMs, 2) : '' ) @@ -370,27 +413,52 @@ // has no time to give, so its outcome takes the slot — as a word, never "Not run", which // stutters against the "Run <name>" label beside it. const outcome = $derived(failed ? 'Failed' : canceled ? 'Cancelled' : 'Done') - const statusTime = $derived(running ? elapsed : duration || outcome) + // No job seen yet, so no time and no outcome: the verb already says Starting. A queued job has + // no run time either, and says why in the slot, in the queued hue, in place of the verb. + const statusTime = $derived( + starting || unseen + ? '' + : waiting + ? 'Waiting for a worker ·' + : running + ? elapsed + : duration || outcome + ) // What the preview button opens changes with the card: the form while the call is still // waiting on one, the run once a job exists. Neither, and there is nothing to open, so // the button is not drawn at all — a form has nowhere to go outside a session, and a // call cancelled before Run never became a run. + // A deployed run can be confirmed on the item's own page instead of on this card: the page + // takes over the call, so Run there is Run here. A test run has no deployed page — it + // executes the draft being written — so it keeps the chat's own form tab. + const asDeployedPage = $derived( + pending && runForm?.kind === 'run' && !!path && !!aiChatManager.openRunOnDeployedPage + ) const previewTarget = $derived( pending - ? aiChatManager.openRunForm - ? ('form' as const) - : undefined + ? asDeployedPage + ? ('deployed' as const) + : aiChatManager.openRunForm + ? ('form' as const) + : undefined : job ? ('run' as const) : undefined ) + // A conversational flow's page has no run form, so opening it is all it can offer: the + // run stays on this card, where there is one to confirm. + const carries = $derived(asDeployedPage && !runForm?.conversational) const previewTitle = $derived( previewTarget === 'form' ? `Open this form in the preview panel: ${path}` - : aiChatManager.openRunInPreview - ? `Open this run in the preview panel: ${path || runnableName}` - : `Open this run in a new tab: ${path || runnableName}` + : previewTarget === 'deployed' + ? carries + ? `Open the deployed ${runnableKind === 'flow' ? 'flow' : 'script'} and confirm this run there: ${path}` + : `Open the deployed ${runnableKind === 'flow' ? 'flow' : 'script'}: ${path}` + : aiChatManager.openRunInPreview + ? `Open this run in the preview panel: ${path || runnableName}` + : `Open this run in a new tab: ${path || runnableName}` ) function openPreview() { @@ -399,12 +467,22 @@ aiChatManager.openRunForm?.({ toolCallId: message.tool_call_id, label }) return } + if (previewTarget === 'deployed') { + aiChatManager.openRunOnDeployedPage?.({ + toolCallId: message.tool_call_id, + kind: runnableKind === 'flow' ? 'flow' : 'script', + path, + summary: label, + carries + }) + return + } if (!job) return // Outside a session there is no panel, so the run opens where the jobs tray sends it. if (aiChatManager.openRunInPreview) { aiChatManager.openRunInPreview({ jobId: job.jobId, workspace: job.workspace, label }) } else { - window.open(`${base}/run/${job.jobId}?workspace=${job.workspace}`, '_blank', 'noreferrer') + window.open(`/run/${job.jobId}?workspace=${job.workspace}`, '_blank', 'noreferrer') } } </script> @@ -416,7 +494,7 @@ {#snippet status()} <!-- An inspection reports nothing here: the card is a snapshot the chat will never update, so a status on it would be frozen at whatever the run happened to be. --> - {#if !pending && !inspected} + {#if !pending && !inspected && statusTime} <span class={twMerge('shrink-0 whitespace-nowrap text-2xs font-medium', statusClass)}> {statusTime} </span> @@ -432,6 +510,7 @@ title={previewTitle} onOpen={openPreview} kindIcon={false} + mode={previewTarget === 'deployed' ? 'view' : 'edit'} /> {/snippet} @@ -591,7 +670,7 @@ : 'No logs.'} </p> {/if} - {#if running && !inspected} + {#if running && !waiting && !inspected} <div class="mt-1 flex items-center gap-1.5 text-2xs text-tertiary"> <Loader2 class="h-3 w-3 animate-spin" /> streaming diff --git a/frontend/src/lib/components/copilot/chat/ToolDiffCard.svelte b/frontend/src/lib/components/copilot/chat/ToolDiffCard.svelte index 94e33374c3..eb0fc1194b 100644 --- a/frontend/src/lib/components/copilot/chat/ToolDiffCard.svelte +++ b/frontend/src/lib/components/copilot/chat/ToolDiffCard.svelte @@ -3,6 +3,8 @@ import ChatCollapsibleCard from './ChatCollapsibleCard.svelte' import ToolCodeDiffView from './ToolCodeDiffView.svelte' import ToolPreviewCard from './ToolPreviewCard.svelte' + import ToolConfirmationFooter from './ToolConfirmationFooter.svelte' + import { Check, XCircle } from 'lucide-svelte' import { diffIsWholeFile, diffLineCounts, @@ -21,8 +23,9 @@ const diff = $derived(toolCodeDiff(message)) const isStreaming = $derived(Boolean(message.isStreamingArguments)) const hasDiff = $derived(Boolean(diff && (diff.before !== '' || diff.after !== ''))) + const awaitingConfirmation = $derived(Boolean(message.isLoading && message.needsConfirmation)) // The card body is a bordered box: opened with nothing in it, it draws an empty line. - const hasBody = $derived(hasDiff || Boolean(message.error)) + const hasBody = $derived(hasDiff || Boolean(message.error) || awaitingConfirmation) // Keyed by call id: a bare flag would carry the expansion onto the next message that // reuses this instance. An active or failed call opens by itself, and remains open @@ -45,7 +48,11 @@ toggled = { id: toggleKey, open: true } } }) - const expanded = $derived(hasBody && (toggled?.id === toggleKey ? toggled.open : opensByDefault)) + // The Apply/Reject footer is inside the body, so a pending confirmation keeps it open. + const expanded = $derived( + awaitingConfirmation || + (hasBody && (toggled?.id === toggleKey ? toggled.open : opensByDefault)) + ) const lines = $derived(diff && expanded ? toolDiffLines(diff, isStreaming) : undefined) const counts = $derived( diff && expanded @@ -79,7 +86,7 @@ label={message.content} {expanded} onToggle={() => (toggled = { id: toggleKey, open: !expanded })} - toggleable={hasBody} + toggleable={hasBody && !awaitingConfirmation} shimmer={isRunning} class={message.isQueued && !message.error ? 'opacity-60 hover:opacity-100 transition-opacity' @@ -91,6 +98,16 @@ {#if diff && hasDiff && expanded} <ToolCodeDiffView {diff} diffLines={lines} streaming={isStreaming} /> {/if} + {#if awaitingConfirmation} + <ToolConfirmationFooter + class="px-3 py-2 border-t border-border-light" + toolCallId={message.tool_call_id} + rejectIcon={XCircle} + rejectDestructive + confirmLabel="Apply" + confirmIcon={Check} + /> + {/if} {#if message.error} <div class="px-3 py-2 text-2xs text-red-600 dark:text-red-400 whitespace-pre-wrap break-words {hasDiff diff --git a/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte b/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte index 38f91353a2..832a96d6b4 100644 --- a/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte +++ b/frontend/src/lib/components/copilot/chat/ToolExecutionDisplay.svelte @@ -13,7 +13,6 @@ ExternalLink, BookOpen } from 'lucide-svelte' - import { base } from '$lib/base' import { truncateRev } from '$lib/utils' import { EXIT_PLAN_MODE_TOOL, @@ -301,7 +300,7 @@ {#snippet jobLink()} <a - href="{base}/run/{message.jobId}?workspace={chatHost.operatingWorkspace}" + href="/run/{message.jobId}?workspace={chatHost.operatingWorkspace}" target="_blank" rel="noopener noreferrer" class="shrink-0 inline-flex items-center gap-1 font-main text-2xs text-tertiary hover:text-primary hover:underline" diff --git a/frontend/src/lib/components/copilot/chat/anthropic.ts b/frontend/src/lib/components/copilot/chat/anthropic.ts index ab69d0b1a3..ce11b0dade 100644 --- a/frontend/src/lib/components/copilot/chat/anthropic.ts +++ b/frontend/src/lib/components/copilot/chat/anthropic.ts @@ -19,6 +19,7 @@ import { applyReasoningToConfig } from '../reasoningRegistry' import { appendPendingToolImages, processToolCall, + type LiveToolSet, queuedToolStatus, type Tool, type ToolCallbacks, @@ -197,7 +198,11 @@ export async function parseAnthropicCompletion( tools: Tool<any>[], helpers: any, abortController?: AbortController, - options?: { workspace?: string; onTokenUsage?: (usage: ChatTokenUsage) => void } + options?: { + workspace?: string + onTokenUsage?: (usage: ChatTokenUsage) => void + live?: LiveToolSet + } ): Promise<ParsedCompletionResult> { let toolCallsToProcess: ChatCompletionMessageFunctionToolCall[] = [] let error = null @@ -447,7 +452,8 @@ export async function parseAnthropicCompletion( helpers, toolCallbacks: callbacks, workspace: options?.workspace, - messages + messages, + live: options?.live }) messages.push(messageToAdd) addedMessages.push(messageToAdd) diff --git a/frontend/src/lib/components/copilot/chat/app/core.ts b/frontend/src/lib/components/copilot/chat/app/core.ts index b013c58ebc..166df65a16 100644 --- a/frontend/src/lib/components/copilot/chat/app/core.ts +++ b/frontend/src/lib/components/copilot/chat/app/core.ts @@ -37,6 +37,8 @@ export interface BackendRunnable { inlineScript?: InlineScript // For workspace scripts/flows and hub scripts path?: string + // Inline only: data table connections naming no role hold the viewer's roles + viewerDataAccess?: boolean } export interface AppFiles { @@ -327,6 +329,12 @@ const getSetBackendRunnableSchema = memo(() => .optional() .describe( 'Required when type is "script", "flow", or "hubscript". The fully qualified path to the workspace script/flow or hub script.' + ), + viewerDataAccess: z + .boolean() + .optional() + .describe( + "Inline only. When true, the runnable reads data as the person viewing the app instead of as the app's identity: data table connections that name no role hold the viewer's roles, and object storage permission rules are checked against the viewer, so row-level security and per-user storage paths answer per viewer. Resources and variables stay the app's. Anonymous viewers are refused. Omit to keep the current setting." ) }) ) @@ -710,7 +718,8 @@ export const getAppTools = memo((): Tool<AppAIChatHelpers>[] => [ ...args, staticInputs: args.staticInputs === null ? undefined : args.staticInputs, inlineScript: args.inlineScript === null ? undefined : args.inlineScript, - path: args.path === null ? undefined : args.path + path: args.path === null ? undefined : args.path, + viewerDataAccess: args.viewerDataAccess === null ? undefined : args.viewerDataAccess } const parsedArgs = getSetBackendRunnableSchema().parse(cleanedArgs) @@ -723,7 +732,10 @@ export const getAppTools = memo((): Tool<AppAIChatHelpers>[] => [ type: parsedArgs.type, ...(parsedArgs.staticInputs && { staticInputs: parsedArgs.staticInputs }), ...(parsedArgs.inlineScript && { inlineScript: parsedArgs.inlineScript }), - ...(parsedArgs.path && { path: parsedArgs.path }) + ...(parsedArgs.path && { path: parsedArgs.path }), + ...(parsedArgs.viewerDataAccess !== undefined && { + viewerDataAccess: parsedArgs.viewerDataAccess + }) } toolCallbacks.setToolStatus(toolId, { diff --git a/frontend/src/lib/components/copilot/chat/artifacts/artifactSharing.test.ts b/frontend/src/lib/components/copilot/chat/artifacts/artifactSharing.test.ts index 115343117a..da3ac686b3 100644 --- a/frontend/src/lib/components/copilot/chat/artifacts/artifactSharing.test.ts +++ b/frontend/src/lib/components/copilot/chat/artifacts/artifactSharing.test.ts @@ -1,7 +1,5 @@ import { describe, expect, it, vi } from 'vitest' -vi.mock('$lib/base', () => ({ base: '' })) - import { shareWorkspaceId } from './artifactSharing' describe('shareWorkspaceId', () => { diff --git a/frontend/src/lib/components/copilot/chat/artifacts/artifactSharing.ts b/frontend/src/lib/components/copilot/chat/artifacts/artifactSharing.ts index 57b08cba9b..269eb6354b 100644 --- a/frontend/src/lib/components/copilot/chat/artifacts/artifactSharing.ts +++ b/frontend/src/lib/components/copilot/chat/artifacts/artifactSharing.ts @@ -1,5 +1,3 @@ -import { base } from '$lib/base' - /** * The workspace a share from `workspaceId` lands in: the topmost ancestor the user still * belongs to. A session often runs in a fork, whose members are its creator alone, so a link @@ -20,7 +18,7 @@ export function shareWorkspaceId( } export function sharedArtifactUrl(workspaceId: string, shareId: string): string { - return `${window.location.origin}${base}/shared_artifacts/${encodeURIComponent( + return `${window.location.origin}/shared_artifacts/${encodeURIComponent( shareId )}?workspace=${encodeURIComponent(workspaceId)}` } diff --git a/frontend/src/lib/components/copilot/chat/assistantPermissions.ts b/frontend/src/lib/components/copilot/chat/assistantPermissions.ts new file mode 100644 index 0000000000..d00ac65b8e --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/assistantPermissions.ts @@ -0,0 +1,59 @@ +import type { OperatorSettings } from '$lib/gen' +import type { UserExt } from '$lib/stores' +import { roleCanAuthor, type EditKind } from '$lib/editRights' +import { capabilitiesForRole } from './global/sessionAccess' +import type { SessionAccess } from './sessionCapabilities' + +/** Where a workspace admin changes what operators may do. Named in the prompt and the + * permissions section alike, so the two send the user to the same place. */ +export const OPERATOR_SETTINGS_LOCATION = 'Workspace settings → Users → Operator settings' + +type PermissionRow = { + kind: EditKind + label: string + /** The draft capability the kind's write tool declares in `requires`. */ + assistant: (access: SessionAccess) => boolean +} + +const ROWS: PermissionRow[] = [ + { kind: 'script', label: 'Scripts', assistant: (a) => a.has('write_draft') }, + { kind: 'flow', label: 'Flows', assistant: (a) => a.has('write_flow_draft') }, + { kind: 'raw_app', label: 'Apps', assistant: (a) => a.has('write_app_draft') }, + { kind: 'schedule', label: 'Schedules', assistant: (a) => a.has('write_schedule_draft') }, + { kind: 'trigger', label: 'Triggers', assistant: (a) => a.has('write_trigger_draft') }, + { kind: 'resource', label: 'Resources', assistant: (a) => a.has('write_resource_draft') }, + { kind: 'variable', label: 'Variables', assistant: (a) => a.has('write_variable_draft') } +] + +export type RoleName = 'admin' | 'developer' | 'operator' + +export function roleName( + user: Pick<UserExt, 'operator' | 'is_admin' | 'is_super_admin'> +): RoleName { + if (user.is_admin || user.is_super_admin) return 'admin' + return user.operator ? 'operator' : 'developer' +} + +/** + * Per item kind, whether the user's role lets them create and edit it themselves, and whether + * the chat can for them. Both act with the user's rights, but the user's column follows the + * item handlers (`roleCanAuthor`) and the chat's the draft endpoint every write tool goes + * through (`capabilitiesForRole`), which refuses operators more than the handlers do. + */ +export function permissionRows( + user: Pick<UserExt, 'operator' | 'is_admin' | 'is_super_admin'>, + operatorSettings: OperatorSettings | null | undefined +): { label: string; user: boolean; assistant: boolean }[] { + const access = capabilitiesForRole({ + isAdmin: !!user.is_admin || !!user.is_super_admin, + operator: !!user.operator, + // Deploy rules gate deploying, not the drafts these rows are about. + deployRulesPass: true, + operatorSettings + }) + return ROWS.map((row) => ({ + label: row.label, + user: roleCanAuthor(row.kind, user, operatorSettings), + assistant: row.assistant(access) + })) +} diff --git a/frontend/src/lib/components/copilot/chat/chatLoop.test.ts b/frontend/src/lib/components/copilot/chat/chatLoop.test.ts index 282e7e1aa6..af4b648b61 100644 --- a/frontend/src/lib/components/copilot/chat/chatLoop.test.ts +++ b/frontend/src/lib/components/copilot/chat/chatLoop.test.ts @@ -29,7 +29,9 @@ vi.mock('../lib', () => ({ providerSupportsWebSearch: mocks.providerSupportsWebSearch })) -vi.mock('../reasoningRegistry', () => ({ +vi.mock('../reasoningRegistry', async (importOriginal) => ({ + usesOpenAIResponsesApi: (await importOriginal<typeof import('../reasoningRegistry')>()) + .usesOpenAIResponsesApi, resolveRequestReasoning: mocks.resolveRequestReasoning, resolveEffectiveReasoning: mocks.resolveEffectiveReasoning })) diff --git a/frontend/src/lib/components/copilot/chat/chatLoop.ts b/frontend/src/lib/components/copilot/chat/chatLoop.ts index cde9d554cd..343dd268e7 100644 --- a/frontend/src/lib/components/copilot/chat/chatLoop.ts +++ b/frontend/src/lib/components/copilot/chat/chatLoop.ts @@ -10,6 +10,7 @@ import { getCompletion, parseOpenAICompletion, providerSupportsWebSearch } from import { resolveEffectiveReasoning, resolveRequestReasoning, + usesOpenAIResponsesApi, type ReasoningProviderModel } from '../reasoningRegistry' import { getAnthropicCompletion, parseAnthropicCompletion } from './anthropic' @@ -427,8 +428,7 @@ export async function runChatLoop(config: ChatLoopConfig): Promise<ChatLoopResul const pendingUserMessage = getPendingUserMessage?.() - const isOpenAI = - modelProvider.provider === 'openai' || modelProvider.provider === 'azure_openai' + const isOpenAI = usesOpenAIResponsesApi(modelProvider.provider, modelProvider.model) const isAnthropic = usesAnthropicMessagesApi(modelProvider.provider, modelProvider.model) // Resolve effort once in chat context (applies the default-on level for // capable models, and the provider-native disable token for an explicit @@ -453,7 +453,8 @@ export async function runChatLoop(config: ChatLoopConfig): Promise<ChatLoopResul const parseOptions = { workspace, provider: modelProvider.provider, - onTokenUsage: reportUsage + onTokenUsage: reportUsage, + live: () => ({ tools: config.tools, helpers: config.helpers }) } if (isOpenAI) { diff --git a/frontend/src/lib/components/copilot/chat/chatViewHost.ts b/frontend/src/lib/components/copilot/chat/chatViewHost.ts index bdacb57615..197b831e7e 100644 --- a/frontend/src/lib/components/copilot/chat/chatViewHost.ts +++ b/frontend/src/lib/components/copilot/chat/chatViewHost.ts @@ -114,6 +114,9 @@ export interface ChatViewHost { // of their own; the chrome they drive hides itself. mode?: AIMode isSessionChat: boolean + /** Someone else's transcript, replayed for a reader who did not write it: markup that + * would execute or render beyond plain text (mermaid diagrams) stays off. */ + untrustedTranscript?: boolean /** Model + reasoning picker. Off where the model is configured elsewhere. */ supportsModelSettings: boolean /** Click a user message to edit and resend it. Needs a host that can rewind diff --git a/frontend/src/lib/components/copilot/chat/datatableMigrationTools.test.ts b/frontend/src/lib/components/copilot/chat/datatableMigrationTools.test.ts new file mode 100644 index 0000000000..086adce9e9 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/datatableMigrationTools.test.ts @@ -0,0 +1,141 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { statusMock, createMock, upsertMock, runMock } = vi.hoisted(() => ({ + upsertMock: vi.fn(), + statusMock: vi.fn(), + createMock: vi.fn(), + runMock: vi.fn() +})) + +vi.mock('./shared', () => ({ + createToolDef: (_schema: unknown, name: string, description: string) => ({ + type: 'function', + function: { name, description, parameters: {} } + }) +})) + +vi.mock('$lib/gen', () => ({ + WorkspaceService: { + getDatatableMigrationsStatus: statusMock, + createDatatableMigration: createMock, + upsertDatatableMigration: upsertMock, + runDatatableMigrations: runMock + } +})) + +import { getDatatableMigrationTools } from './datatableMigrationTools' + +function create(args: Record<string, unknown>) { + const tool = getDatatableMigrationTools().find( + (entry) => entry.def.function.name === 'create_datatable_migration' + )! + return tool.fn({ + args: { + datatable_name: 'main', + name: 'add_refunds', + code_up: 'BEGIN;\nCREATE TABLE refunds ();\nEND;', + ...args + }, + workspace: 'test-workspace', + helpers: {}, + toolCallbacks: { setToolStatus: vi.fn(), removeToolStatus: vi.fn() } as any, + toolId: 'tool-1' + }) +} + +const applied = { timestamp: 10, name: 'init', code_up: '', status: 'ran' } +const created = { timestamp: 30, name: 'add_refunds', code_up: '', status: 'not_run' } + +beforeEach(() => { + for (const mock of [statusMock, createMock, upsertMock, runMock]) mock.mockReset() + createMock.mockResolvedValue({ timestamp: 30 }) + statusMock.mockResolvedValue({ enabled: true, migrations: [applied, created] }) + runMock.mockResolvedValue({ applied: [{ version: 30, name: 'add_refunds' }] }) +}) + +describe('create_datatable_migration', () => { + it('applies only the migration it created', async () => { + const result = await create({}) + expect(runMock).toHaveBeenCalledWith({ + workspace: 'test-workspace', + datatableName: 'main', + only: 30 + }) + expect(result).toContain('Applied migration 30 (add_refunds)') + }) + + it('leaves it pending when an earlier migration is not applied', async () => { + statusMock.mockResolvedValue({ + enabled: true, + migrations: [ + applied, + { timestamp: 20, name: 'earlier', code_up: '', status: 'not_run' }, + created + ] + }) + const result = await create({}) + expect(runMock).not.toHaveBeenCalled() + expect(result).toContain('20 (earlier)') + }) + + it('keeps a migration that fails to apply and rewrites it on request', async () => { + runMock.mockRejectedValueOnce({ body: 'relation "refunds" already exists' }) + const failed = await create({}) + expect(failed).toContain('relation "refunds" already exists') + expect(failed).toContain('with version 30') + + statusMock.mockResolvedValue({ + enabled: true, + migrations: [applied, { ...created, code_down: 'DROP TABLE refunds;' }] + }) + await create({ version: 30, code_up: 'BEGIN;\nCREATE TABLE refunds2 ();\nEND;' }) + expect(createMock).toHaveBeenCalledTimes(1) + expect(upsertMock).toHaveBeenCalledWith({ + workspace: 'test-workspace', + datatableName: 'main', + requestBody: { + timestamp: 30, + code_down: 'DROP TABLE refunds;', + name: 'add_refunds', + code_up: 'BEGIN;\nCREATE TABLE refunds2 ();\nEND;' + } + }) + expect(runMock).toHaveBeenLastCalledWith({ + workspace: 'test-workspace', + datatableName: 'main', + only: 30 + }) + }) + + it('refuses to rewrite a version that is not pending', async () => { + const result = await create({ version: 10 }) + expect(upsertMock).not.toHaveBeenCalled() + expect(runMock).not.toHaveBeenCalled() + expect(result).toContain('cannot be rewritten') + }) + + it('does not call unreadable earlier migrations pending', async () => { + statusMock.mockResolvedValue({ + enabled: true, + migrations: [ + { ...applied, status: 'unknown' }, + { ...created, status: 'unknown' } + ], + error: 'connection refused' + }) + const result = await create({}) + expect(runMock).not.toHaveBeenCalled() + expect(result).toContain('connection refused') + expect(result).not.toContain('10 (init)') + }) + + it('declares the role above the SQL of both directions', async () => { + await create({ role: 'app_rw', code_down: 'DROP TABLE refunds;', apply: false }) + expect(createMock.mock.calls[0][0].requestBody).toEqual({ + name: 'add_refunds', + code_up: '-- role app_rw\nBEGIN;\nCREATE TABLE refunds ();\nEND;', + code_down: '-- role app_rw\nDROP TABLE refunds;' + }) + expect(runMock).not.toHaveBeenCalled() + }) +}) diff --git a/frontend/src/lib/components/copilot/chat/datatableMigrationTools.ts b/frontend/src/lib/components/copilot/chat/datatableMigrationTools.ts new file mode 100644 index 0000000000..c093b450c3 --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/datatableMigrationTools.ts @@ -0,0 +1,414 @@ +import { z } from 'zod' +import { WorkspaceService } from '$lib/gen' +import { withMigrationRole } from '$lib/components/datatableMigrationRole' +import { + migrationScope, + parseMigrationSchemas, + scopesOverlap, + withMigrationSchemas +} from '$lib/components/datatableMigrationSchemas' +import { createToolDef, type ToolCallbacks } from './shared' +import { NONE, RUN_PREVIEW, type SessionTool } from './sessionCapabilities' + +/** + * Tools over a data table's versioned SQL migrations (`datatable_migrations.rs`). + * + * A data table with migrations enabled keeps its schema as an ordered list of definitions, each + * applied once per database and recorded there. That list is what git sync and a workspace merge + * carry, so a schema change made with plain SQL exists in one database only. + */ + +const memo = <T>(factory: () => T): (() => T) => { + let cached: T | undefined + return () => (cached ??= factory()) +} + +function apiErrorMessage(e: unknown): string { + const err = e as { body?: unknown; message?: unknown } | undefined + const body = err?.body + if (typeof body === 'string' && body !== '') return body + if (typeof err?.message === 'string') return err.message + return String(e) +} + +function fail(toolCallbacks: ToolCallbacks, toolId: string, message: string): string { + toolCallbacks.setToolStatus(toolId, { content: message, error: message }) + return message +} + +const migrationLabel = (m: { version: number; name: string }) => `${m.version} (${m.name})` + +const datatableNameSchema = () => + z.string().describe('The datatable the migrations belong to, e.g. "main".') + +// ============= Tool definitions ============= + +const getListMigrationsSchema = memo(() => + z.object({ + datatable_name: datatableNameSchema(), + version: z + .number() + .optional() + .describe('Return the SQL of this one migration instead of the list.') + }) +) +const getListMigrationsToolDef = memo(() => + createToolDef( + getListMigrationsSchema(), + 'list_datatable_migrations', + "List a datatable's migrations in order, each with its version, name and whether it is applied or pending. Pass `version` to read one migration's SQL." + ) +) + +const getCreateMigrationSchema = memo(() => + z.object({ + datatable_name: datatableNameSchema(), + name: z + .string() + .regex(/^[A-Za-z0-9_-]+$/) + .describe( + 'Short name of the change, e.g. "add_refunds_table". Letters, digits, "_" and "-" only.' + ), + code_up: z + .string() + .describe( + 'The SQL that makes the change. Wrap the statements in `BEGIN; ... END;` so they apply atomically, unless one of them cannot run in a transaction.' + ), + code_down: z + .string() + .optional() + .describe( + 'The SQL that undoes `code_up`. Without it the migration cannot be rolled back, so provide it whenever the change is reversible.' + ), + role: z + .string() + .regex(/^[A-Za-z0-9_-]{1,63}$/) + .optional() + .describe( + 'The datatable role the migration runs as, on a datatable that has roles. Omit to run as admin, which only the datatable admins may do.' + ), + schemas: z + .array(z.string().regex(/^[A-Za-z0-9_$-]{1,63}$/)) + .optional() + .describe( + 'Every schema the migration changes or depends on (including schemas of referenced tables, types and functions), with every name in `code_up` schema-qualified. A migration then waits only on earlier migrations touching those schemas. Omit only for a change that spans the whole database (an extension, a grant across schemas): every later migration then waits for it.' + ), + version: z + .number() + .optional() + .describe( + 'Rewrite this migration instead of adding one: only for a pending migration, typically the one that just failed to apply.' + ), + apply: z + .boolean() + .optional() + .describe('Set false to save the migration as pending without running it. Defaults to true.') + }) +) +const getCreateMigrationToolDef = memo(() => + createToolDef( + getCreateMigrationSchema(), + 'create_datatable_migration', + 'Change the schema of a datatable that has migrations enabled: saves the change as a new migration and applies it. One that fails to apply stays saved as pending: call this again with its `version` to fix it.' + ) +) + +const getRunMigrationsSchema = memo(() => z.object({ datatable_name: datatableNameSchema() })) +const getRunMigrationsToolDef = memo(() => + createToolDef( + getRunMigrationsSchema(), + 'run_datatable_migrations', + "Apply a datatable's pending migrations, oldest first. It stops at the first one that fails." + ) +) + +const getRollbackMigrationSchema = memo(() => + z.object({ + datatable_name: datatableNameSchema(), + version: z + .number() + .describe('The applied migration to undo, normally the most recent one, as listed.') + }) +) +const getRollbackMigrationToolDef = memo(() => + createToolDef( + getRollbackMigrationSchema(), + 'rollback_datatable_migration', + 'Undo one applied migration of a datatable by running its down SQL. The migration stays in the list as pending.' + ) +) + +// ============= Tools ============= + +export function getDatatableMigrationTools(): SessionTool<{}>[] { + return [ + { + requires: NONE, + def: getListMigrationsToolDef(), + planModeSafe: true, + fn: async ({ args, workspace, toolId, toolCallbacks }) => { + const { datatable_name, version } = getListMigrationsSchema().parse(args) + toolCallbacks.setToolStatus(toolId, { + content: `Listing migrations of "${datatable_name}"...` + }) + try { + const status = await WorkspaceService.getDatatableMigrationsStatus({ + workspace, + datatableName: datatable_name + }) + if (!status.enabled) { + toolCallbacks.setToolStatus(toolId, { + content: `Migrations are not enabled on "${datatable_name}"` + }) + return `Migrations are not enabled on datatable "${datatable_name}": its schema is changed with plain SQL and there is no history to list. Enabling them is a workspace admin's decision, made in Workspace settings → Data Tables.` + } + if (version !== undefined) { + const migration = status.migrations.find((m) => m.timestamp === version) + if (!migration) { + return fail( + toolCallbacks, + toolId, + `No migration ${version} on datatable "${datatable_name}"` + ) + } + toolCallbacks.setToolStatus(toolId, { + content: `Read migration ${migrationLabel({ version, name: migration.name })}` + }) + return JSON.stringify( + { + version, + name: migration.name, + status: migrationStatus(migration.status), + code_up: migration.code_up, + ...(migration.code_down != null && { code_down: migration.code_down }) + }, + null, + 2 + ) + } + toolCallbacks.setToolStatus(toolId, { + content: `Listed ${status.migrations.length} migration(s) of "${datatable_name}"` + }) + return JSON.stringify( + { + migrations: status.migrations.map((m) => ({ + version: m.timestamp, + name: m.name, + status: migrationStatus(m.status), + schemas: m.schemas ?? 'whole database' + })), + // Set when the database could not be read, which is why every status is unknown. + ...(status.error && { error: status.error }) + }, + null, + 2 + ) + } catch (e) { + return fail(toolCallbacks, toolId, `Error listing migrations: ${apiErrorMessage(e)}`) + } + } + }, + { + // `ensure_not_operator` in datatable_migrations.rs: the condition `run_preview` stands for. + requires: RUN_PREVIEW, + def: getCreateMigrationToolDef(), + requiresConfirmation: true, + confirmationMessage: (args) => + `${args?.version === undefined ? 'Create' : 'Rewrite'}${args?.apply === false ? '' : ' and apply'} data table migration`, + queuedLabel: (args) => `Write migration "${args?.name ?? ''}"`, + showDetails: true, + fn: async ({ args, workspace, toolId, toolCallbacks }) => { + const parsed = getCreateMigrationSchema().parse(args) + const datatableName = parsed.datatable_name + toolCallbacks.setToolStatus(toolId, { + content: `Saving migration "${parsed.name}" on "${datatableName}"...` + }) + // The role is an annotation in the SQL, read from above everything else, and a rollback + // has to run as the role that created what it drops. + // No inference here: the model reads the SQL it wrote better than a pattern does, so + // the scope is what it declares, and the whole database when it declares none. + const declared = parseMigrationSchemas(parsed.code_up) + const scope = parsed.schemas ?? (declared.kind === 'schemas' ? declared.schemas : []) + const definition = { + name: parsed.name, + code_up: withMigrationSchemas( + withRole(parsed.code_up, parsed.role), + scope.map((s) => s.toLowerCase()) + ), + ...(parsed.code_down !== undefined && { + code_down: withRole(parsed.code_down, parsed.role) + }) + } + let version: number + try { + if (parsed.version === undefined) { + const created = await WorkspaceService.createDatatableMigration({ + workspace, + datatableName, + requestBody: definition + }) + version = created.timestamp + } else { + version = parsed.version + // The server inserts at a version it does not know, which would wedge a new + // migration into the middle of the history, and stores a down left out as none. + const { migrations } = await WorkspaceService.getDatatableMigrationsStatus({ + workspace, + datatableName + }) + const existing = migrations.find((m) => m.timestamp === version) + if (existing?.status !== 'not_run') { + return fail( + toolCallbacks, + toolId, + `Migration ${version} is not a pending migration of datatable "${datatableName}", so it cannot be rewritten. Omit \`version\` to add a new migration.` + ) + } + await WorkspaceService.upsertDatatableMigration({ + workspace, + datatableName, + requestBody: { + timestamp: version, + ...(existing.code_down != null && { code_down: existing.code_down }), + ...definition + } + }) + } + } catch (e) { + return fail(toolCallbacks, toolId, `Error saving migration: ${apiErrorMessage(e)}`) + } + const label = migrationLabel({ version, name: parsed.name }) + if (parsed.apply === false) { + toolCallbacks.setToolStatus(toolId, { content: `Saved migration ${label} as pending` }) + return `Saved migration ${label} as pending. It is not applied yet.` + } + + // Applying it alone would run it ahead of migrations it may depend on, and applying + // those with it would run SQL the user was never shown. + let earlierPending: string[] + try { + const status = await WorkspaceService.getDatatableMigrationsStatus({ + workspace, + datatableName + }) + const ownScope = migrationScope(definition.code_up) + const earlier = status.migrations.filter( + (m) => m.timestamp < version && scopesOverlap(m.schemas, ownScope) + ) + // Unreadable is not pending: reporting it so would send the user to apply + // migrations that already ran. + if (status.error || earlier.some((m) => m.status === 'unknown')) { + throw new Error(status.error ?? 'the applied migrations could not be read') + } + earlierPending = earlier + .filter((m) => m.status === 'not_run') + .map((m) => migrationLabel({ version: m.timestamp, name: m.name })) + } catch (e) { + return fail( + toolCallbacks, + toolId, + `Saved migration ${label} as pending, but could not check what else is pending, so it was not applied: ${apiErrorMessage(e)}` + ) + } + if (earlierPending.length > 0) { + toolCallbacks.setToolStatus(toolId, { + content: `Saved migration ${label}; ${earlierPending.length} earlier migration(s) still pending` + }) + return `Saved migration ${label} as pending without applying it: earlier migrations are not applied yet (${earlierPending.join(', ')}) and it may depend on them. Tell the user, then apply them all in order with run_datatable_migrations.` + } + + toolCallbacks.setToolStatus(toolId, { content: `Applying migration ${label}...` }) + try { + await WorkspaceService.runDatatableMigrations({ + workspace, + datatableName, + only: version + }) + } catch (e) { + // Kept whatever failed: part of it may be applied, or all of it with only the record + // missing, and the definition with its down is then the one trace of that. + return fail( + toolCallbacks, + toolId, + `Migration ${label} is saved but failed to apply: ${apiErrorMessage(e)}. It stays pending and blocks later migrations. If nothing of it was applied, fix it by calling this tool again with version ${version}; otherwise, or to drop it, tell the user, who can edit or delete it in Workspace settings → Data Tables.` + ) + } + toolCallbacks.setToolStatus(toolId, { content: `Applied migration ${label}` }) + return `Applied migration ${label} on datatable "${datatableName}".` + } + }, + { + requires: RUN_PREVIEW, + def: getRunMigrationsToolDef(), + requiresConfirmation: true, + confirmationMessage: 'Apply pending data table migrations', + queuedLabel: (args) => `Apply migrations on "${args?.datatable_name ?? 'datatable'}"`, + showDetails: true, + fn: async ({ args, workspace, toolId, toolCallbacks }) => { + const { datatable_name } = getRunMigrationsSchema().parse(args) + toolCallbacks.setToolStatus(toolId, { + content: `Applying migrations on "${datatable_name}"...` + }) + try { + const { applied } = await WorkspaceService.runDatatableMigrations({ + workspace, + datatableName: datatable_name + }) + if (applied.length === 0) { + toolCallbacks.setToolStatus(toolId, { content: 'No pending migration to apply' }) + return `No pending migration to apply on datatable "${datatable_name}".` + } + toolCallbacks.setToolStatus(toolId, { + content: `Applied ${applied.length} migration(s) on "${datatable_name}"` + }) + return `Applied ${applied.length} migration(s) on datatable "${datatable_name}": ${applied.map(migrationLabel).join(', ')}.` + } catch (e) { + // Those before the failing one are applied: the list is what says where it stopped. + return fail( + toolCallbacks, + toolId, + `Error applying migrations: ${apiErrorMessage(e)}. Migrations before the failing one may have been applied: list them to see.` + ) + } + } + }, + { + requires: RUN_PREVIEW, + def: getRollbackMigrationToolDef(), + requiresConfirmation: true, + confirmationMessage: (args) => `Roll back data table migration ${args?.version ?? ''}`, + queuedLabel: (args) => `Roll back migration ${args?.version ?? ''}`, + showDetails: true, + fn: async ({ args, workspace, toolId, toolCallbacks }) => { + const { datatable_name, version } = getRollbackMigrationSchema().parse(args) + toolCallbacks.setToolStatus(toolId, { + content: `Rolling back migration ${version} on "${datatable_name}"...` + }) + try { + const { rolled_back } = await WorkspaceService.rollbackDatatableMigrations({ + workspace, + datatableName: datatable_name, + only: version + }) + if (rolled_back.length === 0) { + toolCallbacks.setToolStatus(toolId, { content: `Migration ${version} is not applied` }) + return `Migration ${version} is not applied on datatable "${datatable_name}", so there is nothing to roll back.` + } + const label = rolled_back.map(migrationLabel).join(', ') + toolCallbacks.setToolStatus(toolId, { content: `Rolled back migration ${label}` }) + return `Rolled back migration ${label} on datatable "${datatable_name}". It is pending again.` + } catch (e) { + return fail(toolCallbacks, toolId, `Error rolling back: ${apiErrorMessage(e)}`) + } + } + } + ] +} + +function migrationStatus(status: 'ran' | 'not_run' | 'unknown'): 'applied' | 'pending' | 'unknown' { + return status === 'ran' ? 'applied' : status === 'not_run' ? 'pending' : 'unknown' +} + +function withRole(sql: string, role: string | undefined): string { + return role === undefined ? sql : withMigrationRole(sql, role) +} diff --git a/frontend/src/lib/components/copilot/chat/datatableTools.ts b/frontend/src/lib/components/copilot/chat/datatableTools.ts index 7a743ab783..e05b2e4325 100644 --- a/frontend/src/lib/components/copilot/chat/datatableTools.ts +++ b/frontend/src/lib/components/copilot/chat/datatableTools.ts @@ -286,6 +286,7 @@ export function getDatatableTools(): SessionTool<{}>[] { datatable_name: d.datatable_name, schemas: d.schemas, ...(d.error && { error: d.error }), + ...(d.migrations_enabled && { migrations_enabled: true }), ...(d.permissioned && { usable_roles: d.usable_roles, default_role: d.default_role }) })), null, diff --git a/frontend/src/lib/components/copilot/chat/flow/openFlow.json b/frontend/src/lib/components/copilot/chat/flow/openFlow.json index 11cee5b724..c9d3322bdb 100644 --- a/frontend/src/lib/components/copilot/chat/flow/openFlow.json +++ b/frontend/src/lib/components/copilot/chat/flow/openFlow.json @@ -1 +1 @@ -{"openapi":"3.0.3","info":{"version":"1.825.0","title":"OpenFlow Spec","contact":{"name":"Ruben Fiszel","email":"ruben@windmill.dev","url":"https://windmill.dev"},"license":{"name":"Apache 2.0","url":"https://www.apache.org/licenses/LICENSE-2.0.html"}},"paths":{},"externalDocs":{"description":"documentation portal","url":"https://windmill.dev"},"components":{"schemas":{"OpenFlow":{"type":"object","description":"Top-level flow definition containing metadata, configuration, and the flow structure","properties":{"summary":{"type":"string","description":"Short description of what this flow does"},"description":{"type":"string","description":"Detailed documentation for this flow"},"value":{"$ref":"#/components/schemas/FlowValue"},"schema":{"type":"object","description":"JSON Schema for flow inputs. Use this to define input parameters, their types, defaults, and validation. For resource inputs, set type to 'object' and format to 'resource-<type>' (e.g., 'resource-stripe')"},"on_behalf_of_email":{"type":"string","description":"Address of the account the flow runs on behalf of. Derived from on_behalf_of on read; accepted on write, where it is resolved to the account it names."},"on_behalf_of":{"type":"string","description":"The flow runs with the permissions of this identity: u/{username}, g/{group}, or a bare email when the username is itself email-shaped. The only stored half of the identity; on_behalf_of_email is derived from it. Omit it when writing and it is resolved from that address instead."}},"required":["summary","value"]},"FlowValue":{"type":"object","description":"The flow structure containing modules and optional preprocessor/failure handlers","properties":{"modules":{"type":"array","description":"Array of steps that execute in sequence. Each step can be a script, subflow, loop, or branch","items":{"$ref":"#/components/schemas/FlowModule"}},"failure_module":{"description":"Special module that executes when the flow fails. Receives error object with message, name, stack, and step_id. Must have id 'failure'. Only supports script/rawscript types","$ref":"#/components/schemas/FlowModule"},"preprocessor_module":{"description":"Special module that runs before the first step on external triggers. Must have id 'preprocessor'. Only supports script/rawscript types. Cannot reference other step results","$ref":"#/components/schemas/FlowModule"},"same_worker":{"type":"boolean","description":"If true, all steps run on the same worker for better performance"},"preserve_step_tags":{"type":"boolean","description":"If true and the flow runs on a custom worker tag, steps that declare their own non-empty tag run on it instead of inheriting the flow tag. Steps without their own tag still inherit the flow tag."},"concurrent_limit":{"type":"number","description":"Maximum number of concurrent executions of this flow"},"concurrency_key":{"type":"string","description":"Expression to group concurrent executions (e.g., by user ID)"},"concurrency_time_window_s":{"type":"number","description":"Time window in seconds for concurrent_limit"},"debounce_delay_s":{"type":"integer","description":"Delay in seconds to debounce flow executions"},"debounce_key":{"type":"string","description":"Expression to group debounced executions"},"debounce_args_to_accumulate":{"type":"array","description":"Arguments to accumulate across debounced executions","items":{"type":"string"}},"max_total_debouncing_time":{"type":"integer","description":"Maximum total time in seconds that a job can be debounced"},"max_total_debounces_amount":{"type":"integer","description":"Maximum number of times a job can be debounced"},"skip_expr":{"type":"string","description":"JavaScript expression to conditionally skip the entire flow"},"cache_ttl":{"type":"number","description":"Cache duration in seconds for flow results"},"cache_ignore_s3_path":{"type":"boolean"},"delete_after_secs":{"type":"integer","description":"If set, delete the flow job's args, result and logs after this many seconds following job completion"},"flow_env":{"type":"object","description":"Environment variables available to all steps. Values can be strings, JSON values, or special references: '$var:path' (workspace variable) or '$res:path' (resource).","additionalProperties":{}},"priority":{"type":"number","description":"Execution priority (higher numbers run first)"},"early_return":{"type":"string","description":"JavaScript expression to return early from the flow"},"chat_input_enabled":{"type":"boolean","description":"Whether this flow accepts chat-style input"},"notes":{"type":"array","description":"Sticky notes attached to the flow","items":{"$ref":"#/components/schemas/FlowNote"}},"groups":{"type":"array","description":"Semantic groups of modules for organizational purposes","items":{"$ref":"#/components/schemas/FlowGroup"}}},"required":["modules"]},"Retry":{"type":"object","description":"Retry configuration for failed module executions","properties":{"constant":{"type":"object","description":"Retry with constant delay between attempts","properties":{"attempts":{"type":"integer","description":"Number of retry attempts"},"seconds":{"type":"integer","description":"Seconds to wait between retries"}}},"exponential":{"type":"object","description":"Retry with exponential backoff: the n-th retry waits multiplier × seconds^n","properties":{"attempts":{"type":"integer","description":"Number of retry attempts"},"multiplier":{"type":"integer","description":"Multiplier for exponential backoff"},"seconds":{"type":"integer","minimum":1,"description":"Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too"},"random_factor":{"type":"integer","minimum":0,"maximum":100,"description":"Random jitter percentage (0-100) to avoid thundering herd"}}},"retry_if":{"$ref":"#/components/schemas/RetryIf"}}},"FlowNote":{"type":"object","description":"A sticky note attached to a flow for documentation and annotation","properties":{"id":{"type":"string","description":"Unique identifier for the note"},"text":{"type":"string","description":"Content of the note"},"position":{"type":"object","description":"Position of the note in the flow editor","properties":{"x":{"type":"number","description":"X coordinate"},"y":{"type":"number","description":"Y coordinate"}},"required":["x","y"]},"size":{"type":"object","description":"Size of the note in the flow editor","properties":{"width":{"type":"number","description":"Width in pixels"},"height":{"type":"number","description":"Height in pixels"}},"required":["width","height"]},"color":{"type":"string","description":"Color of the note, one of: yellow, blue, green, purple, pink, orange, red, cyan, lime, gray. Any other value renders unstyled."},"type":{"type":"string","enum":["free","group"],"description":"Type of note - 'free' for standalone notes. 'group' notes are deprecated; segment a flow with FlowValue.groups instead."},"locked":{"type":"boolean","default":false,"description":"Whether the note is locked and cannot be edited or moved"},"contained_node_ids":{"type":"array","items":{"type":"string"},"description":"For group notes, the IDs of nodes contained within this group"}},"required":["id","text","color","type"]},"FlowGroup":{"type":"object","description":"A semantic group of flow modules for organizational purposes. Does not affect execution — modules remain in their original position in the flow. Groups provide naming and collapsibility in the editor. Members are computed dynamically from all nodes on paths between start_id and end_id.","properties":{"summary":{"type":"string","description":"Display name for this group"},"note":{"type":"string","description":"Markdown note shown below the group header"},"autocollapse":{"type":"boolean","default":false,"description":"If true, this group is collapsed by default in the flow editor. UI hint only."},"start_id":{"type":"string","description":"ID of the first flow module in this group (topological entry point)"},"end_id":{"type":"string","description":"ID of the last flow module in this group (topological exit point)"},"color":{"type":"string","description":"Color for the group in the flow editor, one of: yellow, blue, green, purple, pink, orange, red, cyan, lime, gray. Omit it to let the editor pick one."}},"required":["start_id","end_id"]},"RetryIf":{"type":"object","description":"Conditional retry based on error or result","properties":{"expr":{"type":"string","description":"JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables"}},"required":["expr"]},"StopAfterIf":{"type":"object","description":"Early termination condition for a module","properties":{"skip_if_stopped":{"type":"boolean","description":"If true, following steps are skipped when this condition triggers"},"expr":{"type":"string","description":"JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"},"error_message":{"type":"string","nullable":true,"description":"Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised."},"error_include_result":{"type":"boolean","description":"When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false."}},"required":["expr"]},"FlowModule":{"type":"object","description":"A single step in a flow. Can be a script, subflow, loop, or branch","properties":{"id":{"type":"string","description":"Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"},"value":{"$ref":"#/components/schemas/FlowModuleValue"},"stop_after_if":{"description":"Early termination condition evaluated after this step completes","$ref":"#/components/schemas/StopAfterIf"},"stop_after_all_iters_if":{"description":"For loops only - early termination condition evaluated after all iterations complete","$ref":"#/components/schemas/StopAfterIf"},"skip_if":{"type":"object","description":"Conditionally skip this step based on previous results or flow inputs","properties":{"expr":{"type":"string","description":"JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.<step_id>'"}},"required":["expr"]},"sleep":{"description":"Delay before executing this step (in seconds or as expression)","$ref":"#/components/schemas/InputTransform"},"cache_ttl":{"type":"number","description":"Cache duration in seconds for this step's results"},"cache_ignore_s3_path":{"type":"boolean"},"timeout":{"description":"Maximum execution time in seconds (static value or expression)","$ref":"#/components/schemas/InputTransform"},"delete_after_secs":{"type":"integer","description":"If set, delete the step's args, result and logs after this many seconds following job completion"},"summary":{"type":"string","description":"Short description of what this step does"},"mock":{"type":"object","description":"Mock configuration for testing without executing the actual step","properties":{"enabled":{"type":"boolean","description":"If true, return mock value instead of executing"},"return_value":{"description":"Value to return when mocked"}}},"suspend":{"type":"object","description":"Configuration for approval/resume steps that wait for user input","properties":{"required_events":{"type":"integer","description":"Number of approvals required before continuing"},"timeout":{"type":"integer","description":"Timeout in seconds before auto-continuing or canceling"},"resume_form":{"type":"object","description":"Form schema for collecting input when resuming","properties":{"schema":{"type":"object","description":"JSON Schema for the resume form"}}},"user_auth_required":{"type":"boolean","description":"If true, only authenticated users can approve"},"user_groups_required":{"description":"Expression or list of groups that can approve","$ref":"#/components/schemas/InputTransform"},"self_approval_disabled":{"type":"boolean","description":"If true, the user who started the flow cannot approve"},"hide_cancel":{"type":"boolean","description":"If true, hide the cancel button on the approval form"},"continue_on_disapprove_timeout":{"type":"boolean","description":"If true, continue flow on timeout instead of canceling"},"skin":{"type":"string","enum":["detailed","minimal"],"description":"How the approval request is presented, on the approval page and in Slack/Teams approval messages. 'detailed' (used when unset) shows the flow details (arguments, graph, approvers); 'minimal' shows only the request: the step description, form and approve/reject actions"}}},"priority":{"type":"number","description":"Execution priority for this step (higher numbers run first)"},"continue_on_error":{"type":"boolean","description":"If true, flow continues even if this step fails"},"job_token_scopes":{"type":"array","nullable":true,"items":{"type":"string"},"description":"Scopes the token of this step's jobs is restricted to (domain:action[:resource], e.g. oidc:write), on top of the flow's own restriction: a step can only narrow it. Applies to everything the step runs (loop and branch bodies, AI agent tools)."},"retry":{"description":"Retry configuration if this step fails","$ref":"#/components/schemas/Retry"},"debouncing":{"description":"Debounce configuration for this step (EE only)","type":"object","properties":{"debounce_delay_s":{"type":"integer","description":"Delay in seconds to debounce this step's executions across flow runs"},"debounce_key":{"type":"string","description":"Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/<flow_path>-<step_id>"},"debounce_args_to_accumulate":{"type":"array","description":"Array-type arguments to accumulate across debounced executions","items":{"type":"string"}},"max_total_debouncing_time":{"type":"integer","description":"Maximum total time in seconds before forced execution"},"max_total_debounces_amount":{"type":"integer","description":"Maximum number of debounces before forced execution"}}}},"required":["value","id"]},"InputTransform":{"description":"Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs","oneOf":[{"$ref":"#/components/schemas/StaticTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type"}},"StaticTransform":{"type":"object","description":"Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'","properties":{"value":{"description":"The static value. For resources, use format '$res:path/to/resource'"},"type":{"type":"string","enum":["static"]}},"required":["type"]},"JavascriptTransform":{"type":"object","description":"JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')","properties":{"expr":{"type":"string","description":"JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"},"type":{"type":"string","enum":["javascript"]}},"required":["expr","type"]},"AiTransform":{"type":"object","description":"Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.","properties":{"type":{"type":"string","enum":["ai"]}},"required":["type"]},"AIProviderKind":{"type":"string","description":"Supported AI provider types","enum":["openai","azure_openai","azure_foundry","anthropic","mistral","deepseek","googleai","groq","openrouter","togetherai","customai","aws_bedrock","typesafe","cloudflare"]},"ProviderConfig":{"type":"object","description":"Complete AI provider configuration with resource reference and model selection","properties":{"kind":{"$ref":"#/components/schemas/AIProviderKind"},"resource":{"type":"string","description":"Resource reference in format '$res:{resource_path}' pointing to provider credentials"},"model":{"type":"string","description":"Model identifier (e.g., 'gpt-4', 'claude-3-opus-20240229', 'gemini-pro')"},"reasoning_effort":{"type":"string","description":"Provider-native reasoning effort token (e.g. 'low', 'high', 'none') for models that support extended thinking. Optional; unset leaves the provider default."}},"required":["kind","resource","model"]},"StaticProviderTransform":{"type":"object","description":"Static provider configuration passed directly to the AI agent","properties":{"value":{"$ref":"#/components/schemas/ProviderConfig"},"type":{"type":"string","enum":["static"]}},"required":["type","value"]},"ProviderTransform":{"description":"Provider configuration - can be static (ProviderConfig), JavaScript expression, or AI-determined","oneOf":[{"$ref":"#/components/schemas/StaticProviderTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type"}},"MemoryOff":{"type":"object","description":"No conversation memory/context","properties":{"kind":{"type":"string","enum":["off"]}},"required":["kind"]},"MemoryWindow":{"type":"object","description":"Keeps the most recent messages of the memory named by the run's memory id (or the step's\n`memory_id`). Without a memory id the agent runs without memory.\n","properties":{"kind":{"type":"string","enum":["window"]},"context_length":{"type":"integer","description":"Number of most recent messages to load and store. 0 turns memory off."}},"required":["kind","context_length"]},"MemoryAuto":{"type":"object","deprecated":true,"description":"Deprecated, still read as it was written: the run's memory id, else the `memory_id` here.\nThe step's own `memory_id` is not read while this kind is set; switch the kind to `window`\nto use it. Without a `context_length`, or with 0, it is `off` and reads `previous_messages`.\n","properties":{"kind":{"type":"string","enum":["auto"]},"context_length":{"type":"integer","description":"Maximum number of messages to retain in context"},"memory_id":{"type":"string","description":"Identifier for persistent memory across agent invocations"}},"required":["kind"]},"MemoryCompaction":{"type":"object","description":"Keeps the whole memory named by the run's memory id (or the step's `memory_id`), replacing\nits older part with a summary as the conversation approaches the model's context window.\nWithout a memory id the agent runs without memory, and compaction bounds the run's own loop.\n","properties":{"kind":{"type":"string","enum":["compaction"]},"context_window":{"type":"integer","description":"Overrides the context window looked up from the model, in tokens. Only a model\nWindmill does not know needs one; those fall back to 128000.\n"}},"required":["kind"]},"MemoryMessage":{"type":"object","description":"A single message in conversation history","properties":{"role":{"type":"string","enum":["user","assistant","system"]},"content":{"type":"string"}},"required":["role","content"]},"MemoryManual":{"type":"object","deprecated":true,"description":"Deprecated, still read as it was written. Move the step to `off` with `previous_messages` instead.","properties":{"kind":{"type":"string","enum":["manual"]},"messages":{"type":"array","items":{"$ref":"#/components/schemas/MemoryMessage"}}},"required":["kind","messages"]},"MemoryConfig":{"description":"Managed memory, stored by Windmill and replayed with each request. The memory is named by a memory id, see `memory_id`. While it is off, a step can supply its history in `previous_messages`.","oneOf":[{"$ref":"#/components/schemas/MemoryOff"},{"$ref":"#/components/schemas/MemoryWindow"},{"$ref":"#/components/schemas/MemoryCompaction"},{"$ref":"#/components/schemas/MemoryAuto"},{"$ref":"#/components/schemas/MemoryManual"}],"discriminator":{"propertyName":"kind"}},"StaticMemoryTransform":{"type":"object","description":"Static memory configuration passed directly to the AI agent","properties":{"value":{"$ref":"#/components/schemas/MemoryConfig"},"type":{"type":"string","enum":["static"]}},"required":["type","value"]},"MemoryTransform":{"description":"Memory configuration - can be static (MemoryConfig), JavaScript expression, or AI-determined","oneOf":[{"$ref":"#/components/schemas/StaticMemoryTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type"}},"FlowModuleValue":{"description":"The actual implementation of a flow step. Can be a script (inline or referenced), subflow, loop, branch, or special module type","oneOf":[{"$ref":"#/components/schemas/RawScript"},{"$ref":"#/components/schemas/PathScript"},{"$ref":"#/components/schemas/PathFlow"},{"$ref":"#/components/schemas/ForloopFlow"},{"$ref":"#/components/schemas/WhileloopFlow"},{"$ref":"#/components/schemas/BranchOne"},{"$ref":"#/components/schemas/BranchAll"},{"$ref":"#/components/schemas/Identity"},{"$ref":"#/components/schemas/AiAgent"},{"$ref":"#/components/schemas/AiDecision"}],"discriminator":{"propertyName":"type"}},"RawScript":{"type":"object","description":"Inline script with code defined directly in the flow. Use 'bun' as default language if unspecified. The script receives arguments from input_transforms","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"content":{"type":"string","description":"The script source code. Should export a 'main' function"},"language":{"type":"string","description":"Programming language for this script","enum":["deno","bun","bunnative","python3","go","bash","powershell","postgresql","mysql","bigquery","snowflake","mssql","oracledb","graphql","nativets","php","rust","ansible","csharp","nu","java","ruby","rlang","duckdb"]},"path":{"type":"string","description":"Optional path for saving this script"},"lock":{"type":"string","description":"Lock file content for dependencies"},"type":{"type":"string","enum":["rawscript"]},"tag":{"type":"string","description":"Worker group tag for execution routing"},"concurrent_limit":{"type":"number","description":"Maximum concurrent executions of this script"},"concurrency_time_window_s":{"type":"number","description":"Time window for concurrent_limit"},"custom_concurrency_key":{"type":"string","description":"Custom key for grouping concurrent executions"},"is_trigger":{"type":"boolean","description":"If true, this script is a trigger that can start the flow"},"assets":{"type":"array","description":"External resources this script accesses (S3 objects, resources, etc.)","items":{"type":"object","required":["path","kind"],"properties":{"path":{"type":"string","description":"Path to the asset"},"kind":{"type":"string","description":"Type of asset","enum":["s3object","resource","ducklake","datatable","volume","dbt"]},"access_type":{"type":"string","nullable":true,"description":"Access level for this asset","enum":["r","w","rw",null]},"alt_access_type":{"type":"string","nullable":true,"description":"Alternative access level","enum":["r","w","rw",null]}}}}},"required":["type","content","language","input_transforms"]},"PathScript":{"type":"object","description":"Reference to an existing script by path. Use this when calling a previously saved script instead of writing inline code","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"path":{"type":"string","description":"Path to the script in the workspace (e.g., 'f/scripts/send_email')"},"hash":{"type":"string","description":"Optional specific version hash of the script to use"},"type":{"type":"string","enum":["script"]},"tag_override":{"type":"string","description":"Override the script's default worker group tag"},"is_trigger":{"type":"boolean","description":"If true, this script is a trigger that can start the flow"}},"required":["type","path","input_transforms"]},"PathFlow":{"type":"object","description":"Reference to an existing flow by path. Use this to call another flow as a subflow","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the subflow's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"path":{"type":"string","description":"Path to the flow in the workspace (e.g., 'f/flows/process_user')"},"type":{"type":"string","enum":["flow"]}},"required":["type","path","input_transforms"]},"ForloopFlow":{"type":"object","description":"Executes nested modules in a loop over an iterator. Inside the loop, use 'flow_input.iter.value' to access the current iteration value, and 'flow_input.iter.index' for the index. Supports parallel execution for better performance on I/O-bound operations","properties":{"modules":{"type":"array","description":"Steps to execute for each iteration. These can reference the iteration value via 'flow_input.iter.value'","items":{"$ref":"#/components/schemas/FlowModule"}},"iterator":{"description":"JavaScript expression that returns an array to iterate over. Can reference 'results.step_id' or 'flow_input'","$ref":"#/components/schemas/InputTransform"},"skip_failures":{"type":"boolean","description":"If true, iteration failures don't stop the loop. Failed iterations return null"},"type":{"type":"string","enum":["forloopflow"]},"parallel":{"type":"boolean","description":"If true, iterations run concurrently (faster for I/O-bound operations). Use with parallelism to control concurrency"},"parallelism":{"description":"Maximum number of concurrent iterations when parallel=true. Limits resource usage. Can be static number or expression","$ref":"#/components/schemas/InputTransform"},"squash":{"type":"boolean"}},"required":["modules","iterator","skip_failures","type"]},"WhileloopFlow":{"type":"object","description":"Executes nested modules repeatedly until stopped. The implicit iterator is the iteration counter, so 'flow_input.iter.value' equals 'flow_input.iter.index' (0, 1, 2, ...) and never carries state. To carry state across iterations, a step reads its own previous-iteration result via 'results.<its_own_id>' with a first-iteration fallback - the loop's stop_after_if must then be on that inner step (a plain single-step body with stop_after_if on the loop module does not resolve 'results' across iterations and never terminates); plain counters can instead be derived from 'flow_input.iter.index', which works in every configuration. stop_after_if is evaluated after each iteration - on the loop module 'result' is the last iteration's result","properties":{"modules":{"type":"array","description":"Steps to execute in each iteration","items":{"$ref":"#/components/schemas/FlowModule"}},"skip_failures":{"type":"boolean","description":"If true, iteration failures don't stop the loop. Failed iterations return null"},"type":{"type":"string","enum":["whileloopflow"]},"parallel":{"type":"boolean","description":"If true, iterations run concurrently (use with caution in while loops)"},"parallelism":{"description":"Maximum number of concurrent iterations when parallel=true","$ref":"#/components/schemas/InputTransform"},"squash":{"type":"boolean"}},"required":["modules","skip_failures","type"]},"BranchOne":{"type":"object","description":"Conditional branching where only the first matching branch executes. Branches are evaluated in order, and the first one with a true expression runs. If no branches match, the default branch executes","properties":{"branches":{"type":"array","description":"Array of branches to evaluate in order. The first branch with expr evaluating to true executes","items":{"type":"object","properties":{"summary":{"type":"string","description":"Short description of this branch condition"},"expr":{"type":"string","description":"JavaScript expression that returns boolean. Can use 'results.step_id' or 'flow_input'. First true expr wins"},"modules":{"type":"array","description":"Steps to execute if this branch's expr is true","items":{"$ref":"#/components/schemas/FlowModule"}}},"required":["modules","expr"]}},"default":{"type":"array","description":"Steps to execute if no branch expressions match","items":{"$ref":"#/components/schemas/FlowModule"}},"type":{"type":"string","enum":["branchone"]}},"required":["branches","default","type"]},"BranchAll":{"type":"object","description":"Parallel branching where all branches execute simultaneously. Unlike BranchOne, all branches run regardless of conditions. Useful for executing independent tasks concurrently","properties":{"branches":{"type":"array","description":"Array of branches that all execute (either in parallel or sequentially)","items":{"type":"object","properties":{"summary":{"type":"string","description":"Short description of this branch's purpose"},"skip_failure":{"type":"boolean","description":"If true, failure in this branch doesn't fail the entire flow"},"modules":{"type":"array","description":"Steps to execute in this branch","items":{"$ref":"#/components/schemas/FlowModule"}}},"required":["modules"]}},"type":{"type":"string","enum":["branchall"]},"parallel":{"type":"boolean","description":"If true, all branches execute concurrently. If false, they execute sequentially"}},"required":["branches","type"]},"AgentTool":{"type":"object","description":"A tool available to an AI agent. Can be a flow module or an external MCP (Model Context Protocol) tool","properties":{"id":{"type":"string","description":"Unique identifier for this tool. Cannot contain spaces - use underscores instead (e.g., 'get_user_data' not 'get user data')"},"summary":{"type":"string","description":"The name the AI agent calls this tool by, not a human label. On a flowmodule tool it must match ^[a-zA-Z0-9_]+$ - letters, numbers and underscores only (e.g. 'search_documentation', not 'Search documentation') - and always be set; on an mcp or websearch tool it is a plain label. Put the human-readable explanation in 'description'."},"description":{"type":"string","description":"Free-text description of the tool given to the AI to decide when and how to call it. Overrides the description auto-derived from the underlying script."},"job_token_scopes":{"type":"array","nullable":true,"items":{"type":"string"},"description":"Scopes the token of this tool's jobs is restricted to, on top of the agent step's own restriction: a tool can only narrow it."},"value":{"$ref":"#/components/schemas/ToolValue"}},"required":["id","value"]},"ToolValue":{"description":"The implementation of a tool. Can be a flow module (script/flow) or an MCP tool reference","oneOf":[{"$ref":"#/components/schemas/FlowModuleTool"},{"$ref":"#/components/schemas/McpToolValue"},{"$ref":"#/components/schemas/WebsearchToolValue"}]},"FlowModuleTool":{"description":"A tool implemented as a flow module (script, flow, etc.). The AI can call this like any other flow module","allOf":[{"type":"object","properties":{"tool_type":{"type":"string","enum":["flowmodule"]}},"required":["tool_type"]},{"$ref":"#/components/schemas/FlowModuleValue"}]},"WebsearchToolValue":{"type":"object","description":"A tool implemented as a websearch tool. The AI can call this like any other websearch tool","properties":{"tool_type":{"type":"string","enum":["websearch"]}},"required":["tool_type"]},"McpToolValue":{"type":"object","description":"Reference to an external MCP (Model Context Protocol) tool. The AI can call tools from MCP servers","properties":{"tool_type":{"type":"string","enum":["mcp"]},"resource_path":{"type":"string","description":"Path to the MCP resource/server configuration"},"include_tools":{"type":"array","description":"Whitelist of specific tools to include from this MCP server","items":{"type":"string"}},"exclude_tools":{"type":"array","description":"Blacklist of tools to exclude from this MCP server","items":{"type":"string"}}},"required":["tool_type","resource_path"]},"AiAgent":{"type":"object","description":"AI agent step that can use tools to accomplish tasks. The agent receives inputs and can call any of its configured tools to complete the task","properties":{"input_transforms":{"type":"object","description":"Input parameters for the AI agent mapped to their values","properties":{"provider":{"$ref":"#/components/schemas/ProviderTransform"},"output_type":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Output format type.\nValid values: 'text' (default) - plain text response, 'image' - image generation\n"},"user_message":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"The user's prompt/message to the AI agent. Supports variable interpolation with\nflow.input syntax. Required unless memory is off and `previous_messages` supplies\nthe prompt; image output always needs it.\n"},"system_prompt":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"System instructions that guide the AI's behavior, persona, and response style. Optional."},"streaming":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Boolean. If true, stream the AI response incrementally.\nStreaming events include: token_delta, reasoning_token_delta, tool_call, tool_call_arguments, tool_execution, tool_result\n"},"memory":{"$ref":"#/components/schemas/MemoryTransform"},"memory_id":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"String. Names the memory this step reads and writes, overriding the memory id the run\nwas started with (the chat conversation, an app chat session or the `memory_id` run\nparameter). Leave unset to use the run's memory id. A fixed value shares one memory\nacross every run; an expression such as `flow_input.customer_id` keeps one memory per\nkey. When it evaluates to an empty value the agent runs without memory. Read only\nwhile `memory` is `window` or `compaction`: it is ignored when memory is off, and an\nolder `auto` or `manual` memory reads neither history input.\n"},"previous_messages":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Array of MemoryMessage. History supplied by the flow, sent between the system prompt\nand the user message. Read only while `memory` is off or absent: managed memory\nignores it, and an older `auto` or `manual` memory reads neither history input.\n"},"output_schema":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"JSON Schema object defining structured output format. Used when you need the AI to return data in a specific shape.\nSupports standard JSON Schema properties: type, properties, required, items, enum, pattern, minLength, maxLength, minimum, maximum, etc.\nExample: { type: 'object', properties: { name: { type: 'string' }, age: { type: 'integer' } }, required: ['name'] }\n"},"user_attachments":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Array of file references (images or PDFs) for the AI agent.\nFormat: Array<{ bucket: string, key: string }> - S3 object references\nExample: [{ bucket: 'my-bucket', key: 'documents/report.pdf' }]\n"},"enabled_tools":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Array of strings naming which of the tools configured in `tools` the agent may call\nthis run. Leaving it unset carries every one of them; an empty array carries none.\nA tool is named as the model is shown it. An entry the model is shown nothing of is\nnamed by what identifies it instead: an MCP server by its resource path, carrying\nevery tool it exposes (which of them stays that entry's include_tools/exclude_tools),\nand a websearch entry by the reserved name '__wm_web_search', whatever summary it carries\n(no tool may take that name).\nExample: ['get_user', 'u/admin/github_mcp', '__wm_web_search']\n"},"max_completion_tokens":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Integer. Maximum number of tokens the AI will generate in its response.\nRange: 1 to 4,294,967,295. Typical values: 256-4096 for most use cases.\n"},"temperature":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Float. Controls randomness/creativity of responses.\nRange: 0.0 to 2.0 (provider-dependent)\n- 0.0 = deterministic, focused responses\n- 0.7 = balanced (common default)\n- 1.0+ = more creative/random\n"},"max_iterations":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Number. Limits how many times the agent can loop through reasoning and tool use.\nRange: 1-1000.\n"}}},"tools":{"type":"array","description":"Array of tools the agent can use. The agent decides which tools to call based on the task","items":{"$ref":"#/components/schemas/AgentTool"}},"type":{"type":"string","enum":["aiagent"]},"tag":{"type":"string","description":"Worker group tag for execution routing. If not set, the AI agent step runs on the flow's tag (default `flow`)"},"omit_output_from_conversation":{"type":"boolean","default":false,"description":"If true, this AI agent step does not persist its assistant or tool messages to the flow conversation when chat mode is enabled."},"agent":{"type":"string","description":"Path of a reusable `ai_agent` resource (hybrid linking). When set, the agent brain\nconfig (provider/model/system prompt/etc.) and tool set are resolved at runtime from\nthat resource; the module's input_transforms then only carry the flow-local inputs\n(user_message, user_attachments, enabled_tools and the history inputs memory_id and previous_messages).\n"},"tool_inputs":{"type":"object","description":"Host-local wiring for an agent's tool inputs, keyed by tool id then input key. Binds the\nreferenced agent's tools to this flow's context (flow_input/results) without mutating the\nshared resource; overlaid onto the tools' input_transforms at runtime — including when\n`agent` is unset, since a step forked for editing keeps these overrides until it is saved\nback or unlinked.\n","additionalProperties":{"type":"object","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}}},"parallel":{"type":"boolean","description":"If true, the agent can execute multiple tool calls in parallel"}},"required":["type","input_transforms"]},"AiDecision":{"type":"object","description":"AI decision step: one call to a decision model (TypeSafe's Jev, Cloudflare's\nJev-compatible Clef, or OpenAI's Decisions API) that answers typed questions about a\nstate with calibrated probabilities, instead of generating text.\nPrefer it over an AI agent to classify, route, score or check something: it is fast,\ncheap and its answers are structured. Its result is { output: { <question name>: answer },\nmodel, usage }, so a later step reads e.g. results.<id>.output.intent.choice. To route on\nthe answers, follow it with a branchone whose branch exprs read\nresults.<id>.output.<question>.choice. Usable as an AI agent tool, where the calling agent\nsupplies the state.\n","properties":{"input_transforms":{"type":"object","description":"Input parameters for the decision mapped to their values","properties":{"provider":{"$ref":"#/components/schemas/ProviderTransform"},"state":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"What the questions are asked about: a string, an object or an array of strings.\nAn object with descriptive keys holding only what the questions need works best.\nExample: { message: flow_input.message, plan: results.a.plan }\n"},"questions":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Object mapping each question name to { type, instructions, criteria }, where type is:\n- 'choice': criteria maps each option to its description (up to 255); the answer\n has choice, probabilities and confidence\n- 'score': criteria is an ordered array of 2 to 10 level descriptions; the answer\n has score, legend, probabilities and confidence\n- 'noul': yes/no, criteria optionally { true, false } descriptions; the answer has\n noul, the probability of yes (0 to 1)\nExample: { intent: { type: 'choice', instructions: 'What does the customer want?',\ncriteria: { refund: 'Money back', bug: 'Something is broken' } } }\n"}},"required":["provider","state","questions"]},"type":{"type":"string","enum":["aidecision"]},"tag":{"type":"string","description":"Worker group tag for execution routing. If not set, the step runs on the flow's tag (default `flow`)"}},"required":["type","input_transforms"]},"Identity":{"type":"object","description":"Pass-through module that returns its input unchanged. Useful for flow structure or as a placeholder","properties":{"type":{"type":"string","enum":["identity"]},"flow":{"type":"boolean","description":"If true, marks this as a flow identity (special handling)"}},"required":["type"]},"FlowStatus":{"type":"object","properties":{"step":{"type":"integer"},"modules":{"type":"array","items":{"$ref":"#/components/schemas/FlowStatusModule"}},"user_states":{"additionalProperties":true},"preprocessor_module":{"allOf":[{"$ref":"#/components/schemas/FlowStatusModule"}]},"failure_module":{"allOf":[{"$ref":"#/components/schemas/FlowStatusModule"},{"type":"object","properties":{"parent_module":{"type":"string"}}}]},"retry":{"type":"object","properties":{"fail_count":{"type":"integer"},"failed_jobs":{"type":"array","items":{"type":"string","format":"uuid"}}}}},"required":["step","modules","failure_module"]},"FlowStatusModule":{"type":"object","properties":{"type":{"type":"string","enum":["WaitingForPriorSteps","WaitingForEvents","WaitingForExecutor","InProgress","Success","Failure"]},"id":{"type":"string"},"job":{"type":"string","format":"uuid"},"count":{"type":"integer"},"progress":{"type":"integer"},"iterator":{"type":"object","properties":{"index":{"type":"integer"},"itered":{"type":"array","items":{}},"itered_len":{"type":"integer"},"args":{}}},"flow_jobs":{"type":"array","items":{"type":"string"}},"flow_jobs_success":{"type":"array","items":{"type":"boolean"}},"flow_jobs_duration":{"type":"object","properties":{"started_at":{"type":"array","items":{"type":"string"}},"duration_ms":{"type":"array","items":{"type":"integer"}}}},"branch_chosen":{"type":"object","properties":{"type":{"type":"string","enum":["branch","default"]},"branch":{"type":"integer"}},"required":["type"]},"branchall":{"type":"object","properties":{"branch":{"type":"integer"},"len":{"type":"integer"}},"required":["branch","len"]},"approvers":{"type":"array","items":{"type":"object","properties":{"resume_id":{"type":"integer"},"approver":{"type":"string"}},"required":["resume_id","approver"]}},"failed_retries":{"type":"array","items":{"type":"string","format":"uuid"}},"skipped":{"type":"boolean"},"agent_actions":{"type":"array","items":{"type":"object","oneOf":[{"type":"object","properties":{"job_id":{"type":"string","format":"uuid"},"function_name":{"type":"string"},"type":{"type":"string","enum":["tool_call"]},"module_id":{"type":"string"}},"required":["job_id","function_name","type","module_id"]},{"type":"object","properties":{"call_id":{"type":"string","format":"uuid"},"function_name":{"type":"string"},"resource_path":{"type":"string"},"type":{"type":"string","enum":["mcp_tool_call"]},"arguments":{"type":"object"}},"required":["call_id","function_name","resource_path","type"]},{"type":"object","properties":{"type":{"type":"string","enum":["web_search"]}},"required":["type"]},{"type":"object","properties":{"type":{"type":"string","enum":["message"]}},"required":["content","type"]}]}},"agent_actions_success":{"type":"array","items":{"type":"boolean"}}},"required":["type"]}}}} \ No newline at end of file +{"openapi":"3.0.3","info":{"version":"1.830.0","title":"OpenFlow Spec","contact":{"name":"Ruben Fiszel","email":"ruben@windmill.dev","url":"https://windmill.dev"},"license":{"name":"Apache 2.0","url":"https://www.apache.org/licenses/LICENSE-2.0.html"}},"paths":{},"externalDocs":{"description":"documentation portal","url":"https://windmill.dev"},"components":{"schemas":{"OpenFlow":{"type":"object","description":"Top-level flow definition containing metadata, configuration, and the flow structure","properties":{"summary":{"type":"string","description":"Short description of what this flow does"},"description":{"type":"string","description":"Detailed documentation for this flow"},"value":{"$ref":"#/components/schemas/FlowValue"},"schema":{"type":"object","description":"JSON Schema for flow inputs. Use this to define input parameters, their types, defaults, and validation. For resource inputs, set type to 'object' and format to 'resource-<type>' (e.g., 'resource-stripe')"},"on_behalf_of_email":{"type":"string","description":"Address of the account the flow runs on behalf of. Derived from on_behalf_of on read; accepted on write, where it is resolved to the account it names."},"on_behalf_of":{"type":"string","description":"The flow runs with the permissions of this identity: u/{username}, g/{group}, or a bare email when the username is itself email-shaped. The only stored half of the identity; on_behalf_of_email is derived from it. Omit it when writing and it is resolved from that address instead."}},"required":["summary","value"]},"FlowValue":{"type":"object","description":"The flow structure containing modules and optional preprocessor/failure handlers","properties":{"modules":{"type":"array","description":"Array of steps that execute in sequence. Each step can be a script, subflow, loop, or branch","items":{"$ref":"#/components/schemas/FlowModule"}},"failure_module":{"description":"Special module that executes when the flow fails. Receives error object with message, name, stack, and step_id. Must have id 'failure'. Only supports script/rawscript types","$ref":"#/components/schemas/FlowModule"},"preprocessor_module":{"description":"Special module that runs before the first step on external triggers. Must have id 'preprocessor'. Only supports script/rawscript types. Cannot reference other step results","$ref":"#/components/schemas/FlowModule"},"same_worker":{"type":"boolean","description":"If true, all steps run on the same worker for better performance"},"preserve_step_tags":{"type":"boolean","description":"If true and the flow runs on a custom worker tag, steps that declare their own non-empty tag run on it instead of inheriting the flow tag. Steps without their own tag still inherit the flow tag."},"concurrent_limit":{"type":"number","description":"Maximum number of concurrent executions of this flow"},"concurrency_key":{"type":"string","description":"Expression to group concurrent executions (e.g., by user ID)"},"concurrency_time_window_s":{"type":"number","description":"Time window in seconds for concurrent_limit"},"debounce_delay_s":{"type":"integer","description":"Delay in seconds to debounce flow executions"},"debounce_key":{"type":"string","description":"Expression to group debounced executions"},"debounce_args_to_accumulate":{"type":"array","description":"Arguments to accumulate across debounced executions","items":{"type":"string"}},"max_total_debouncing_time":{"type":"integer","description":"Maximum total time in seconds that a job can be debounced"},"max_total_debounces_amount":{"type":"integer","description":"Maximum number of times a job can be debounced"},"skip_expr":{"type":"string","description":"JavaScript expression to conditionally skip the entire flow"},"cache_ttl":{"type":"number","description":"Cache duration in seconds for flow results"},"cache_ignore_s3_path":{"type":"boolean"},"delete_after_secs":{"type":"integer","description":"If set, delete the flow job's args, result and logs after this many seconds following job completion"},"flow_env":{"type":"object","description":"Environment variables available to all steps. Values can be strings, JSON values, or special references: '$var:path' (workspace variable) or '$res:path' (resource).","additionalProperties":{}},"priority":{"type":"number","description":"Execution priority (higher numbers run first)"},"early_return":{"type":"string","description":"Id of the step whose result a sync webhook returns as soon as that step completes, while the rest of the flow keeps running. When the step does not run, or fails while the flow has a failure module, the flow's final result is returned instead."},"chat_input_enabled":{"type":"boolean","description":"Whether this flow accepts chat-style input"},"notes":{"type":"array","description":"Sticky notes attached to the flow","items":{"$ref":"#/components/schemas/FlowNote"}},"groups":{"type":"array","description":"Semantic groups of modules for organizational purposes","items":{"$ref":"#/components/schemas/FlowGroup"}}},"required":["modules"]},"Retry":{"type":"object","description":"Retry configuration for failed module executions","properties":{"constant":{"type":"object","description":"Retry with constant delay between attempts","properties":{"attempts":{"type":"integer","description":"Number of retry attempts"},"seconds":{"type":"integer","description":"Seconds to wait between retries"}}},"exponential":{"type":"object","description":"Retry with exponential backoff: the n-th retry waits multiplier × seconds^n","properties":{"attempts":{"type":"integer","description":"Number of retry attempts"},"multiplier":{"type":"integer","description":"Multiplier for exponential backoff"},"seconds":{"type":"integer","minimum":1,"description":"Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too"},"random_factor":{"type":"integer","minimum":0,"maximum":100,"description":"Random jitter percentage (0-100) to avoid thundering herd"}}},"retry_if":{"$ref":"#/components/schemas/RetryIf"}}},"FlowNote":{"type":"object","description":"A sticky note attached to a flow for documentation and annotation","properties":{"id":{"type":"string","description":"Unique identifier for the note"},"text":{"type":"string","description":"Content of the note"},"position":{"type":"object","description":"Position of the note in the flow editor","properties":{"x":{"type":"number","description":"X coordinate"},"y":{"type":"number","description":"Y coordinate"}},"required":["x","y"]},"size":{"type":"object","description":"Size of the note in the flow editor","properties":{"width":{"type":"number","description":"Width in pixels"},"height":{"type":"number","description":"Height in pixels"}},"required":["width","height"]},"color":{"type":"string","description":"Color of the note, one of: yellow, blue, green, purple, pink, orange, red, cyan, lime, gray. Any other value renders unstyled."},"type":{"type":"string","enum":["free","group"],"description":"Type of note - 'free' for standalone notes. 'group' notes are deprecated; segment a flow with FlowValue.groups instead."},"locked":{"type":"boolean","default":false,"description":"Whether the note is locked and cannot be edited or moved"},"contained_node_ids":{"type":"array","items":{"type":"string"},"description":"For group notes, the IDs of nodes contained within this group"}},"required":["id","text","color","type"]},"FlowGroup":{"type":"object","description":"A semantic group of flow modules for organizational purposes. Does not affect execution — modules remain in their original position in the flow. Groups provide naming and collapsibility in the editor. Members are computed dynamically from all nodes on paths between start_id and end_id.","properties":{"summary":{"type":"string","description":"Display name for this group"},"note":{"type":"string","description":"Markdown note shown below the group header"},"autocollapse":{"type":"boolean","default":false,"description":"If true, this group is collapsed by default in the flow editor. UI hint only."},"start_id":{"type":"string","description":"ID of the first flow module in this group (topological entry point)"},"end_id":{"type":"string","description":"ID of the last flow module in this group (topological exit point)"},"color":{"type":"string","description":"Color for the group in the flow editor, one of: yellow, blue, green, purple, pink, orange, red, cyan, lime, gray. Omit it to let the editor pick one."}},"required":["start_id","end_id"]},"RetryIf":{"type":"object","description":"Conditional retry based on error or result","properties":{"expr":{"type":"string","description":"JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables"}},"required":["expr"]},"StopAfterIf":{"type":"object","description":"Early termination condition for a module","properties":{"skip_if_stopped":{"type":"boolean","description":"If true, following steps are skipped when this condition triggers"},"expr":{"type":"string","description":"JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"},"error_message":{"type":"string","nullable":true,"description":"Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised."},"error_include_result":{"type":"boolean","description":"When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false."}},"required":["expr"]},"FlowModule":{"type":"object","description":"A single step in a flow. Can be a script, subflow, loop, or branch","properties":{"id":{"type":"string","description":"Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"},"value":{"$ref":"#/components/schemas/FlowModuleValue"},"stop_after_if":{"description":"Early termination condition evaluated after this step completes","$ref":"#/components/schemas/StopAfterIf"},"stop_after_all_iters_if":{"description":"For loops only - early termination condition evaluated after all iterations complete","$ref":"#/components/schemas/StopAfterIf"},"skip_if":{"type":"object","description":"Conditionally skip this step based on previous results or flow inputs","properties":{"expr":{"type":"string","description":"JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.<step_id>'"}},"required":["expr"]},"sleep":{"description":"Delay before executing this step (in seconds or as expression)","$ref":"#/components/schemas/InputTransform"},"cache_ttl":{"type":"number","description":"Cache duration in seconds for this step's results"},"cache_ignore_s3_path":{"type":"boolean"},"timeout":{"description":"Maximum execution time in seconds (static value or expression)","$ref":"#/components/schemas/InputTransform"},"delete_after_secs":{"type":"integer","description":"If set, delete the step's args, result and logs after this many seconds following job completion"},"summary":{"type":"string","description":"Short description of what this step does"},"mock":{"type":"object","description":"Mock configuration for testing without executing the actual step","properties":{"enabled":{"type":"boolean","description":"If true, return mock value instead of executing"},"return_value":{"description":"Value to return when mocked"}}},"suspend":{"type":"object","description":"Configuration for approval/resume steps that wait for user input","properties":{"required_events":{"type":"integer","description":"Number of approvals required before continuing"},"timeout":{"type":"integer","description":"Timeout in seconds before auto-continuing or canceling"},"resume_form":{"type":"object","description":"Form schema for collecting input when resuming","properties":{"schema":{"type":"object","description":"JSON Schema for the resume form"}}},"user_auth_required":{"type":"boolean","description":"If true, only authenticated users can approve"},"user_groups_required":{"description":"Expression or list of groups that can approve","$ref":"#/components/schemas/InputTransform"},"self_approval_disabled":{"type":"boolean","description":"If true, the user who started the flow cannot approve"},"hide_cancel":{"type":"boolean","description":"If true, hide the cancel button on the approval form"},"continue_on_disapprove_timeout":{"type":"boolean","description":"If true, continue flow on timeout instead of canceling"},"skin":{"type":"string","enum":["detailed","minimal"],"description":"How the approval request is presented, on the approval page and in Slack/Teams approval messages. 'detailed' (used when unset) shows the flow details (arguments, graph, approvers); 'minimal' shows only the request: the step description, form and approve/reject actions"}}},"priority":{"type":"number","description":"Execution priority for this step (higher numbers run first)"},"continue_on_error":{"type":"boolean","description":"If true, flow continues even if this step fails"},"job_token_scopes":{"type":"array","nullable":true,"items":{"type":"string"},"description":"Scopes the token of this step's jobs is restricted to (domain:action[:resource], e.g. oidc:write), on top of the flow's own restriction: a step can only narrow it. Applies to everything the step runs (loop and branch bodies, AI agent tools)."},"retry":{"description":"Retry configuration if this step fails","$ref":"#/components/schemas/Retry"},"debouncing":{"description":"Debounce configuration for this step (EE only)","type":"object","properties":{"debounce_delay_s":{"type":"integer","description":"Delay in seconds to debounce this step's executions across flow runs"},"debounce_key":{"type":"string","description":"Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/<flow_path>-<step_id>"},"debounce_args_to_accumulate":{"type":"array","description":"Array-type arguments to accumulate across debounced executions","items":{"type":"string"}},"max_total_debouncing_time":{"type":"integer","description":"Maximum total time in seconds before forced execution"},"max_total_debounces_amount":{"type":"integer","description":"Maximum number of debounces before forced execution"}}}},"required":["value","id"]},"InputTransform":{"description":"Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs","oneOf":[{"$ref":"#/components/schemas/StaticTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type"}},"StaticTransform":{"type":"object","description":"Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'","properties":{"value":{"description":"The static value. For resources, use format '$res:path/to/resource'"},"type":{"type":"string","enum":["static"]}},"required":["type"]},"JavascriptTransform":{"type":"object","description":"JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')","properties":{"expr":{"type":"string","description":"JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"},"type":{"type":"string","enum":["javascript"]}},"required":["expr","type"]},"AiTransform":{"type":"object","description":"Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.","properties":{"type":{"type":"string","enum":["ai"]}},"required":["type"]},"AIProviderKind":{"type":"string","description":"Supported AI provider types","enum":["openai","azure_openai","azure_foundry","anthropic","mistral","deepseek","googleai","groq","openrouter","togetherai","customai","aws_bedrock","typesafe","cloudflare"]},"ProviderConfig":{"type":"object","description":"Complete AI provider configuration with resource reference and model selection","properties":{"kind":{"$ref":"#/components/schemas/AIProviderKind"},"resource":{"type":"string","description":"Resource reference in format '$res:{resource_path}' pointing to provider credentials"},"model":{"type":"string","description":"Model identifier (e.g., 'gpt-4', 'claude-3-opus-20240229', 'gemini-pro')"},"reasoning_effort":{"type":"string","description":"Provider-native reasoning effort token (e.g. 'low', 'high', 'none') for models that support extended thinking. Optional; unset leaves the provider default."}},"required":["kind","resource","model"]},"StaticProviderTransform":{"type":"object","description":"Static provider configuration passed directly to the AI agent","properties":{"value":{"$ref":"#/components/schemas/ProviderConfig"},"type":{"type":"string","enum":["static"]}},"required":["type","value"]},"ProviderTransform":{"description":"Provider configuration - can be static (ProviderConfig), JavaScript expression, or AI-determined","oneOf":[{"$ref":"#/components/schemas/StaticProviderTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type"}},"MemoryOff":{"type":"object","description":"No conversation memory/context","properties":{"kind":{"type":"string","enum":["off"]}},"required":["kind"]},"MemoryWindow":{"type":"object","description":"Keeps the most recent messages of the memory named by the run's memory id (or the step's\n`memory_id`). Without a memory id the agent runs without memory.\n","properties":{"kind":{"type":"string","enum":["window"]},"context_length":{"type":"integer","description":"Number of most recent messages to load and store. 0 turns memory off."}},"required":["kind","context_length"]},"MemoryAuto":{"type":"object","deprecated":true,"description":"Deprecated, still read as it was written: the run's memory id, else the `memory_id` here.\nThe step's own `memory_id` is not read while this kind is set; switch the kind to `window`\nto use it. Without a `context_length`, or with 0, it is `off` and reads `previous_messages`.\n","properties":{"kind":{"type":"string","enum":["auto"]},"context_length":{"type":"integer","description":"Maximum number of messages to retain in context"},"memory_id":{"type":"string","description":"Identifier for persistent memory across agent invocations"}},"required":["kind"]},"MemoryCompaction":{"type":"object","description":"Keeps the whole memory named by the run's memory id (or the step's `memory_id`), replacing\nits older part with a summary as the conversation approaches the model's context window.\nWithout a memory id the agent runs without memory, and compaction bounds the run's own loop.\n","properties":{"kind":{"type":"string","enum":["compaction"]},"context_window":{"type":"integer","description":"Overrides the context window looked up from the model, in tokens. Only a model\nWindmill does not know needs one; those fall back to 128000.\n"}},"required":["kind"]},"MemoryMessage":{"type":"object","description":"A single message in conversation history","properties":{"role":{"type":"string","enum":["user","assistant","system"]},"content":{"type":"string"}},"required":["role","content"]},"MemoryManual":{"type":"object","deprecated":true,"description":"Deprecated, still read as it was written. Move the step to `off` with `previous_messages` instead.","properties":{"kind":{"type":"string","enum":["manual"]},"messages":{"type":"array","items":{"$ref":"#/components/schemas/MemoryMessage"}}},"required":["kind","messages"]},"MemoryConfig":{"description":"Managed memory, stored by Windmill and replayed with each request. The memory is named by a memory id, see `memory_id`. While it is off, a step can supply its history in `previous_messages`.","oneOf":[{"$ref":"#/components/schemas/MemoryOff"},{"$ref":"#/components/schemas/MemoryWindow"},{"$ref":"#/components/schemas/MemoryCompaction"},{"$ref":"#/components/schemas/MemoryAuto"},{"$ref":"#/components/schemas/MemoryManual"}],"discriminator":{"propertyName":"kind"}},"StaticMemoryTransform":{"type":"object","description":"Static memory configuration passed directly to the AI agent","properties":{"value":{"$ref":"#/components/schemas/MemoryConfig"},"type":{"type":"string","enum":["static"]}},"required":["type","value"]},"MemoryTransform":{"description":"Memory configuration - can be static (MemoryConfig), JavaScript expression, or AI-determined","oneOf":[{"$ref":"#/components/schemas/StaticMemoryTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type"}},"FlowModuleValue":{"description":"The actual implementation of a flow step. Can be a script (inline or referenced), subflow, loop, branch, or special module type","oneOf":[{"$ref":"#/components/schemas/RawScript"},{"$ref":"#/components/schemas/PathScript"},{"$ref":"#/components/schemas/PathFlow"},{"$ref":"#/components/schemas/ForloopFlow"},{"$ref":"#/components/schemas/WhileloopFlow"},{"$ref":"#/components/schemas/BranchOne"},{"$ref":"#/components/schemas/BranchAll"},{"$ref":"#/components/schemas/Identity"},{"$ref":"#/components/schemas/AiAgent"},{"$ref":"#/components/schemas/AiDecision"}],"discriminator":{"propertyName":"type"}},"RawScript":{"type":"object","description":"Inline script with code defined directly in the flow. Use 'bun' as default language if unspecified. The script receives arguments from input_transforms","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"content":{"type":"string","description":"The script source code. Should export a 'main' function"},"language":{"type":"string","description":"Programming language for this script","enum":["deno","bun","bunnative","python3","go","bash","powershell","postgresql","mysql","bigquery","snowflake","mssql","oracledb","graphql","nativets","php","rust","ansible","csharp","nu","java","ruby","rlang","duckdb"]},"path":{"type":"string","description":"Optional path for saving this script"},"lock":{"type":"string","description":"Lock file content for dependencies"},"type":{"type":"string","enum":["rawscript"]},"tag":{"type":"string","description":"Worker group tag for execution routing"},"concurrent_limit":{"type":"number","description":"Maximum concurrent executions of this script"},"concurrency_time_window_s":{"type":"number","description":"Time window for concurrent_limit"},"custom_concurrency_key":{"type":"string","description":"Custom key for grouping concurrent executions"},"is_trigger":{"type":"boolean","description":"If true, this script is a trigger that can start the flow"},"assets":{"type":"array","description":"External resources this script accesses (S3 objects, resources, etc.)","items":{"type":"object","required":["path","kind"],"properties":{"path":{"type":"string","description":"Path to the asset"},"kind":{"type":"string","description":"Type of asset","enum":["s3object","resource","ducklake","datatable","volume","dbt"]},"access_type":{"type":"string","nullable":true,"description":"Access level for this asset","enum":["r","w","rw",null]},"alt_access_type":{"type":"string","nullable":true,"description":"Alternative access level","enum":["r","w","rw",null]}}}}},"required":["type","content","language","input_transforms"]},"PathScript":{"type":"object","description":"Reference to an existing script by path. Use this when calling a previously saved script instead of writing inline code","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"path":{"type":"string","description":"Path to the script in the workspace (e.g., 'f/scripts/send_email')"},"hash":{"type":"string","description":"Optional specific version hash of the script to use"},"type":{"type":"string","enum":["script"]},"tag_override":{"type":"string","description":"Override the script's default worker group tag"},"is_trigger":{"type":"boolean","description":"If true, this script is a trigger that can start the flow"}},"required":["type","path","input_transforms"]},"PathFlow":{"type":"object","description":"Reference to an existing flow by path. Use this to call another flow as a subflow","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the subflow's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"path":{"type":"string","description":"Path to the flow in the workspace (e.g., 'f/flows/process_user')"},"type":{"type":"string","enum":["flow"]}},"required":["type","path","input_transforms"]},"ForloopFlow":{"type":"object","description":"Executes nested modules in a loop over an iterator. Inside the loop, use 'flow_input.iter.value' to access the current iteration value, and 'flow_input.iter.index' for the index. Supports parallel execution for better performance on I/O-bound operations","properties":{"modules":{"type":"array","description":"Steps to execute for each iteration. These can reference the iteration value via 'flow_input.iter.value'","items":{"$ref":"#/components/schemas/FlowModule"}},"iterator":{"description":"JavaScript expression that returns an array to iterate over. Can reference 'results.step_id' or 'flow_input'","$ref":"#/components/schemas/InputTransform"},"skip_failures":{"type":"boolean","description":"If true, iteration failures don't stop the loop. Failed iterations return null"},"type":{"type":"string","enum":["forloopflow"]},"parallel":{"type":"boolean","description":"If true, iterations run concurrently (faster for I/O-bound operations). Use with parallelism to control concurrency"},"parallelism":{"description":"Maximum number of concurrent iterations when parallel=true. Limits resource usage. Can be static number or expression","$ref":"#/components/schemas/InputTransform"},"squash":{"type":"boolean"}},"required":["modules","iterator","skip_failures","type"]},"WhileloopFlow":{"type":"object","description":"Executes nested modules repeatedly until stopped. The implicit iterator is the iteration counter, so 'flow_input.iter.value' equals 'flow_input.iter.index' (0, 1, 2, ...) and never carries state. To carry state across iterations, a step reads its own previous-iteration result via 'results.<its_own_id>' with a first-iteration fallback - the loop's stop_after_if must then be on that inner step (a plain single-step body with stop_after_if on the loop module does not resolve 'results' across iterations and never terminates); plain counters can instead be derived from 'flow_input.iter.index', which works in every configuration. stop_after_if is evaluated after each iteration - on the loop module 'result' is the last iteration's result","properties":{"modules":{"type":"array","description":"Steps to execute in each iteration","items":{"$ref":"#/components/schemas/FlowModule"}},"skip_failures":{"type":"boolean","description":"If true, iteration failures don't stop the loop. Failed iterations return null"},"type":{"type":"string","enum":["whileloopflow"]},"parallel":{"type":"boolean","description":"If true, iterations run concurrently (use with caution in while loops)"},"parallelism":{"description":"Maximum number of concurrent iterations when parallel=true","$ref":"#/components/schemas/InputTransform"},"squash":{"type":"boolean"}},"required":["modules","skip_failures","type"]},"BranchOne":{"type":"object","description":"Conditional branching where only the first matching branch executes. Branches are evaluated in order, and the first one with a true expression runs. If no branches match, the default branch executes","properties":{"branches":{"type":"array","description":"Array of branches to evaluate in order. The first branch with expr evaluating to true executes","items":{"type":"object","properties":{"summary":{"type":"string","description":"Short description of this branch condition"},"expr":{"type":"string","description":"JavaScript expression that returns boolean. Can use 'results.step_id' or 'flow_input'. First true expr wins"},"modules":{"type":"array","description":"Steps to execute if this branch's expr is true","items":{"$ref":"#/components/schemas/FlowModule"}}},"required":["modules","expr"]}},"default":{"type":"array","description":"Steps to execute if no branch expressions match","items":{"$ref":"#/components/schemas/FlowModule"}},"type":{"type":"string","enum":["branchone"]}},"required":["branches","default","type"]},"BranchAll":{"type":"object","description":"Parallel branching where all branches execute simultaneously. Unlike BranchOne, all branches run regardless of conditions. Useful for executing independent tasks concurrently","properties":{"branches":{"type":"array","description":"Array of branches that all execute (either in parallel or sequentially)","items":{"type":"object","properties":{"summary":{"type":"string","description":"Short description of this branch's purpose"},"skip_failure":{"type":"boolean","description":"If true, failure in this branch doesn't fail the entire flow"},"modules":{"type":"array","description":"Steps to execute in this branch","items":{"$ref":"#/components/schemas/FlowModule"}}},"required":["modules"]}},"type":{"type":"string","enum":["branchall"]},"parallel":{"type":"boolean","description":"If true, all branches execute concurrently. If false, they execute sequentially"}},"required":["branches","type"]},"AgentTool":{"type":"object","description":"A tool available to an AI agent. Can be a flow module or an external MCP (Model Context Protocol) tool","properties":{"id":{"type":"string","description":"Unique identifier for this tool. Cannot contain spaces - use underscores instead (e.g., 'get_user_data' not 'get user data')"},"summary":{"type":"string","description":"The name the AI agent calls this tool by, not a human label. On a flowmodule tool it must match ^[a-zA-Z0-9_]+$ - letters, numbers and underscores only (e.g. 'search_documentation', not 'Search documentation') - and always be set; on an mcp or websearch tool it is a plain label. Put the human-readable explanation in 'description'."},"description":{"type":"string","description":"Free-text description of the tool given to the AI to decide when and how to call it. Overrides the description auto-derived from the underlying script."},"job_token_scopes":{"type":"array","nullable":true,"items":{"type":"string"},"description":"Scopes the token of this tool's jobs is restricted to, on top of the agent step's own restriction: a tool can only narrow it."},"value":{"$ref":"#/components/schemas/ToolValue"}},"required":["id","value"]},"ToolValue":{"description":"The implementation of a tool. Can be a flow module (script/flow) or an MCP tool reference","oneOf":[{"$ref":"#/components/schemas/FlowModuleTool"},{"$ref":"#/components/schemas/McpToolValue"},{"$ref":"#/components/schemas/WebsearchToolValue"}]},"FlowModuleTool":{"description":"A tool implemented as a flow module (script, flow, etc.). The AI can call this like any other flow module","allOf":[{"type":"object","properties":{"tool_type":{"type":"string","enum":["flowmodule"]}},"required":["tool_type"]},{"$ref":"#/components/schemas/FlowModuleValue"}]},"WebsearchToolValue":{"type":"object","description":"A tool implemented as a websearch tool. The AI can call this like any other websearch tool","properties":{"tool_type":{"type":"string","enum":["websearch"]}},"required":["tool_type"]},"McpToolValue":{"type":"object","description":"Reference to an external MCP (Model Context Protocol) tool. The AI can call tools from MCP servers","properties":{"tool_type":{"type":"string","enum":["mcp"]},"resource_path":{"type":"string","description":"Path to the MCP resource/server configuration"},"include_tools":{"type":"array","description":"Whitelist of specific tools to include from this MCP server","items":{"type":"string"}},"exclude_tools":{"type":"array","description":"Blacklist of tools to exclude from this MCP server","items":{"type":"string"}}},"required":["tool_type","resource_path"]},"AiAgent":{"type":"object","description":"AI agent step that can use tools to accomplish tasks. The agent receives inputs and can call any of its configured tools to complete the task","properties":{"input_transforms":{"type":"object","description":"Input parameters for the AI agent mapped to their values","properties":{"provider":{"$ref":"#/components/schemas/ProviderTransform"},"output_type":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Output format type.\nValid values: 'text' (default) - plain text response, 'image' - image generation\n"},"user_message":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"The user's prompt/message to the AI agent. Supports variable interpolation with\nflow.input syntax. Required unless memory is off and `previous_messages` supplies\nthe prompt; image output always needs it.\n"},"system_prompt":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"System instructions that guide the AI's behavior, persona, and response style. Optional."},"streaming":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Boolean. If true, stream the AI response incrementally.\nStreaming events include: token_delta, reasoning_token_delta, tool_call, tool_call_arguments, tool_execution, tool_result\n"},"memory":{"$ref":"#/components/schemas/MemoryTransform"},"memory_id":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"String. Names the memory this step reads and writes, overriding the memory id the run\nwas started with (the chat conversation, an app chat session or the `memory_id` run\nparameter). Leave unset to use the run's memory id. A fixed value shares one memory\nacross every run; an expression such as `flow_input.customer_id` keeps one memory per\nkey. When it evaluates to an empty value the agent runs without memory. Read only\nwhile `memory` is `window` or `compaction`: it is ignored when memory is off, and an\nolder `auto` or `manual` memory reads neither history input.\n"},"previous_messages":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Array of MemoryMessage. History supplied by the flow, sent between the system prompt\nand the user message. Read only while `memory` is off or absent: managed memory\nignores it, and an older `auto` or `manual` memory reads neither history input.\n"},"output_schema":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"JSON Schema object defining structured output format. Used when you need the AI to return data in a specific shape.\nSupports standard JSON Schema properties: type, properties, required, items, enum, pattern, minLength, maxLength, minimum, maximum, etc.\nExample: { type: 'object', properties: { name: { type: 'string' }, age: { type: 'integer' } }, required: ['name'] }\n"},"user_attachments":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Array of file references (images or PDFs) for the AI agent.\nFormat: Array<{ bucket: string, key: string }> - S3 object references\nExample: [{ bucket: 'my-bucket', key: 'documents/report.pdf' }]\n"},"enabled_tools":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Array of strings naming which of the tools configured in `tools` the agent may call\nthis run. Leaving it unset carries every one of them; an empty array carries none.\nA tool is named as the model is shown it. An entry the model is shown nothing of is\nnamed by what identifies it instead: an MCP server by its resource path, carrying\nevery tool it exposes (which of them stays that entry's include_tools/exclude_tools),\nand a websearch entry by the reserved name '__wm_web_search', whatever summary it carries\n(no tool may take that name).\nExample: ['get_user', 'u/admin/github_mcp', '__wm_web_search']\n"},"max_completion_tokens":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Integer. Maximum number of tokens the AI will generate in its response.\nRange: 1 to 4,294,967,295. Typical values: 256-4096 for most use cases.\n"},"temperature":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Float. Controls randomness/creativity of responses.\nRange: 0.0 to 2.0 (provider-dependent)\n- 0.0 = deterministic, focused responses\n- 0.7 = balanced (common default)\n- 1.0+ = more creative/random\n"},"max_iterations":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Number. Limits how many times the agent can loop through reasoning and tool use.\nRange: 1-1000.\n"}}},"tools":{"type":"array","description":"Array of tools the agent can use. The agent decides which tools to call based on the task","items":{"$ref":"#/components/schemas/AgentTool"}},"type":{"type":"string","enum":["aiagent"]},"tag":{"type":"string","description":"Worker group tag for execution routing. If not set, the AI agent step runs on the flow's tag (default `flow`)"},"omit_output_from_conversation":{"type":"boolean","default":false,"description":"If true, this AI agent step does not persist its assistant or tool messages to the flow conversation when chat mode is enabled."},"agent":{"type":"string","description":"Path of a reusable `ai_agent` resource (hybrid linking). When set, the agent brain\nconfig (provider/model/system prompt/etc.) and tool set are resolved at runtime from\nthat resource; the module's input_transforms then only carry the flow-local inputs\n(user_message, user_attachments, enabled_tools and the history inputs memory_id and previous_messages).\n"},"tool_inputs":{"type":"object","description":"Host-local wiring for an agent's tool inputs, keyed by tool id then input key. Binds the\nreferenced agent's tools to this flow's context (flow_input/results) without mutating the\nshared resource; overlaid onto the tools' input_transforms at runtime — including when\n`agent` is unset, since a step forked for editing keeps these overrides until it is saved\nback or unlinked.\n","additionalProperties":{"type":"object","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}}},"parallel":{"type":"boolean","description":"If true, the agent can execute multiple tool calls in parallel"}},"required":["type","input_transforms"]},"AiDecision":{"type":"object","description":"AI decision step: one call to a decision model (TypeSafe's Jev, Cloudflare's\nJev-compatible Clef, or OpenAI's Decisions API) that answers typed questions about a\nstate with calibrated probabilities, instead of generating text.\nPrefer it over an AI agent to classify, route, score or check something: it is fast,\ncheap and its answers are structured. Its result is { output: { <question name>: answer },\nmodel, usage }, so a later step reads e.g. results.<id>.output.intent.choice. To route on\nthe answers, follow it with a branchone whose branch exprs read\nresults.<id>.output.<question>.choice. Usable as an AI agent tool, where the calling agent\nsupplies the state.\n","properties":{"input_transforms":{"type":"object","description":"Input parameters for the decision mapped to their values","properties":{"provider":{"$ref":"#/components/schemas/ProviderTransform"},"state":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"What the questions are asked about: a string, an object or an array of strings.\nAn object with descriptive keys holding only what the questions need works best.\nExample: { message: flow_input.message, plan: results.a.plan }\n"},"questions":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Object mapping each question name to { type, instructions, criteria }, where type is:\n- 'choice': criteria maps each option to its description (up to 255); the answer\n has choice, probabilities and confidence\n- 'score': criteria is an ordered array of 2 to 10 level descriptions; the answer\n has score, legend, probabilities and confidence\n- 'noul': yes/no, criteria optionally { true, false } descriptions; the answer has\n noul, the probability of yes (0 to 1)\nExample: { intent: { type: 'choice', instructions: 'What does the customer want?',\ncriteria: { refund: 'Money back', bug: 'Something is broken' } } }\n"}},"required":["provider","state","questions"]},"type":{"type":"string","enum":["aidecision"]},"tag":{"type":"string","description":"Worker group tag for execution routing. If not set, the step runs on the flow's tag (default `flow`)"}},"required":["type","input_transforms"]},"Identity":{"type":"object","description":"Pass-through module that returns its input unchanged. Useful for flow structure or as a placeholder","properties":{"type":{"type":"string","enum":["identity"]},"flow":{"type":"boolean","description":"If true, marks this as a flow identity (special handling)"}},"required":["type"]},"FlowStatus":{"type":"object","properties":{"step":{"type":"integer"},"modules":{"type":"array","items":{"$ref":"#/components/schemas/FlowStatusModule"}},"user_states":{"additionalProperties":true},"preprocessor_module":{"allOf":[{"$ref":"#/components/schemas/FlowStatusModule"}]},"failure_module":{"allOf":[{"$ref":"#/components/schemas/FlowStatusModule"},{"type":"object","properties":{"parent_module":{"type":"string"}}}]},"retry":{"type":"object","properties":{"fail_count":{"type":"integer"},"failed_jobs":{"type":"array","items":{"type":"string","format":"uuid"}}}}},"required":["step","modules","failure_module"]},"FlowStatusModule":{"type":"object","properties":{"type":{"type":"string","enum":["WaitingForPriorSteps","WaitingForEvents","WaitingForExecutor","InProgress","Success","Failure"]},"id":{"type":"string"},"job":{"type":"string","format":"uuid"},"count":{"type":"integer"},"progress":{"type":"integer"},"iterator":{"type":"object","properties":{"index":{"type":"integer"},"itered":{"type":"array","items":{}},"itered_len":{"type":"integer"},"args":{}}},"flow_jobs":{"type":"array","items":{"type":"string"}},"flow_jobs_success":{"type":"array","items":{"type":"boolean"}},"flow_jobs_duration":{"type":"object","properties":{"started_at":{"type":"array","items":{"type":"string"}},"duration_ms":{"type":"array","items":{"type":"integer"}}}},"branch_chosen":{"type":"object","properties":{"type":{"type":"string","enum":["branch","default"]},"branch":{"type":"integer"}},"required":["type"]},"branchall":{"type":"object","properties":{"branch":{"type":"integer"},"len":{"type":"integer"}},"required":["branch","len"]},"approvers":{"type":"array","items":{"type":"object","properties":{"resume_id":{"type":"integer"},"approver":{"type":"string"}},"required":["resume_id","approver"]}},"failed_retries":{"type":"array","items":{"type":"string","format":"uuid"}},"skipped":{"type":"boolean"},"agent_actions":{"type":"array","items":{"type":"object","oneOf":[{"type":"object","properties":{"job_id":{"type":"string","format":"uuid"},"function_name":{"type":"string"},"type":{"type":"string","enum":["tool_call"]},"module_id":{"type":"string"}},"required":["job_id","function_name","type","module_id"]},{"type":"object","properties":{"call_id":{"type":"string","format":"uuid"},"function_name":{"type":"string"},"resource_path":{"type":"string"},"type":{"type":"string","enum":["mcp_tool_call"]},"arguments":{"type":"object"}},"required":["call_id","function_name","resource_path","type"]},{"type":"object","properties":{"type":{"type":"string","enum":["web_search"]}},"required":["type"]},{"type":"object","properties":{"type":{"type":"string","enum":["message"]}},"required":["content","type"]}]}},"agent_actions_success":{"type":"array","items":{"type":"boolean"}}},"required":["type"]}}}} \ No newline at end of file diff --git a/frontend/src/lib/components/copilot/chat/flow/openFlowZod.gen.ts b/frontend/src/lib/components/copilot/chat/flow/openFlowZod.gen.ts index 88cb8fe875..d83ef70207 100644 --- a/frontend/src/lib/components/copilot/chat/flow/openFlowZod.gen.ts +++ b/frontend/src/lib/components/copilot/chat/flow/openFlowZod.gen.ts @@ -1,6 +1,6 @@ import { z } from "zod" -export const flowModuleValueSchema = z.discriminatedUnion("type", [z.object({ "input_transforms": z.record(z.string(), z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs")).describe("Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments"), "content": z.string().describe("The script source code. Should export a 'main' function"), "language": z.enum(["deno","bun","bunnative","python3","go","bash","powershell","postgresql","mysql","bigquery","snowflake","mssql","oracledb","graphql","nativets","php","rust","ansible","csharp","nu","java","ruby","rlang","duckdb"]).describe("Programming language for this script"), "path": z.string().describe("Optional path for saving this script").optional(), "lock": z.string().describe("Lock file content for dependencies").optional(), "type": z.literal("rawscript"), "tag": z.string().describe("Worker group tag for execution routing").optional(), "concurrent_limit": z.number().describe("Maximum concurrent executions of this script").optional(), "concurrency_time_window_s": z.number().describe("Time window for concurrent_limit").optional(), "custom_concurrency_key": z.string().describe("Custom key for grouping concurrent executions").optional(), "is_trigger": z.boolean().describe("If true, this script is a trigger that can start the flow").optional(), "assets": z.array(z.object({ "path": z.string().describe("Path to the asset"), "kind": z.enum(["s3object","resource","ducklake","datatable","volume","dbt"]).describe("Type of asset"), "access_type": z.union([z.literal("r"), z.literal("w"), z.literal("rw"), z.literal(null)]).nullable().describe("Access level for this asset").optional(), "alt_access_type": z.union([z.literal("r"), z.literal("w"), z.literal("rw"), z.literal(null)]).nullable().describe("Alternative access level").optional() })).describe("External resources this script accesses (S3 objects, resources, etc.)").optional() }).describe("Inline script with code defined directly in the flow. Use 'bun' as default language if unspecified. The script receives arguments from input_transforms"), z.object({ "input_transforms": z.record(z.string(), z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs")).describe("Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments"), "path": z.string().describe("Path to the script in the workspace (e.g., 'f/scripts/send_email')"), "hash": z.string().describe("Optional specific version hash of the script to use").optional(), "type": z.literal("script"), "tag_override": z.string().describe("Override the script's default worker group tag").optional(), "is_trigger": z.boolean().describe("If true, this script is a trigger that can start the flow").optional() }).describe("Reference to an existing script by path. Use this when calling a previously saved script instead of writing inline code"), z.object({ "input_transforms": z.record(z.string(), z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs")).describe("Map of parameter names to their values (static or JavaScript expressions). These become the subflow's input arguments"), "path": z.string().describe("Path to the flow in the workspace (e.g., 'f/flows/process_user')"), "type": z.literal("flow") }).describe("Reference to an existing flow by path. Use this to call another flow as a subflow"), z.object({ "modules": z.array(z.object({ "id": z.string().describe("Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"), "value": z.lazy(() => flowModuleValueSchema), "stop_after_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised.").optional(), "error_include_result": z.boolean().describe("When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false.").optional() }).describe("Early termination condition for a module").optional(), "stop_after_all_iters_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised.").optional(), "error_include_result": z.boolean().describe("When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false.").optional() }).describe("Early termination condition for a module").optional(), "skip_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.<step_id>'") }).describe("Conditionally skip this step based on previous results or flow inputs").optional(), "sleep": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "cache_ttl": z.number().describe("Cache duration in seconds for this step's results").optional(), "cache_ignore_s3_path": z.boolean().optional(), "timeout": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "delete_after_secs": z.number().int().describe("If set, delete the step's args, result and logs after this many seconds following job completion").optional(), "summary": z.string().describe("Short description of what this step does").optional(), "mock": z.object({ "enabled": z.boolean().describe("If true, return mock value instead of executing").optional(), "return_value": z.any().describe("Value to return when mocked").optional() }).describe("Mock configuration for testing without executing the actual step").optional(), "suspend": z.object({ "required_events": z.number().int().describe("Number of approvals required before continuing").optional(), "timeout": z.number().int().describe("Timeout in seconds before auto-continuing or canceling").optional(), "resume_form": z.object({ "schema": z.record(z.string(), z.any()).describe("JSON Schema for the resume form").optional() }).describe("Form schema for collecting input when resuming").optional(), "user_auth_required": z.boolean().describe("If true, only authenticated users can approve").optional(), "user_groups_required": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "self_approval_disabled": z.boolean().describe("If true, the user who started the flow cannot approve").optional(), "hide_cancel": z.boolean().describe("If true, hide the cancel button on the approval form").optional(), "continue_on_disapprove_timeout": z.boolean().describe("If true, continue flow on timeout instead of canceling").optional(), "skin": z.enum(["detailed","minimal"]).describe("How the approval request is presented, on the approval page and in Slack/Teams approval messages. 'detailed' (used when unset) shows the flow details (arguments, graph, approvers); 'minimal' shows only the request: the step description, form and approve/reject actions").optional() }).describe("Configuration for approval/resume steps that wait for user input").optional(), "priority": z.number().describe("Execution priority for this step (higher numbers run first)").optional(), "continue_on_error": z.boolean().describe("If true, flow continues even if this step fails").optional(), "job_token_scopes": z.array(z.string()).nullable().describe("Scopes the token of this step's jobs is restricted to (domain:action[:resource], e.g. oidc:write), on top of the flow's own restriction: a step can only narrow it. Applies to everything the step runs (loop and branch bodies, AI agent tools).").optional(), "retry": z.object({ "constant": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "seconds": z.number().int().describe("Seconds to wait between retries").optional() }).describe("Retry with constant delay between attempts").optional(), "exponential": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "multiplier": z.number().int().describe("Multiplier for exponential backoff").optional(), "seconds": z.number().int().gte(1).describe("Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too").optional(), "random_factor": z.number().int().gte(0).lte(100).describe("Random jitter percentage (0-100) to avoid thundering herd").optional() }).describe("Retry with exponential backoff: the n-th retry waits multiplier × seconds^n").optional(), "retry_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables") }).describe("Conditional retry based on error or result").optional() }).describe("Retry configuration for failed module executions").optional(), "debouncing": z.object({ "debounce_delay_s": z.number().int().describe("Delay in seconds to debounce this step's executions across flow runs").optional(), "debounce_key": z.string().describe("Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/<flow_path>-<step_id>").optional(), "debounce_args_to_accumulate": z.array(z.string()).describe("Array-type arguments to accumulate across debounced executions").optional(), "max_total_debouncing_time": z.number().int().describe("Maximum total time in seconds before forced execution").optional(), "max_total_debounces_amount": z.number().int().describe("Maximum number of debounces before forced execution").optional() }).describe("Debounce configuration for this step (EE only)").optional() }).describe("A single step in a flow. Can be a script, subflow, loop, or branch")).describe("Steps to execute for each iteration. These can reference the iteration value via 'flow_input.iter.value'"), "iterator": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs"), "skip_failures": z.boolean().describe("If true, iteration failures don't stop the loop. Failed iterations return null"), "type": z.literal("forloopflow"), "parallel": z.boolean().describe("If true, iterations run concurrently (faster for I/O-bound operations). Use with parallelism to control concurrency").optional(), "parallelism": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "squash": z.boolean().optional() }).describe("Executes nested modules in a loop over an iterator. Inside the loop, use 'flow_input.iter.value' to access the current iteration value, and 'flow_input.iter.index' for the index. Supports parallel execution for better performance on I/O-bound operations"), z.object({ "modules": z.array(z.object({ "id": z.string().describe("Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"), "value": z.lazy(() => flowModuleValueSchema), "stop_after_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised.").optional(), "error_include_result": z.boolean().describe("When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false.").optional() }).describe("Early termination condition for a module").optional(), "stop_after_all_iters_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised.").optional(), "error_include_result": z.boolean().describe("When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false.").optional() }).describe("Early termination condition for a module").optional(), "skip_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.<step_id>'") }).describe("Conditionally skip this step based on previous results or flow inputs").optional(), "sleep": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "cache_ttl": z.number().describe("Cache duration in seconds for this step's results").optional(), "cache_ignore_s3_path": z.boolean().optional(), "timeout": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "delete_after_secs": z.number().int().describe("If set, delete the step's args, result and logs after this many seconds following job completion").optional(), "summary": z.string().describe("Short description of what this step does").optional(), "mock": z.object({ "enabled": z.boolean().describe("If true, return mock value instead of executing").optional(), "return_value": z.any().describe("Value to return when mocked").optional() }).describe("Mock configuration for testing without executing the actual step").optional(), "suspend": z.object({ "required_events": z.number().int().describe("Number of approvals required before continuing").optional(), "timeout": z.number().int().describe("Timeout in seconds before auto-continuing or canceling").optional(), "resume_form": z.object({ "schema": z.record(z.string(), z.any()).describe("JSON Schema for the resume form").optional() }).describe("Form schema for collecting input when resuming").optional(), "user_auth_required": z.boolean().describe("If true, only authenticated users can approve").optional(), "user_groups_required": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "self_approval_disabled": z.boolean().describe("If true, the user who started the flow cannot approve").optional(), "hide_cancel": z.boolean().describe("If true, hide the cancel button on the approval form").optional(), "continue_on_disapprove_timeout": z.boolean().describe("If true, continue flow on timeout instead of canceling").optional(), "skin": z.enum(["detailed","minimal"]).describe("How the approval request is presented, on the approval page and in Slack/Teams approval messages. 'detailed' (used when unset) shows the flow details (arguments, graph, approvers); 'minimal' shows only the request: the step description, form and approve/reject actions").optional() }).describe("Configuration for approval/resume steps that wait for user input").optional(), "priority": z.number().describe("Execution priority for this step (higher numbers run first)").optional(), "continue_on_error": z.boolean().describe("If true, flow continues even if this step fails").optional(), "job_token_scopes": z.array(z.string()).nullable().describe("Scopes the token of this step's jobs is restricted to (domain:action[:resource], e.g. oidc:write), on top of the flow's own restriction: a step can only narrow it. Applies to everything the step runs (loop and branch bodies, AI agent tools).").optional(), "retry": z.object({ "constant": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "seconds": z.number().int().describe("Seconds to wait between retries").optional() }).describe("Retry with constant delay between attempts").optional(), "exponential": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "multiplier": z.number().int().describe("Multiplier for exponential backoff").optional(), "seconds": z.number().int().gte(1).describe("Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too").optional(), "random_factor": z.number().int().gte(0).lte(100).describe("Random jitter percentage (0-100) to avoid thundering herd").optional() }).describe("Retry with exponential backoff: the n-th retry waits multiplier × seconds^n").optional(), "retry_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables") }).describe("Conditional retry based on error or result").optional() }).describe("Retry configuration for failed module executions").optional(), "debouncing": z.object({ "debounce_delay_s": z.number().int().describe("Delay in seconds to debounce this step's executions across flow runs").optional(), "debounce_key": z.string().describe("Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/<flow_path>-<step_id>").optional(), "debounce_args_to_accumulate": z.array(z.string()).describe("Array-type arguments to accumulate across debounced executions").optional(), "max_total_debouncing_time": z.number().int().describe("Maximum total time in seconds before forced execution").optional(), "max_total_debounces_amount": z.number().int().describe("Maximum number of debounces before forced execution").optional() }).describe("Debounce configuration for this step (EE only)").optional() }).describe("A single step in a flow. Can be a script, subflow, loop, or branch")).describe("Steps to execute in each iteration"), "skip_failures": z.boolean().describe("If true, iteration failures don't stop the loop. Failed iterations return null"), "type": z.literal("whileloopflow"), "parallel": z.boolean().describe("If true, iterations run concurrently (use with caution in while loops)").optional(), "parallelism": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "squash": z.boolean().optional() }).describe("Executes nested modules repeatedly until stopped. The implicit iterator is the iteration counter, so 'flow_input.iter.value' equals 'flow_input.iter.index' (0, 1, 2, ...) and never carries state. To carry state across iterations, a step reads its own previous-iteration result via 'results.<its_own_id>' with a first-iteration fallback - the loop's stop_after_if must then be on that inner step (a plain single-step body with stop_after_if on the loop module does not resolve 'results' across iterations and never terminates); plain counters can instead be derived from 'flow_input.iter.index', which works in every configuration. stop_after_if is evaluated after each iteration - on the loop module 'result' is the last iteration's result"), z.object({ "branches": z.array(z.object({ "summary": z.string().describe("Short description of this branch condition").optional(), "expr": z.string().describe("JavaScript expression that returns boolean. Can use 'results.step_id' or 'flow_input'. First true expr wins"), "modules": z.array(z.object({ "id": z.string().describe("Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"), "value": z.lazy(() => flowModuleValueSchema), "stop_after_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised.").optional(), "error_include_result": z.boolean().describe("When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false.").optional() }).describe("Early termination condition for a module").optional(), "stop_after_all_iters_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised.").optional(), "error_include_result": z.boolean().describe("When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false.").optional() }).describe("Early termination condition for a module").optional(), "skip_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.<step_id>'") }).describe("Conditionally skip this step based on previous results or flow inputs").optional(), "sleep": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "cache_ttl": z.number().describe("Cache duration in seconds for this step's results").optional(), "cache_ignore_s3_path": z.boolean().optional(), "timeout": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "delete_after_secs": z.number().int().describe("If set, delete the step's args, result and logs after this many seconds following job completion").optional(), "summary": z.string().describe("Short description of what this step does").optional(), "mock": z.object({ "enabled": z.boolean().describe("If true, return mock value instead of executing").optional(), "return_value": z.any().describe("Value to return when mocked").optional() }).describe("Mock configuration for testing without executing the actual step").optional(), "suspend": z.object({ "required_events": z.number().int().describe("Number of approvals required before continuing").optional(), "timeout": z.number().int().describe("Timeout in seconds before auto-continuing or canceling").optional(), "resume_form": z.object({ "schema": z.record(z.string(), z.any()).describe("JSON Schema for the resume form").optional() }).describe("Form schema for collecting input when resuming").optional(), "user_auth_required": z.boolean().describe("If true, only authenticated users can approve").optional(), "user_groups_required": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "self_approval_disabled": z.boolean().describe("If true, the user who started the flow cannot approve").optional(), "hide_cancel": z.boolean().describe("If true, hide the cancel button on the approval form").optional(), "continue_on_disapprove_timeout": z.boolean().describe("If true, continue flow on timeout instead of canceling").optional(), "skin": z.enum(["detailed","minimal"]).describe("How the approval request is presented, on the approval page and in Slack/Teams approval messages. 'detailed' (used when unset) shows the flow details (arguments, graph, approvers); 'minimal' shows only the request: the step description, form and approve/reject actions").optional() }).describe("Configuration for approval/resume steps that wait for user input").optional(), "priority": z.number().describe("Execution priority for this step (higher numbers run first)").optional(), "continue_on_error": z.boolean().describe("If true, flow continues even if this step fails").optional(), "job_token_scopes": z.array(z.string()).nullable().describe("Scopes the token of this step's jobs is restricted to (domain:action[:resource], e.g. oidc:write), on top of the flow's own restriction: a step can only narrow it. Applies to everything the step runs (loop and branch bodies, AI agent tools).").optional(), "retry": z.object({ "constant": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "seconds": z.number().int().describe("Seconds to wait between retries").optional() }).describe("Retry with constant delay between attempts").optional(), "exponential": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "multiplier": z.number().int().describe("Multiplier for exponential backoff").optional(), "seconds": z.number().int().gte(1).describe("Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too").optional(), "random_factor": z.number().int().gte(0).lte(100).describe("Random jitter percentage (0-100) to avoid thundering herd").optional() }).describe("Retry with exponential backoff: the n-th retry waits multiplier × seconds^n").optional(), "retry_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables") }).describe("Conditional retry based on error or result").optional() }).describe("Retry configuration for failed module executions").optional(), "debouncing": z.object({ "debounce_delay_s": z.number().int().describe("Delay in seconds to debounce this step's executions across flow runs").optional(), "debounce_key": z.string().describe("Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/<flow_path>-<step_id>").optional(), "debounce_args_to_accumulate": z.array(z.string()).describe("Array-type arguments to accumulate across debounced executions").optional(), "max_total_debouncing_time": z.number().int().describe("Maximum total time in seconds before forced execution").optional(), "max_total_debounces_amount": z.number().int().describe("Maximum number of debounces before forced execution").optional() }).describe("Debounce configuration for this step (EE only)").optional() }).describe("A single step in a flow. Can be a script, subflow, loop, or branch")).describe("Steps to execute if this branch's expr is true") })).describe("Array of branches to evaluate in order. The first branch with expr evaluating to true executes"), "default": z.array(z.object({ "id": z.string().describe("Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"), "value": z.lazy(() => flowModuleValueSchema), "stop_after_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised.").optional(), "error_include_result": z.boolean().describe("When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false.").optional() }).describe("Early termination condition for a module").optional(), "stop_after_all_iters_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised.").optional(), "error_include_result": z.boolean().describe("When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false.").optional() }).describe("Early termination condition for a module").optional(), "skip_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.<step_id>'") }).describe("Conditionally skip this step based on previous results or flow inputs").optional(), "sleep": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "cache_ttl": z.number().describe("Cache duration in seconds for this step's results").optional(), "cache_ignore_s3_path": z.boolean().optional(), "timeout": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "delete_after_secs": z.number().int().describe("If set, delete the step's args, result and logs after this many seconds following job completion").optional(), "summary": z.string().describe("Short description of what this step does").optional(), "mock": z.object({ "enabled": z.boolean().describe("If true, return mock value instead of executing").optional(), "return_value": z.any().describe("Value to return when mocked").optional() }).describe("Mock configuration for testing without executing the actual step").optional(), "suspend": z.object({ "required_events": z.number().int().describe("Number of approvals required before continuing").optional(), "timeout": z.number().int().describe("Timeout in seconds before auto-continuing or canceling").optional(), "resume_form": z.object({ "schema": z.record(z.string(), z.any()).describe("JSON Schema for the resume form").optional() }).describe("Form schema for collecting input when resuming").optional(), "user_auth_required": z.boolean().describe("If true, only authenticated users can approve").optional(), "user_groups_required": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "self_approval_disabled": z.boolean().describe("If true, the user who started the flow cannot approve").optional(), "hide_cancel": z.boolean().describe("If true, hide the cancel button on the approval form").optional(), "continue_on_disapprove_timeout": z.boolean().describe("If true, continue flow on timeout instead of canceling").optional(), "skin": z.enum(["detailed","minimal"]).describe("How the approval request is presented, on the approval page and in Slack/Teams approval messages. 'detailed' (used when unset) shows the flow details (arguments, graph, approvers); 'minimal' shows only the request: the step description, form and approve/reject actions").optional() }).describe("Configuration for approval/resume steps that wait for user input").optional(), "priority": z.number().describe("Execution priority for this step (higher numbers run first)").optional(), "continue_on_error": z.boolean().describe("If true, flow continues even if this step fails").optional(), "job_token_scopes": z.array(z.string()).nullable().describe("Scopes the token of this step's jobs is restricted to (domain:action[:resource], e.g. oidc:write), on top of the flow's own restriction: a step can only narrow it. Applies to everything the step runs (loop and branch bodies, AI agent tools).").optional(), "retry": z.object({ "constant": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "seconds": z.number().int().describe("Seconds to wait between retries").optional() }).describe("Retry with constant delay between attempts").optional(), "exponential": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "multiplier": z.number().int().describe("Multiplier for exponential backoff").optional(), "seconds": z.number().int().gte(1).describe("Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too").optional(), "random_factor": z.number().int().gte(0).lte(100).describe("Random jitter percentage (0-100) to avoid thundering herd").optional() }).describe("Retry with exponential backoff: the n-th retry waits multiplier × seconds^n").optional(), "retry_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables") }).describe("Conditional retry based on error or result").optional() }).describe("Retry configuration for failed module executions").optional(), "debouncing": z.object({ "debounce_delay_s": z.number().int().describe("Delay in seconds to debounce this step's executions across flow runs").optional(), "debounce_key": z.string().describe("Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/<flow_path>-<step_id>").optional(), "debounce_args_to_accumulate": z.array(z.string()).describe("Array-type arguments to accumulate across debounced executions").optional(), "max_total_debouncing_time": z.number().int().describe("Maximum total time in seconds before forced execution").optional(), "max_total_debounces_amount": z.number().int().describe("Maximum number of debounces before forced execution").optional() }).describe("Debounce configuration for this step (EE only)").optional() }).describe("A single step in a flow. Can be a script, subflow, loop, or branch")).describe("Steps to execute if no branch expressions match"), "type": z.literal("branchone") }).describe("Conditional branching where only the first matching branch executes. Branches are evaluated in order, and the first one with a true expression runs. If no branches match, the default branch executes"), z.object({ "branches": z.array(z.object({ "summary": z.string().describe("Short description of this branch's purpose").optional(), "skip_failure": z.boolean().describe("If true, failure in this branch doesn't fail the entire flow").optional(), "modules": z.array(z.object({ "id": z.string().describe("Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"), "value": z.lazy(() => flowModuleValueSchema), "stop_after_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised.").optional(), "error_include_result": z.boolean().describe("When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false.").optional() }).describe("Early termination condition for a module").optional(), "stop_after_all_iters_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised.").optional(), "error_include_result": z.boolean().describe("When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false.").optional() }).describe("Early termination condition for a module").optional(), "skip_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.<step_id>'") }).describe("Conditionally skip this step based on previous results or flow inputs").optional(), "sleep": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "cache_ttl": z.number().describe("Cache duration in seconds for this step's results").optional(), "cache_ignore_s3_path": z.boolean().optional(), "timeout": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "delete_after_secs": z.number().int().describe("If set, delete the step's args, result and logs after this many seconds following job completion").optional(), "summary": z.string().describe("Short description of what this step does").optional(), "mock": z.object({ "enabled": z.boolean().describe("If true, return mock value instead of executing").optional(), "return_value": z.any().describe("Value to return when mocked").optional() }).describe("Mock configuration for testing without executing the actual step").optional(), "suspend": z.object({ "required_events": z.number().int().describe("Number of approvals required before continuing").optional(), "timeout": z.number().int().describe("Timeout in seconds before auto-continuing or canceling").optional(), "resume_form": z.object({ "schema": z.record(z.string(), z.any()).describe("JSON Schema for the resume form").optional() }).describe("Form schema for collecting input when resuming").optional(), "user_auth_required": z.boolean().describe("If true, only authenticated users can approve").optional(), "user_groups_required": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "self_approval_disabled": z.boolean().describe("If true, the user who started the flow cannot approve").optional(), "hide_cancel": z.boolean().describe("If true, hide the cancel button on the approval form").optional(), "continue_on_disapprove_timeout": z.boolean().describe("If true, continue flow on timeout instead of canceling").optional(), "skin": z.enum(["detailed","minimal"]).describe("How the approval request is presented, on the approval page and in Slack/Teams approval messages. 'detailed' (used when unset) shows the flow details (arguments, graph, approvers); 'minimal' shows only the request: the step description, form and approve/reject actions").optional() }).describe("Configuration for approval/resume steps that wait for user input").optional(), "priority": z.number().describe("Execution priority for this step (higher numbers run first)").optional(), "continue_on_error": z.boolean().describe("If true, flow continues even if this step fails").optional(), "job_token_scopes": z.array(z.string()).nullable().describe("Scopes the token of this step's jobs is restricted to (domain:action[:resource], e.g. oidc:write), on top of the flow's own restriction: a step can only narrow it. Applies to everything the step runs (loop and branch bodies, AI agent tools).").optional(), "retry": z.object({ "constant": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "seconds": z.number().int().describe("Seconds to wait between retries").optional() }).describe("Retry with constant delay between attempts").optional(), "exponential": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "multiplier": z.number().int().describe("Multiplier for exponential backoff").optional(), "seconds": z.number().int().gte(1).describe("Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too").optional(), "random_factor": z.number().int().gte(0).lte(100).describe("Random jitter percentage (0-100) to avoid thundering herd").optional() }).describe("Retry with exponential backoff: the n-th retry waits multiplier × seconds^n").optional(), "retry_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables") }).describe("Conditional retry based on error or result").optional() }).describe("Retry configuration for failed module executions").optional(), "debouncing": z.object({ "debounce_delay_s": z.number().int().describe("Delay in seconds to debounce this step's executions across flow runs").optional(), "debounce_key": z.string().describe("Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/<flow_path>-<step_id>").optional(), "debounce_args_to_accumulate": z.array(z.string()).describe("Array-type arguments to accumulate across debounced executions").optional(), "max_total_debouncing_time": z.number().int().describe("Maximum total time in seconds before forced execution").optional(), "max_total_debounces_amount": z.number().int().describe("Maximum number of debounces before forced execution").optional() }).describe("Debounce configuration for this step (EE only)").optional() }).describe("A single step in a flow. Can be a script, subflow, loop, or branch")).describe("Steps to execute in this branch") })).describe("Array of branches that all execute (either in parallel or sequentially)"), "type": z.literal("branchall"), "parallel": z.boolean().describe("If true, all branches execute concurrently. If false, they execute sequentially").optional() }).describe("Parallel branching where all branches execute simultaneously. Unlike BranchOne, all branches run regardless of conditions. Useful for executing independent tasks concurrently"), z.object({ "type": z.literal("identity"), "flow": z.boolean().describe("If true, marks this as a flow identity (special handling)").optional() }).describe("Pass-through module that returns its input unchanged. Useful for flow structure or as a placeholder"), z.object({ "input_transforms": z.object({ "provider": z.discriminatedUnion("type", [z.object({ "value": z.object({ "kind": z.enum(["openai","azure_openai","azure_foundry","anthropic","mistral","deepseek","googleai","groq","openrouter","togetherai","customai","aws_bedrock","typesafe","cloudflare"]).describe("Supported AI provider types"), "resource": z.string().describe("Resource reference in format '$res:{resource_path}' pointing to provider credentials"), "model": z.string().describe("Model identifier (e.g., 'gpt-4', 'claude-3-opus-20240229', 'gemini-pro')"), "reasoning_effort": z.string().describe("Provider-native reasoning effort token (e.g. 'low', 'high', 'none') for models that support extended thinking. Optional; unset leaves the provider default.").optional() }).describe("Complete AI provider configuration with resource reference and model selection"), "type": z.literal("static") }).describe("Static provider configuration passed directly to the AI agent"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Provider configuration - can be static (ProviderConfig), JavaScript expression, or AI-determined").optional(), "output_type": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Output format type.\nValid values: 'text' (default) - plain text response, 'image' - image generation\n").optional(), "user_message": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("The user's prompt/message to the AI agent. Supports variable interpolation with\nflow.input syntax. Required unless memory is off and `previous_messages` supplies\nthe prompt; image output always needs it.\n").optional(), "system_prompt": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("System instructions that guide the AI's behavior, persona, and response style. Optional.").optional(), "streaming": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Boolean. If true, stream the AI response incrementally.\nStreaming events include: token_delta, reasoning_token_delta, tool_call, tool_call_arguments, tool_execution, tool_result\n").optional(), "memory": z.discriminatedUnion("type", [z.object({ "value": z.discriminatedUnion("kind", [z.object({ "kind": z.literal("off") }).describe("No conversation memory/context"), z.object({ "kind": z.literal("window"), "context_length": z.number().int().describe("Number of most recent messages to load and store. 0 turns memory off.") }).describe("Keeps the most recent messages of the memory named by the run's memory id (or the step's\n`memory_id`). Without a memory id the agent runs without memory.\n"), z.object({ "kind": z.literal("compaction"), "context_window": z.number().int().describe("Overrides the context window looked up from the model, in tokens. Only a model\nWindmill does not know needs one; those fall back to 128000.\n").optional() }).describe("Keeps the whole memory named by the run's memory id (or the step's `memory_id`), replacing\nits older part with a summary as the conversation approaches the model's context window.\nWithout a memory id the agent runs without memory, and compaction bounds the run's own loop.\n"), z.object({ "kind": z.literal("auto"), "context_length": z.number().int().describe("Maximum number of messages to retain in context").optional(), "memory_id": z.string().describe("Identifier for persistent memory across agent invocations").optional() }).describe("Deprecated, still read as it was written: the run's memory id, else the `memory_id` here.\nThe step's own `memory_id` is not read while this kind is set; switch the kind to `window`\nto use it. Without a `context_length`, or with 0, it is `off` and reads `previous_messages`.\n"), z.object({ "kind": z.literal("manual"), "messages": z.array(z.object({ "role": z.enum(["user","assistant","system"]), "content": z.string() }).describe("A single message in conversation history")) }).describe("Deprecated, still read as it was written. Move the step to `off` with `previous_messages` instead.")]).describe("Managed memory, stored by Windmill and replayed with each request. The memory is named by a memory id, see `memory_id`. While it is off, a step can supply its history in `previous_messages`."), "type": z.literal("static") }).describe("Static memory configuration passed directly to the AI agent"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Memory configuration - can be static (MemoryConfig), JavaScript expression, or AI-determined").optional(), "memory_id": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("String. Names the memory this step reads and writes, overriding the memory id the run\nwas started with (the chat conversation, an app chat session or the `memory_id` run\nparameter). Leave unset to use the run's memory id. A fixed value shares one memory\nacross every run; an expression such as `flow_input.customer_id` keeps one memory per\nkey. When it evaluates to an empty value the agent runs without memory. Read only\nwhile `memory` is `window` or `compaction`: it is ignored when memory is off, and an\nolder `auto` or `manual` memory reads neither history input.\n").optional(), "previous_messages": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Array of MemoryMessage. History supplied by the flow, sent between the system prompt\nand the user message. Read only while `memory` is off or absent: managed memory\nignores it, and an older `auto` or `manual` memory reads neither history input.\n").optional(), "output_schema": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("JSON Schema object defining structured output format. Used when you need the AI to return data in a specific shape.\nSupports standard JSON Schema properties: type, properties, required, items, enum, pattern, minLength, maxLength, minimum, maximum, etc.\nExample: { type: 'object', properties: { name: { type: 'string' }, age: { type: 'integer' } }, required: ['name'] }\n").optional(), "user_attachments": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Array of file references (images or PDFs) for the AI agent.\nFormat: Array<{ bucket: string, key: string }> - S3 object references\nExample: [{ bucket: 'my-bucket', key: 'documents/report.pdf' }]\n").optional(), "enabled_tools": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Array of strings naming which of the tools configured in `tools` the agent may call\nthis run. Leaving it unset carries every one of them; an empty array carries none.\nA tool is named as the model is shown it. An entry the model is shown nothing of is\nnamed by what identifies it instead: an MCP server by its resource path, carrying\nevery tool it exposes (which of them stays that entry's include_tools/exclude_tools),\nand a websearch entry by the reserved name '__wm_web_search', whatever summary it carries\n(no tool may take that name).\nExample: ['get_user', 'u/admin/github_mcp', '__wm_web_search']\n").optional(), "max_completion_tokens": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Integer. Maximum number of tokens the AI will generate in its response.\nRange: 1 to 4,294,967,295. Typical values: 256-4096 for most use cases.\n").optional(), "temperature": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Float. Controls randomness/creativity of responses.\nRange: 0.0 to 2.0 (provider-dependent)\n- 0.0 = deterministic, focused responses\n- 0.7 = balanced (common default)\n- 1.0+ = more creative/random\n").optional(), "max_iterations": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Number. Limits how many times the agent can loop through reasoning and tool use.\nRange: 1-1000.\n").optional() }).describe("Input parameters for the AI agent mapped to their values"), "tools": z.array(z.object({ "id": z.string().describe("Unique identifier for this tool. Cannot contain spaces - use underscores instead (e.g., 'get_user_data' not 'get user data')"), "summary": z.string().describe("The name the AI agent calls this tool by, not a human label. On a flowmodule tool it must match ^[a-zA-Z0-9_]+$ - letters, numbers and underscores only (e.g. 'search_documentation', not 'Search documentation') - and always be set; on an mcp or websearch tool it is a plain label. Put the human-readable explanation in 'description'.").optional(), "description": z.string().describe("Free-text description of the tool given to the AI to decide when and how to call it. Overrides the description auto-derived from the underlying script.").optional(), "job_token_scopes": z.array(z.string()).nullable().describe("Scopes the token of this tool's jobs is restricted to, on top of the agent step's own restriction: a tool can only narrow it.").optional(), "value": z.any().superRefine((x, ctx) => { +export const flowModuleValueSchema = z.discriminatedUnion("type", [z.object({ "input_transforms": z.record(z.string(), z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs")).describe("Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments"), "content": z.string().describe("The script source code. Should export a 'main' function"), "language": z.enum(["deno","bun","bunnative","python3","go","bash","powershell","postgresql","mysql","bigquery","snowflake","mssql","oracledb","graphql","nativets","php","rust","ansible","csharp","nu","java","ruby","rlang","duckdb"]).describe("Programming language for this script"), "path": z.string().describe("Optional path for saving this script").optional(), "lock": z.string().describe("Lock file content for dependencies").optional(), "type": z.literal("rawscript"), "tag": z.string().describe("Worker group tag for execution routing").optional(), "concurrent_limit": z.number().describe("Maximum concurrent executions of this script").optional(), "concurrency_time_window_s": z.number().describe("Time window for concurrent_limit").optional(), "custom_concurrency_key": z.string().describe("Custom key for grouping concurrent executions").optional(), "is_trigger": z.boolean().describe("If true, this script is a trigger that can start the flow").optional(), "assets": z.array(z.object({ "path": z.string().describe("Path to the asset"), "kind": z.enum(["s3object","resource","ducklake","datatable","volume","dbt"]).describe("Type of asset"), "access_type": z.union([z.literal("r"), z.literal("w"), z.literal("rw"), z.literal(null)]).nullable().describe("Access level for this asset").optional(), "alt_access_type": z.union([z.literal("r"), z.literal("w"), z.literal("rw"), z.literal(null)]).nullable().describe("Alternative access level").optional() })).describe("External resources this script accesses (S3 objects, resources, etc.)").optional() }).describe("Inline script with code defined directly in the flow. Use 'bun' as default language if unspecified. The script receives arguments from input_transforms"), z.object({ "input_transforms": z.record(z.string(), z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs")).describe("Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments"), "path": z.string().describe("Path to the script in the workspace (e.g., 'f/scripts/send_email')"), "hash": z.string().describe("Optional specific version hash of the script to use").optional(), "type": z.literal("script"), "tag_override": z.string().describe("Override the script's default worker group tag").optional(), "is_trigger": z.boolean().describe("If true, this script is a trigger that can start the flow").optional() }).describe("Reference to an existing script by path. Use this when calling a previously saved script instead of writing inline code"), z.object({ "input_transforms": z.record(z.string(), z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs")).describe("Map of parameter names to their values (static or JavaScript expressions). These become the subflow's input arguments"), "path": z.string().describe("Path to the flow in the workspace (e.g., 'f/flows/process_user')"), "type": z.literal("flow") }).describe("Reference to an existing flow by path. Use this to call another flow as a subflow"), z.object({ "modules": z.array(z.object({ "id": z.string().describe("Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"), "value": z.lazy(() => flowModuleValueSchema), "stop_after_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised.").optional(), "error_include_result": z.boolean().describe("When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false.").optional() }).describe("Early termination condition for a module").optional(), "stop_after_all_iters_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised.").optional(), "error_include_result": z.boolean().describe("When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false.").optional() }).describe("Early termination condition for a module").optional(), "skip_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.<step_id>'") }).describe("Conditionally skip this step based on previous results or flow inputs").optional(), "sleep": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "cache_ttl": z.number().describe("Cache duration in seconds for this step's results").optional(), "cache_ignore_s3_path": z.boolean().optional(), "timeout": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "delete_after_secs": z.number().int().describe("If set, delete the step's args, result and logs after this many seconds following job completion").optional(), "summary": z.string().describe("Short description of what this step does").optional(), "mock": z.object({ "enabled": z.boolean().describe("If true, return mock value instead of executing").optional(), "return_value": z.any().describe("Value to return when mocked").optional() }).describe("Mock configuration for testing without executing the actual step").optional(), "suspend": z.object({ "required_events": z.number().int().describe("Number of approvals required before continuing").optional(), "timeout": z.number().int().describe("Timeout in seconds before auto-continuing or canceling").optional(), "resume_form": z.object({ "schema": z.record(z.string(), z.any()).describe("JSON Schema for the resume form").optional() }).describe("Form schema for collecting input when resuming").optional(), "user_auth_required": z.boolean().describe("If true, only authenticated users can approve").optional(), "user_groups_required": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "self_approval_disabled": z.boolean().describe("If true, the user who started the flow cannot approve").optional(), "hide_cancel": z.boolean().describe("If true, hide the cancel button on the approval form").optional(), "continue_on_disapprove_timeout": z.boolean().describe("If true, continue flow on timeout instead of canceling").optional(), "skin": z.enum(["detailed","minimal"]).describe("How the approval request is presented, on the approval page and in Slack/Teams approval messages. 'detailed' (used when unset) shows the flow details (arguments, graph, approvers); 'minimal' shows only the request: the step description, form and approve/reject actions").optional() }).describe("Configuration for approval/resume steps that wait for user input").optional(), "priority": z.number().describe("Execution priority for this step (higher numbers run first)").optional(), "continue_on_error": z.boolean().describe("If true, flow continues even if this step fails").optional(), "job_token_scopes": z.array(z.string()).nullable().describe("Scopes the token of this step's jobs is restricted to (domain:action[:resource], e.g. oidc:write), on top of the flow's own restriction: a step can only narrow it. Applies to everything the step runs (loop and branch bodies, AI agent tools).").optional(), "retry": z.object({ "constant": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "seconds": z.number().int().describe("Seconds to wait between retries").optional() }).describe("Retry with constant delay between attempts").optional(), "exponential": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "multiplier": z.number().int().describe("Multiplier for exponential backoff").optional(), "seconds": z.number().int().gte(1).describe("Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too").optional(), "random_factor": z.number().int().gte(0).lte(100).describe("Random jitter percentage (0-100) to avoid thundering herd").optional() }).describe("Retry with exponential backoff: the n-th retry waits multiplier × seconds^n").optional(), "retry_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables") }).describe("Conditional retry based on error or result").optional() }).describe("Retry configuration for failed module executions").optional(), "debouncing": z.object({ "debounce_delay_s": z.number().int().describe("Delay in seconds to debounce this step's executions across flow runs").optional(), "debounce_key": z.string().describe("Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/<flow_path>-<step_id>").optional(), "debounce_args_to_accumulate": z.array(z.string()).describe("Array-type arguments to accumulate across debounced executions").optional(), "max_total_debouncing_time": z.number().int().describe("Maximum total time in seconds before forced execution").optional(), "max_total_debounces_amount": z.number().int().describe("Maximum number of debounces before forced execution").optional() }).describe("Debounce configuration for this step (EE only)").optional() }).describe("A single step in a flow. Can be a script, subflow, loop, or branch")).describe("Steps to execute for each iteration. These can reference the iteration value via 'flow_input.iter.value'"), "iterator": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs"), "skip_failures": z.boolean().describe("If true, iteration failures don't stop the loop. Failed iterations return null"), "type": z.literal("forloopflow"), "parallel": z.boolean().describe("If true, iterations run concurrently (faster for I/O-bound operations). Use with parallelism to control concurrency").optional(), "parallelism": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "squash": z.boolean().optional() }).describe("Executes nested modules in a loop over an iterator. Inside the loop, use 'flow_input.iter.value' to access the current iteration value, and 'flow_input.iter.index' for the index. Supports parallel execution for better performance on I/O-bound operations"), z.object({ "modules": z.array(z.object({ "id": z.string().describe("Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"), "value": z.lazy(() => flowModuleValueSchema), "stop_after_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised.").optional(), "error_include_result": z.boolean().describe("When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false.").optional() }).describe("Early termination condition for a module").optional(), "stop_after_all_iters_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised.").optional(), "error_include_result": z.boolean().describe("When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false.").optional() }).describe("Early termination condition for a module").optional(), "skip_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.<step_id>'") }).describe("Conditionally skip this step based on previous results or flow inputs").optional(), "sleep": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "cache_ttl": z.number().describe("Cache duration in seconds for this step's results").optional(), "cache_ignore_s3_path": z.boolean().optional(), "timeout": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "delete_after_secs": z.number().int().describe("If set, delete the step's args, result and logs after this many seconds following job completion").optional(), "summary": z.string().describe("Short description of what this step does").optional(), "mock": z.object({ "enabled": z.boolean().describe("If true, return mock value instead of executing").optional(), "return_value": z.any().describe("Value to return when mocked").optional() }).describe("Mock configuration for testing without executing the actual step").optional(), "suspend": z.object({ "required_events": z.number().int().describe("Number of approvals required before continuing").optional(), "timeout": z.number().int().describe("Timeout in seconds before auto-continuing or canceling").optional(), "resume_form": z.object({ "schema": z.record(z.string(), z.any()).describe("JSON Schema for the resume form").optional() }).describe("Form schema for collecting input when resuming").optional(), "user_auth_required": z.boolean().describe("If true, only authenticated users can approve").optional(), "user_groups_required": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "self_approval_disabled": z.boolean().describe("If true, the user who started the flow cannot approve").optional(), "hide_cancel": z.boolean().describe("If true, hide the cancel button on the approval form").optional(), "continue_on_disapprove_timeout": z.boolean().describe("If true, continue flow on timeout instead of canceling").optional(), "skin": z.enum(["detailed","minimal"]).describe("How the approval request is presented, on the approval page and in Slack/Teams approval messages. 'detailed' (used when unset) shows the flow details (arguments, graph, approvers); 'minimal' shows only the request: the step description, form and approve/reject actions").optional() }).describe("Configuration for approval/resume steps that wait for user input").optional(), "priority": z.number().describe("Execution priority for this step (higher numbers run first)").optional(), "continue_on_error": z.boolean().describe("If true, flow continues even if this step fails").optional(), "job_token_scopes": z.array(z.string()).nullable().describe("Scopes the token of this step's jobs is restricted to (domain:action[:resource], e.g. oidc:write), on top of the flow's own restriction: a step can only narrow it. Applies to everything the step runs (loop and branch bodies, AI agent tools).").optional(), "retry": z.object({ "constant": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "seconds": z.number().int().describe("Seconds to wait between retries").optional() }).describe("Retry with constant delay between attempts").optional(), "exponential": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "multiplier": z.number().int().describe("Multiplier for exponential backoff").optional(), "seconds": z.number().int().gte(1).describe("Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too").optional(), "random_factor": z.number().int().gte(0).lte(100).describe("Random jitter percentage (0-100) to avoid thundering herd").optional() }).describe("Retry with exponential backoff: the n-th retry waits multiplier × seconds^n").optional(), "retry_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables") }).describe("Conditional retry based on error or result").optional() }).describe("Retry configuration for failed module executions").optional(), "debouncing": z.object({ "debounce_delay_s": z.number().int().describe("Delay in seconds to debounce this step's executions across flow runs").optional(), "debounce_key": z.string().describe("Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/<flow_path>-<step_id>").optional(), "debounce_args_to_accumulate": z.array(z.string()).describe("Array-type arguments to accumulate across debounced executions").optional(), "max_total_debouncing_time": z.number().int().describe("Maximum total time in seconds before forced execution").optional(), "max_total_debounces_amount": z.number().int().describe("Maximum number of debounces before forced execution").optional() }).describe("Debounce configuration for this step (EE only)").optional() }).describe("A single step in a flow. Can be a script, subflow, loop, or branch")).describe("Steps to execute in each iteration"), "skip_failures": z.boolean().describe("If true, iteration failures don't stop the loop. Failed iterations return null"), "type": z.literal("whileloopflow"), "parallel": z.boolean().describe("If true, iterations run concurrently (use with caution in while loops)").optional(), "parallelism": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "squash": z.boolean().optional() }).describe("Executes nested modules repeatedly until stopped. The implicit iterator is the iteration counter, so 'flow_input.iter.value' equals 'flow_input.iter.index' (0, 1, 2, ...) and never carries state. To carry state across iterations, a step reads its own previous-iteration result via 'results.<its_own_id>' with a first-iteration fallback - the loop's stop_after_if must then be on that inner step (a plain single-step body with stop_after_if on the loop module does not resolve 'results' across iterations and never terminates); plain counters can instead be derived from 'flow_input.iter.index', which works in every configuration. stop_after_if is evaluated after each iteration - on the loop module 'result' is the last iteration's result"), z.object({ "branches": z.array(z.object({ "summary": z.string().describe("Short description of this branch condition").optional(), "expr": z.string().describe("JavaScript expression that returns boolean. Can use 'results.step_id' or 'flow_input'. First true expr wins"), "modules": z.array(z.object({ "id": z.string().describe("Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"), "value": z.lazy(() => flowModuleValueSchema), "stop_after_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised.").optional(), "error_include_result": z.boolean().describe("When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false.").optional() }).describe("Early termination condition for a module").optional(), "stop_after_all_iters_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised.").optional(), "error_include_result": z.boolean().describe("When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false.").optional() }).describe("Early termination condition for a module").optional(), "skip_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.<step_id>'") }).describe("Conditionally skip this step based on previous results or flow inputs").optional(), "sleep": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "cache_ttl": z.number().describe("Cache duration in seconds for this step's results").optional(), "cache_ignore_s3_path": z.boolean().optional(), "timeout": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "delete_after_secs": z.number().int().describe("If set, delete the step's args, result and logs after this many seconds following job completion").optional(), "summary": z.string().describe("Short description of what this step does").optional(), "mock": z.object({ "enabled": z.boolean().describe("If true, return mock value instead of executing").optional(), "return_value": z.any().describe("Value to return when mocked").optional() }).describe("Mock configuration for testing without executing the actual step").optional(), "suspend": z.object({ "required_events": z.number().int().describe("Number of approvals required before continuing").optional(), "timeout": z.number().int().describe("Timeout in seconds before auto-continuing or canceling").optional(), "resume_form": z.object({ "schema": z.record(z.string(), z.any()).describe("JSON Schema for the resume form").optional() }).describe("Form schema for collecting input when resuming").optional(), "user_auth_required": z.boolean().describe("If true, only authenticated users can approve").optional(), "user_groups_required": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "self_approval_disabled": z.boolean().describe("If true, the user who started the flow cannot approve").optional(), "hide_cancel": z.boolean().describe("If true, hide the cancel button on the approval form").optional(), "continue_on_disapprove_timeout": z.boolean().describe("If true, continue flow on timeout instead of canceling").optional(), "skin": z.enum(["detailed","minimal"]).describe("How the approval request is presented, on the approval page and in Slack/Teams approval messages. 'detailed' (used when unset) shows the flow details (arguments, graph, approvers); 'minimal' shows only the request: the step description, form and approve/reject actions").optional() }).describe("Configuration for approval/resume steps that wait for user input").optional(), "priority": z.number().describe("Execution priority for this step (higher numbers run first)").optional(), "continue_on_error": z.boolean().describe("If true, flow continues even if this step fails").optional(), "job_token_scopes": z.array(z.string()).nullable().describe("Scopes the token of this step's jobs is restricted to (domain:action[:resource], e.g. oidc:write), on top of the flow's own restriction: a step can only narrow it. Applies to everything the step runs (loop and branch bodies, AI agent tools).").optional(), "retry": z.object({ "constant": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "seconds": z.number().int().describe("Seconds to wait between retries").optional() }).describe("Retry with constant delay between attempts").optional(), "exponential": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "multiplier": z.number().int().describe("Multiplier for exponential backoff").optional(), "seconds": z.number().int().gte(1).describe("Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too").optional(), "random_factor": z.number().int().gte(0).lte(100).describe("Random jitter percentage (0-100) to avoid thundering herd").optional() }).describe("Retry with exponential backoff: the n-th retry waits multiplier × seconds^n").optional(), "retry_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables") }).describe("Conditional retry based on error or result").optional() }).describe("Retry configuration for failed module executions").optional(), "debouncing": z.object({ "debounce_delay_s": z.number().int().describe("Delay in seconds to debounce this step's executions across flow runs").optional(), "debounce_key": z.string().describe("Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/<flow_path>-<step_id>").optional(), "debounce_args_to_accumulate": z.array(z.string()).describe("Array-type arguments to accumulate across debounced executions").optional(), "max_total_debouncing_time": z.number().int().describe("Maximum total time in seconds before forced execution").optional(), "max_total_debounces_amount": z.number().int().describe("Maximum number of debounces before forced execution").optional() }).describe("Debounce configuration for this step (EE only)").optional() }).describe("A single step in a flow. Can be a script, subflow, loop, or branch")).describe("Steps to execute if this branch's expr is true") })).describe("Array of branches to evaluate in order. The first branch with expr evaluating to true executes"), "default": z.array(z.object({ "id": z.string().describe("Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"), "value": z.lazy(() => flowModuleValueSchema), "stop_after_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised.").optional(), "error_include_result": z.boolean().describe("When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false.").optional() }).describe("Early termination condition for a module").optional(), "stop_after_all_iters_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised.").optional(), "error_include_result": z.boolean().describe("When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false.").optional() }).describe("Early termination condition for a module").optional(), "skip_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.<step_id>'") }).describe("Conditionally skip this step based on previous results or flow inputs").optional(), "sleep": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "cache_ttl": z.number().describe("Cache duration in seconds for this step's results").optional(), "cache_ignore_s3_path": z.boolean().optional(), "timeout": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "delete_after_secs": z.number().int().describe("If set, delete the step's args, result and logs after this many seconds following job completion").optional(), "summary": z.string().describe("Short description of what this step does").optional(), "mock": z.object({ "enabled": z.boolean().describe("If true, return mock value instead of executing").optional(), "return_value": z.any().describe("Value to return when mocked").optional() }).describe("Mock configuration for testing without executing the actual step").optional(), "suspend": z.object({ "required_events": z.number().int().describe("Number of approvals required before continuing").optional(), "timeout": z.number().int().describe("Timeout in seconds before auto-continuing or canceling").optional(), "resume_form": z.object({ "schema": z.record(z.string(), z.any()).describe("JSON Schema for the resume form").optional() }).describe("Form schema for collecting input when resuming").optional(), "user_auth_required": z.boolean().describe("If true, only authenticated users can approve").optional(), "user_groups_required": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "self_approval_disabled": z.boolean().describe("If true, the user who started the flow cannot approve").optional(), "hide_cancel": z.boolean().describe("If true, hide the cancel button on the approval form").optional(), "continue_on_disapprove_timeout": z.boolean().describe("If true, continue flow on timeout instead of canceling").optional(), "skin": z.enum(["detailed","minimal"]).describe("How the approval request is presented, on the approval page and in Slack/Teams approval messages. 'detailed' (used when unset) shows the flow details (arguments, graph, approvers); 'minimal' shows only the request: the step description, form and approve/reject actions").optional() }).describe("Configuration for approval/resume steps that wait for user input").optional(), "priority": z.number().describe("Execution priority for this step (higher numbers run first)").optional(), "continue_on_error": z.boolean().describe("If true, flow continues even if this step fails").optional(), "job_token_scopes": z.array(z.string()).nullable().describe("Scopes the token of this step's jobs is restricted to (domain:action[:resource], e.g. oidc:write), on top of the flow's own restriction: a step can only narrow it. Applies to everything the step runs (loop and branch bodies, AI agent tools).").optional(), "retry": z.object({ "constant": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "seconds": z.number().int().describe("Seconds to wait between retries").optional() }).describe("Retry with constant delay between attempts").optional(), "exponential": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "multiplier": z.number().int().describe("Multiplier for exponential backoff").optional(), "seconds": z.number().int().gte(1).describe("Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too").optional(), "random_factor": z.number().int().gte(0).lte(100).describe("Random jitter percentage (0-100) to avoid thundering herd").optional() }).describe("Retry with exponential backoff: the n-th retry waits multiplier × seconds^n").optional(), "retry_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables") }).describe("Conditional retry based on error or result").optional() }).describe("Retry configuration for failed module executions").optional(), "debouncing": z.object({ "debounce_delay_s": z.number().int().describe("Delay in seconds to debounce this step's executions across flow runs").optional(), "debounce_key": z.string().describe("Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/<flow_path>-<step_id>").optional(), "debounce_args_to_accumulate": z.array(z.string()).describe("Array-type arguments to accumulate across debounced executions").optional(), "max_total_debouncing_time": z.number().int().describe("Maximum total time in seconds before forced execution").optional(), "max_total_debounces_amount": z.number().int().describe("Maximum number of debounces before forced execution").optional() }).describe("Debounce configuration for this step (EE only)").optional() }).describe("A single step in a flow. Can be a script, subflow, loop, or branch")).describe("Steps to execute if no branch expressions match"), "type": z.literal("branchone") }).describe("Conditional branching where only the first matching branch executes. Branches are evaluated in order, and the first one with a true expression runs. If no branches match, the default branch executes"), z.object({ "branches": z.array(z.object({ "summary": z.string().describe("Short description of this branch's purpose").optional(), "skip_failure": z.boolean().describe("If true, failure in this branch doesn't fail the entire flow").optional(), "modules": z.array(z.object({ "id": z.string().describe("Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"), "value": z.lazy(() => flowModuleValueSchema), "stop_after_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised.").optional(), "error_include_result": z.boolean().describe("When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false.").optional() }).describe("Early termination condition for a module").optional(), "stop_after_all_iters_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised.").optional(), "error_include_result": z.boolean().describe("When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false.").optional() }).describe("Early termination condition for a module").optional(), "skip_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.<step_id>'") }).describe("Conditionally skip this step based on previous results or flow inputs").optional(), "sleep": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "cache_ttl": z.number().describe("Cache duration in seconds for this step's results").optional(), "cache_ignore_s3_path": z.boolean().optional(), "timeout": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "delete_after_secs": z.number().int().describe("If set, delete the step's args, result and logs after this many seconds following job completion").optional(), "summary": z.string().describe("Short description of what this step does").optional(), "mock": z.object({ "enabled": z.boolean().describe("If true, return mock value instead of executing").optional(), "return_value": z.any().describe("Value to return when mocked").optional() }).describe("Mock configuration for testing without executing the actual step").optional(), "suspend": z.object({ "required_events": z.number().int().describe("Number of approvals required before continuing").optional(), "timeout": z.number().int().describe("Timeout in seconds before auto-continuing or canceling").optional(), "resume_form": z.object({ "schema": z.record(z.string(), z.any()).describe("JSON Schema for the resume form").optional() }).describe("Form schema for collecting input when resuming").optional(), "user_auth_required": z.boolean().describe("If true, only authenticated users can approve").optional(), "user_groups_required": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "self_approval_disabled": z.boolean().describe("If true, the user who started the flow cannot approve").optional(), "hide_cancel": z.boolean().describe("If true, hide the cancel button on the approval form").optional(), "continue_on_disapprove_timeout": z.boolean().describe("If true, continue flow on timeout instead of canceling").optional(), "skin": z.enum(["detailed","minimal"]).describe("How the approval request is presented, on the approval page and in Slack/Teams approval messages. 'detailed' (used when unset) shows the flow details (arguments, graph, approvers); 'minimal' shows only the request: the step description, form and approve/reject actions").optional() }).describe("Configuration for approval/resume steps that wait for user input").optional(), "priority": z.number().describe("Execution priority for this step (higher numbers run first)").optional(), "continue_on_error": z.boolean().describe("If true, flow continues even if this step fails").optional(), "job_token_scopes": z.array(z.string()).nullable().describe("Scopes the token of this step's jobs is restricted to (domain:action[:resource], e.g. oidc:write), on top of the flow's own restriction: a step can only narrow it. Applies to everything the step runs (loop and branch bodies, AI agent tools).").optional(), "retry": z.object({ "constant": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "seconds": z.number().int().describe("Seconds to wait between retries").optional() }).describe("Retry with constant delay between attempts").optional(), "exponential": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "multiplier": z.number().int().describe("Multiplier for exponential backoff").optional(), "seconds": z.number().int().gte(1).describe("Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too").optional(), "random_factor": z.number().int().gte(0).lte(100).describe("Random jitter percentage (0-100) to avoid thundering herd").optional() }).describe("Retry with exponential backoff: the n-th retry waits multiplier × seconds^n").optional(), "retry_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables") }).describe("Conditional retry based on error or result").optional() }).describe("Retry configuration for failed module executions").optional(), "debouncing": z.object({ "debounce_delay_s": z.number().int().describe("Delay in seconds to debounce this step's executions across flow runs").optional(), "debounce_key": z.string().describe("Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/<flow_path>-<step_id>").optional(), "debounce_args_to_accumulate": z.array(z.string()).describe("Array-type arguments to accumulate across debounced executions").optional(), "max_total_debouncing_time": z.number().int().describe("Maximum total time in seconds before forced execution").optional(), "max_total_debounces_amount": z.number().int().describe("Maximum number of debounces before forced execution").optional() }).describe("Debounce configuration for this step (EE only)").optional() }).describe("A single step in a flow. Can be a script, subflow, loop, or branch")).describe("Steps to execute in this branch") })).describe("Array of branches that all execute (either in parallel or sequentially)"), "type": z.literal("branchall"), "parallel": z.boolean().describe("If true, all branches execute concurrently. If false, they execute sequentially").optional() }).describe("Parallel branching where all branches execute simultaneously. Unlike BranchOne, all branches run regardless of conditions. Useful for executing independent tasks concurrently"), z.object({ "type": z.literal("identity"), "flow": z.boolean().describe("If true, marks this as a flow identity (special handling)").optional() }).describe("Pass-through module that returns its input unchanged. Useful for flow structure or as a placeholder"), z.object({ "input_transforms": z.object({ "provider": z.discriminatedUnion("type", [z.object({ "value": z.object({ "kind": z.enum(["openai","azure_openai","azure_foundry","anthropic","mistral","deepseek","googleai","groq","openrouter","togetherai","customai","aws_bedrock","typesafe","cloudflare"]).describe("Supported AI provider types"), "resource": z.string().describe("Resource reference in format '$res:{resource_path}' pointing to provider credentials"), "model": z.string().describe("Model identifier (e.g., 'gpt-4', 'claude-3-opus-20240229', 'gemini-pro')"), "reasoning_effort": z.string().describe("Provider-native reasoning effort token (e.g. 'low', 'high', 'none') for models that support extended thinking. Optional; unset leaves the provider default.").optional() }).describe("Complete AI provider configuration with resource reference and model selection"), "type": z.literal("static") }).describe("Static provider configuration passed directly to the AI agent"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Provider configuration - can be static (ProviderConfig), JavaScript expression, or AI-determined").optional(), "output_type": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Output format type.\nValid values: 'text' (default) - plain text response, 'image' - image generation\n").optional(), "user_message": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("The user's prompt/message to the AI agent. Supports variable interpolation with\nflow.input syntax. Required unless memory is off and `previous_messages` supplies\nthe prompt; image output always needs it.\n").optional(), "system_prompt": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("System instructions that guide the AI's behavior, persona, and response style. Optional.").optional(), "streaming": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Boolean. If true, stream the AI response incrementally.\nStreaming events include: token_delta, reasoning_token_delta, tool_call, tool_call_arguments, tool_execution, tool_result\n").optional(), "memory": z.discriminatedUnion("type", [z.object({ "value": z.discriminatedUnion("kind", [z.object({ "kind": z.literal("off") }).describe("No conversation memory/context"), z.object({ "kind": z.literal("window"), "context_length": z.number().int().describe("Number of most recent messages to load and store. 0 turns memory off.") }).describe("Keeps the most recent messages of the memory named by the run's memory id (or the step's\n`memory_id`). Without a memory id the agent runs without memory.\n"), z.object({ "kind": z.literal("compaction"), "context_window": z.number().int().describe("Overrides the context window looked up from the model, in tokens. Only a model\nWindmill does not know needs one; those fall back to 128000.\n").optional() }).describe("Keeps the whole memory named by the run's memory id (or the step's `memory_id`), replacing\nits older part with a summary as the conversation approaches the model's context window.\nWithout a memory id the agent runs without memory, and compaction bounds the run's own loop.\n"), z.object({ "kind": z.literal("auto"), "context_length": z.number().int().describe("Maximum number of messages to retain in context").optional(), "memory_id": z.string().describe("Identifier for persistent memory across agent invocations").optional() }).describe("Deprecated, still read as it was written: the run's memory id, else the `memory_id` here.\nThe step's own `memory_id` is not read while this kind is set; switch the kind to `window`\nto use it. Without a `context_length`, or with 0, it is `off` and reads `previous_messages`.\n"), z.object({ "kind": z.literal("manual"), "messages": z.array(z.object({ "role": z.enum(["user","assistant","system"]), "content": z.string() }).describe("A single message in conversation history")) }).describe("Deprecated, still read as it was written. Move the step to `off` with `previous_messages` instead.")]).describe("Managed memory, stored by Windmill and replayed with each request. The memory is named by a memory id, see `memory_id`. While it is off, a step can supply its history in `previous_messages`."), "type": z.literal("static") }).describe("Static memory configuration passed directly to the AI agent"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Memory configuration - can be static (MemoryConfig), JavaScript expression, or AI-determined").optional(), "memory_id": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("String. Names the memory this step reads and writes, overriding the memory id the run\nwas started with (the chat conversation, an app chat session or the `memory_id` run\nparameter). Leave unset to use the run's memory id. A fixed value shares one memory\nacross every run; an expression such as `flow_input.customer_id` keeps one memory per\nkey. When it evaluates to an empty value the agent runs without memory. Read only\nwhile `memory` is `window` or `compaction`: it is ignored when memory is off, and an\nolder `auto` or `manual` memory reads neither history input.\n").optional(), "previous_messages": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Array of MemoryMessage. History supplied by the flow, sent between the system prompt\nand the user message. Read only while `memory` is off or absent: managed memory\nignores it, and an older `auto` or `manual` memory reads neither history input.\n").optional(), "output_schema": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("JSON Schema object defining structured output format. Used when you need the AI to return data in a specific shape.\nSupports standard JSON Schema properties: type, properties, required, items, enum, pattern, minLength, maxLength, minimum, maximum, etc.\nExample: { type: 'object', properties: { name: { type: 'string' }, age: { type: 'integer' } }, required: ['name'] }\n").optional(), "user_attachments": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Array of file references (images or PDFs) for the AI agent.\nFormat: Array<{ bucket: string, key: string }> - S3 object references\nExample: [{ bucket: 'my-bucket', key: 'documents/report.pdf' }]\n").optional(), "enabled_tools": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Array of strings naming which of the tools configured in `tools` the agent may call\nthis run. Leaving it unset carries every one of them; an empty array carries none.\nA tool is named as the model is shown it. An entry the model is shown nothing of is\nnamed by what identifies it instead: an MCP server by its resource path, carrying\nevery tool it exposes (which of them stays that entry's include_tools/exclude_tools),\nand a websearch entry by the reserved name '__wm_web_search', whatever summary it carries\n(no tool may take that name).\nExample: ['get_user', 'u/admin/github_mcp', '__wm_web_search']\n").optional(), "max_completion_tokens": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Integer. Maximum number of tokens the AI will generate in its response.\nRange: 1 to 4,294,967,295. Typical values: 256-4096 for most use cases.\n").optional(), "temperature": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Float. Controls randomness/creativity of responses.\nRange: 0.0 to 2.0 (provider-dependent)\n- 0.0 = deterministic, focused responses\n- 0.7 = balanced (common default)\n- 1.0+ = more creative/random\n").optional(), "max_iterations": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Number. Limits how many times the agent can loop through reasoning and tool use.\nRange: 1-1000.\n").optional(), "model": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("String. Only on a step linked to a saved agent (see `agent`): replaces the model\nsaved on the agent for this step's runs, on the agent's own provider resource. An\nempty value keeps the saved model. Set it to an expression such as\n`flow_input.model` to choose the model per run.\n").optional(), "reasoning_effort": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("String. Only on a step linked to a saved agent (see `agent`): replaces the reasoning\neffort saved on the agent for this step's runs, as a provider-native token (e.g.\n'low', 'high', 'none'). An empty value sends no effort, so the model runs at its\ndefault. Leave the input out to keep the saved effort, which holds only while the\nstep runs the saved model. A step that is not linked sets both inside `provider`.\n").optional() }).describe("Input parameters for the AI agent mapped to their values"), "tools": z.array(z.object({ "id": z.string().describe("Unique identifier for this tool. Cannot contain spaces - use underscores instead (e.g., 'get_user_data' not 'get user data')"), "summary": z.string().describe("The name the AI agent calls this tool by, not a human label. On a flowmodule tool it must match ^[a-zA-Z0-9_]+$ - letters, numbers and underscores only (e.g. 'search_documentation', not 'Search documentation') - and always be set; on an mcp or websearch tool it is a plain label. Put the human-readable explanation in 'description'.").optional(), "description": z.string().describe("Free-text description of the tool given to the AI to decide when and how to call it. Overrides the description auto-derived from the underlying script.").optional(), "job_token_scopes": z.array(z.string()).nullable().describe("Scopes the token of this tool's jobs is restricted to, on top of the agent step's own restriction: a tool can only narrow it.").optional(), "value": z.any().superRefine((x, ctx) => { const schemas = [z.intersection(z.object({ "tool_type": z.literal("flowmodule") }), z.lazy(() => flowModuleValueSchema)).describe("A tool implemented as a flow module (script, flow, etc.). The AI can call this like any other flow module"), z.object({ "tool_type": z.literal("mcp"), "resource_path": z.string().describe("Path to the MCP resource/server configuration"), "include_tools": z.array(z.string()).describe("Whitelist of specific tools to include from this MCP server").optional(), "exclude_tools": z.array(z.string()).describe("Blacklist of tools to exclude from this MCP server").optional() }).describe("Reference to an external MCP (Model Context Protocol) tool. The AI can call tools from MCP servers"), z.object({ "tool_type": z.literal("websearch") }).describe("A tool implemented as a websearch tool. The AI can call this like any other websearch tool")]; const errors = schemas.reduce<z.ZodError[]>( (errors, schema) => @@ -17,10 +17,10 @@ export const flowModuleValueSchema = z.discriminatedUnion("type", [z.object({ "i message: "Invalid input: Should pass single schema", }); } - }).describe("The implementation of a tool. Can be a flow module (script/flow) or an MCP tool reference") }).describe("A tool available to an AI agent. Can be a flow module or an external MCP (Model Context Protocol) tool")).describe("Array of tools the agent can use. The agent decides which tools to call based on the task").optional(), "type": z.literal("aiagent"), "tag": z.string().describe("Worker group tag for execution routing. If not set, the AI agent step runs on the flow's tag (default `flow`)").optional(), "omit_output_from_conversation": z.boolean().describe("If true, this AI agent step does not persist its assistant or tool messages to the flow conversation when chat mode is enabled.").default(false), "agent": z.string().describe("Path of a reusable `ai_agent` resource (hybrid linking). When set, the agent brain\nconfig (provider/model/system prompt/etc.) and tool set are resolved at runtime from\nthat resource; the module's input_transforms then only carry the flow-local inputs\n(user_message, user_attachments, enabled_tools and the history inputs memory_id and previous_messages).\n").optional(), "tool_inputs": z.record(z.string(), z.record(z.string(), z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs"))).describe("Host-local wiring for an agent's tool inputs, keyed by tool id then input key. Binds the\nreferenced agent's tools to this flow's context (flow_input/results) without mutating the\nshared resource; overlaid onto the tools' input_transforms at runtime — including when\n`agent` is unset, since a step forked for editing keeps these overrides until it is saved\nback or unlinked.\n").optional(), "parallel": z.boolean().describe("If true, the agent can execute multiple tool calls in parallel").optional() }).describe("AI agent step that can use tools to accomplish tasks. The agent receives inputs and can call any of its configured tools to complete the task"), z.object({ "input_transforms": z.object({ "provider": z.discriminatedUnion("type", [z.object({ "value": z.object({ "kind": z.enum(["openai","azure_openai","azure_foundry","anthropic","mistral","deepseek","googleai","groq","openrouter","togetherai","customai","aws_bedrock","typesafe","cloudflare"]).describe("Supported AI provider types"), "resource": z.string().describe("Resource reference in format '$res:{resource_path}' pointing to provider credentials"), "model": z.string().describe("Model identifier (e.g., 'gpt-4', 'claude-3-opus-20240229', 'gemini-pro')"), "reasoning_effort": z.string().describe("Provider-native reasoning effort token (e.g. 'low', 'high', 'none') for models that support extended thinking. Optional; unset leaves the provider default.").optional() }).describe("Complete AI provider configuration with resource reference and model selection"), "type": z.literal("static") }).describe("Static provider configuration passed directly to the AI agent"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Provider configuration - can be static (ProviderConfig), JavaScript expression, or AI-determined"), "state": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("What the questions are asked about: a string, an object or an array of strings.\nAn object with descriptive keys holding only what the questions need works best.\nExample: { message: flow_input.message, plan: results.a.plan }\n"), "questions": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Object mapping each question name to { type, instructions, criteria }, where type is:\n- 'choice': criteria maps each option to its description (up to 255); the answer\n has choice, probabilities and confidence\n- 'score': criteria is an ordered array of 2 to 10 level descriptions; the answer\n has score, legend, probabilities and confidence\n- 'noul': yes/no, criteria optionally { true, false } descriptions; the answer has\n noul, the probability of yes (0 to 1)\nExample: { intent: { type: 'choice', instructions: 'What does the customer want?',\ncriteria: { refund: 'Money back', bug: 'Something is broken' } } }\n") }).describe("Input parameters for the decision mapped to their values"), "type": z.literal("aidecision"), "tag": z.string().describe("Worker group tag for execution routing. If not set, the step runs on the flow's tag (default `flow`)").optional() }).describe("AI decision step: one call to a decision model (TypeSafe's Jev, Cloudflare's\nJev-compatible Clef, or OpenAI's Decisions API) that answers typed questions about a\nstate with calibrated probabilities, instead of generating text.\nPrefer it over an AI agent to classify, route, score or check something: it is fast,\ncheap and its answers are structured. Its result is { output: { <question name>: answer },\nmodel, usage }, so a later step reads e.g. results.<id>.output.intent.choice. To route on\nthe answers, follow it with a branchone whose branch exprs read\nresults.<id>.output.<question>.choice. Usable as an AI agent tool, where the calling agent\nsupplies the state.\n")]).describe("The actual implementation of a flow step. Can be a script (inline or referenced), subflow, loop, branch, or special module type") + }).describe("The implementation of a tool. Can be a flow module (script/flow) or an MCP tool reference") }).describe("A tool available to an AI agent. Can be a flow module or an external MCP (Model Context Protocol) tool")).describe("Array of tools the agent can use. The agent decides which tools to call based on the task").optional(), "type": z.literal("aiagent"), "tag": z.string().describe("Worker group tag for execution routing. If not set, the AI agent step runs on the flow's tag (default `flow`)").optional(), "omit_output_from_conversation": z.boolean().describe("If true, this AI agent step does not persist its assistant or tool messages to the flow conversation when chat mode is enabled.").default(false), "agent": z.string().describe("Path of a reusable `ai_agent` resource (hybrid linking). When set, the agent brain\nconfig (provider/model/system prompt/etc.) and tool set are resolved at runtime from\nthat resource; the module's input_transforms then only carry the flow-local inputs\n(user_message, user_attachments, enabled_tools and the history inputs memory_id and previous_messages)\nand, optionally, the `model` and `reasoning_effort` overrides of what the agent saved.\n").optional(), "tool_inputs": z.record(z.string(), z.record(z.string(), z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs"))).describe("Host-local wiring for an agent's tool inputs, keyed by tool id then input key. Binds the\nreferenced agent's tools to this flow's context (flow_input/results) without mutating the\nshared resource; overlaid onto the tools' input_transforms at runtime — including when\n`agent` is unset, since a step forked for editing keeps these overrides until it is saved\nback or unlinked.\n").optional(), "parallel": z.boolean().describe("If true, the agent can execute multiple tool calls in parallel").optional() }).describe("AI agent step that can use tools to accomplish tasks. The agent receives inputs and can call any of its configured tools to complete the task"), z.object({ "input_transforms": z.object({ "provider": z.discriminatedUnion("type", [z.object({ "value": z.object({ "kind": z.enum(["openai","azure_openai","azure_foundry","anthropic","mistral","deepseek","googleai","groq","openrouter","togetherai","customai","aws_bedrock","typesafe","cloudflare"]).describe("Supported AI provider types"), "resource": z.string().describe("Resource reference in format '$res:{resource_path}' pointing to provider credentials"), "model": z.string().describe("Model identifier (e.g., 'gpt-4', 'claude-3-opus-20240229', 'gemini-pro')"), "reasoning_effort": z.string().describe("Provider-native reasoning effort token (e.g. 'low', 'high', 'none') for models that support extended thinking. Optional; unset leaves the provider default.").optional() }).describe("Complete AI provider configuration with resource reference and model selection"), "type": z.literal("static") }).describe("Static provider configuration passed directly to the AI agent"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Provider configuration - can be static (ProviderConfig), JavaScript expression, or AI-determined"), "state": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("What the questions are asked about: a string, an object or an array of strings.\nAn object with descriptive keys holding only what the questions need works best.\nExample: { message: flow_input.message, plan: results.a.plan }\n"), "questions": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Object mapping each question name to { type, instructions, criteria }, where type is:\n- 'choice': criteria maps each option to its description (up to 255); the answer\n has choice, probabilities and confidence\n- 'score': criteria is an ordered array of 2 to 10 level descriptions; the answer\n has score, legend, probabilities and confidence\n- 'noul': yes/no, criteria optionally { true, false } descriptions; the answer has\n noul, the probability of yes (0 to 1)\nExample: { intent: { type: 'choice', instructions: 'What does the customer want?',\ncriteria: { refund: 'Money back', bug: 'Something is broken' } } }\n") }).describe("Input parameters for the decision mapped to their values"), "type": z.literal("aidecision"), "tag": z.string().describe("Worker group tag for execution routing. If not set, the step runs on the flow's tag (default `flow`)").optional() }).describe("AI decision step: one call to a decision model (TypeSafe's Jev, Cloudflare's\nJev-compatible Clef, or OpenAI's Decisions API) that answers typed questions about a\nstate with calibrated probabilities, instead of generating text.\nPrefer it over an AI agent to classify, route, score or check something: it is fast,\ncheap and its answers are structured. Its result is { output: { <question name>: answer },\nmodel, usage }, so a later step reads e.g. results.<id>.output.intent.choice. To route on\nthe answers, follow it with a branchone whose branch exprs read\nresults.<id>.output.<question>.choice. Usable as an AI agent tool, where the calling agent\nsupplies the state.\n")]).describe("The actual implementation of a flow step. Can be a script (inline or referenced), subflow, loop, branch, or special module type") -export const flowModuleSchema = z.object({ "id": z.string().describe("Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"), "value": z.discriminatedUnion("type", [z.object({ "input_transforms": z.record(z.string(), z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs")).describe("Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments"), "content": z.string().describe("The script source code. Should export a 'main' function"), "language": z.enum(["deno","bun","bunnative","python3","go","bash","powershell","postgresql","mysql","bigquery","snowflake","mssql","oracledb","graphql","nativets","php","rust","ansible","csharp","nu","java","ruby","rlang","duckdb"]).describe("Programming language for this script"), "path": z.string().describe("Optional path for saving this script").optional(), "lock": z.string().describe("Lock file content for dependencies").optional(), "type": z.literal("rawscript"), "tag": z.string().describe("Worker group tag for execution routing").optional(), "concurrent_limit": z.number().describe("Maximum concurrent executions of this script").optional(), "concurrency_time_window_s": z.number().describe("Time window for concurrent_limit").optional(), "custom_concurrency_key": z.string().describe("Custom key for grouping concurrent executions").optional(), "is_trigger": z.boolean().describe("If true, this script is a trigger that can start the flow").optional(), "assets": z.array(z.object({ "path": z.string().describe("Path to the asset"), "kind": z.enum(["s3object","resource","ducklake","datatable","volume","dbt"]).describe("Type of asset"), "access_type": z.union([z.literal("r"), z.literal("w"), z.literal("rw"), z.literal(null)]).nullable().describe("Access level for this asset").optional(), "alt_access_type": z.union([z.literal("r"), z.literal("w"), z.literal("rw"), z.literal(null)]).nullable().describe("Alternative access level").optional() })).describe("External resources this script accesses (S3 objects, resources, etc.)").optional() }).describe("Inline script with code defined directly in the flow. Use 'bun' as default language if unspecified. The script receives arguments from input_transforms"), z.object({ "input_transforms": z.record(z.string(), z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs")).describe("Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments"), "path": z.string().describe("Path to the script in the workspace (e.g., 'f/scripts/send_email')"), "hash": z.string().describe("Optional specific version hash of the script to use").optional(), "type": z.literal("script"), "tag_override": z.string().describe("Override the script's default worker group tag").optional(), "is_trigger": z.boolean().describe("If true, this script is a trigger that can start the flow").optional() }).describe("Reference to an existing script by path. Use this when calling a previously saved script instead of writing inline code"), z.object({ "input_transforms": z.record(z.string(), z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs")).describe("Map of parameter names to their values (static or JavaScript expressions). These become the subflow's input arguments"), "path": z.string().describe("Path to the flow in the workspace (e.g., 'f/flows/process_user')"), "type": z.literal("flow") }).describe("Reference to an existing flow by path. Use this to call another flow as a subflow"), z.object({ "modules": z.array(z.lazy(() => flowModuleSchema)).describe("Steps to execute for each iteration. These can reference the iteration value via 'flow_input.iter.value'"), "iterator": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs"), "skip_failures": z.boolean().describe("If true, iteration failures don't stop the loop. Failed iterations return null"), "type": z.literal("forloopflow"), "parallel": z.boolean().describe("If true, iterations run concurrently (faster for I/O-bound operations). Use with parallelism to control concurrency").optional(), "parallelism": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "squash": z.boolean().optional() }).describe("Executes nested modules in a loop over an iterator. Inside the loop, use 'flow_input.iter.value' to access the current iteration value, and 'flow_input.iter.index' for the index. Supports parallel execution for better performance on I/O-bound operations"), z.object({ "modules": z.array(z.lazy(() => flowModuleSchema)).describe("Steps to execute in each iteration"), "skip_failures": z.boolean().describe("If true, iteration failures don't stop the loop. Failed iterations return null"), "type": z.literal("whileloopflow"), "parallel": z.boolean().describe("If true, iterations run concurrently (use with caution in while loops)").optional(), "parallelism": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "squash": z.boolean().optional() }).describe("Executes nested modules repeatedly until stopped. The implicit iterator is the iteration counter, so 'flow_input.iter.value' equals 'flow_input.iter.index' (0, 1, 2, ...) and never carries state. To carry state across iterations, a step reads its own previous-iteration result via 'results.<its_own_id>' with a first-iteration fallback - the loop's stop_after_if must then be on that inner step (a plain single-step body with stop_after_if on the loop module does not resolve 'results' across iterations and never terminates); plain counters can instead be derived from 'flow_input.iter.index', which works in every configuration. stop_after_if is evaluated after each iteration - on the loop module 'result' is the last iteration's result"), z.object({ "branches": z.array(z.object({ "summary": z.string().describe("Short description of this branch condition").optional(), "expr": z.string().describe("JavaScript expression that returns boolean. Can use 'results.step_id' or 'flow_input'. First true expr wins"), "modules": z.array(z.lazy(() => flowModuleSchema)).describe("Steps to execute if this branch's expr is true") })).describe("Array of branches to evaluate in order. The first branch with expr evaluating to true executes"), "default": z.array(z.lazy(() => flowModuleSchema)).describe("Steps to execute if no branch expressions match"), "type": z.literal("branchone") }).describe("Conditional branching where only the first matching branch executes. Branches are evaluated in order, and the first one with a true expression runs. If no branches match, the default branch executes"), z.object({ "branches": z.array(z.object({ "summary": z.string().describe("Short description of this branch's purpose").optional(), "skip_failure": z.boolean().describe("If true, failure in this branch doesn't fail the entire flow").optional(), "modules": z.array(z.lazy(() => flowModuleSchema)).describe("Steps to execute in this branch") })).describe("Array of branches that all execute (either in parallel or sequentially)"), "type": z.literal("branchall"), "parallel": z.boolean().describe("If true, all branches execute concurrently. If false, they execute sequentially").optional() }).describe("Parallel branching where all branches execute simultaneously. Unlike BranchOne, all branches run regardless of conditions. Useful for executing independent tasks concurrently"), z.object({ "type": z.literal("identity"), "flow": z.boolean().describe("If true, marks this as a flow identity (special handling)").optional() }).describe("Pass-through module that returns its input unchanged. Useful for flow structure or as a placeholder"), z.object({ "input_transforms": z.object({ "provider": z.discriminatedUnion("type", [z.object({ "value": z.object({ "kind": z.enum(["openai","azure_openai","azure_foundry","anthropic","mistral","deepseek","googleai","groq","openrouter","togetherai","customai","aws_bedrock","typesafe","cloudflare"]).describe("Supported AI provider types"), "resource": z.string().describe("Resource reference in format '$res:{resource_path}' pointing to provider credentials"), "model": z.string().describe("Model identifier (e.g., 'gpt-4', 'claude-3-opus-20240229', 'gemini-pro')"), "reasoning_effort": z.string().describe("Provider-native reasoning effort token (e.g. 'low', 'high', 'none') for models that support extended thinking. Optional; unset leaves the provider default.").optional() }).describe("Complete AI provider configuration with resource reference and model selection"), "type": z.literal("static") }).describe("Static provider configuration passed directly to the AI agent"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Provider configuration - can be static (ProviderConfig), JavaScript expression, or AI-determined").optional(), "output_type": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Output format type.\nValid values: 'text' (default) - plain text response, 'image' - image generation\n").optional(), "user_message": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("The user's prompt/message to the AI agent. Supports variable interpolation with\nflow.input syntax. Required unless memory is off and `previous_messages` supplies\nthe prompt; image output always needs it.\n").optional(), "system_prompt": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("System instructions that guide the AI's behavior, persona, and response style. Optional.").optional(), "streaming": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Boolean. If true, stream the AI response incrementally.\nStreaming events include: token_delta, reasoning_token_delta, tool_call, tool_call_arguments, tool_execution, tool_result\n").optional(), "memory": z.discriminatedUnion("type", [z.object({ "value": z.discriminatedUnion("kind", [z.object({ "kind": z.literal("off") }).describe("No conversation memory/context"), z.object({ "kind": z.literal("window"), "context_length": z.number().int().describe("Number of most recent messages to load and store. 0 turns memory off.") }).describe("Keeps the most recent messages of the memory named by the run's memory id (or the step's\n`memory_id`). Without a memory id the agent runs without memory.\n"), z.object({ "kind": z.literal("compaction"), "context_window": z.number().int().describe("Overrides the context window looked up from the model, in tokens. Only a model\nWindmill does not know needs one; those fall back to 128000.\n").optional() }).describe("Keeps the whole memory named by the run's memory id (or the step's `memory_id`), replacing\nits older part with a summary as the conversation approaches the model's context window.\nWithout a memory id the agent runs without memory, and compaction bounds the run's own loop.\n"), z.object({ "kind": z.literal("auto"), "context_length": z.number().int().describe("Maximum number of messages to retain in context").optional(), "memory_id": z.string().describe("Identifier for persistent memory across agent invocations").optional() }).describe("Deprecated, still read as it was written: the run's memory id, else the `memory_id` here.\nThe step's own `memory_id` is not read while this kind is set; switch the kind to `window`\nto use it. Without a `context_length`, or with 0, it is `off` and reads `previous_messages`.\n"), z.object({ "kind": z.literal("manual"), "messages": z.array(z.object({ "role": z.enum(["user","assistant","system"]), "content": z.string() }).describe("A single message in conversation history")) }).describe("Deprecated, still read as it was written. Move the step to `off` with `previous_messages` instead.")]).describe("Managed memory, stored by Windmill and replayed with each request. The memory is named by a memory id, see `memory_id`. While it is off, a step can supply its history in `previous_messages`."), "type": z.literal("static") }).describe("Static memory configuration passed directly to the AI agent"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Memory configuration - can be static (MemoryConfig), JavaScript expression, or AI-determined").optional(), "memory_id": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("String. Names the memory this step reads and writes, overriding the memory id the run\nwas started with (the chat conversation, an app chat session or the `memory_id` run\nparameter). Leave unset to use the run's memory id. A fixed value shares one memory\nacross every run; an expression such as `flow_input.customer_id` keeps one memory per\nkey. When it evaluates to an empty value the agent runs without memory. Read only\nwhile `memory` is `window` or `compaction`: it is ignored when memory is off, and an\nolder `auto` or `manual` memory reads neither history input.\n").optional(), "previous_messages": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Array of MemoryMessage. History supplied by the flow, sent between the system prompt\nand the user message. Read only while `memory` is off or absent: managed memory\nignores it, and an older `auto` or `manual` memory reads neither history input.\n").optional(), "output_schema": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("JSON Schema object defining structured output format. Used when you need the AI to return data in a specific shape.\nSupports standard JSON Schema properties: type, properties, required, items, enum, pattern, minLength, maxLength, minimum, maximum, etc.\nExample: { type: 'object', properties: { name: { type: 'string' }, age: { type: 'integer' } }, required: ['name'] }\n").optional(), "user_attachments": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Array of file references (images or PDFs) for the AI agent.\nFormat: Array<{ bucket: string, key: string }> - S3 object references\nExample: [{ bucket: 'my-bucket', key: 'documents/report.pdf' }]\n").optional(), "enabled_tools": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Array of strings naming which of the tools configured in `tools` the agent may call\nthis run. Leaving it unset carries every one of them; an empty array carries none.\nA tool is named as the model is shown it. An entry the model is shown nothing of is\nnamed by what identifies it instead: an MCP server by its resource path, carrying\nevery tool it exposes (which of them stays that entry's include_tools/exclude_tools),\nand a websearch entry by the reserved name '__wm_web_search', whatever summary it carries\n(no tool may take that name).\nExample: ['get_user', 'u/admin/github_mcp', '__wm_web_search']\n").optional(), "max_completion_tokens": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Integer. Maximum number of tokens the AI will generate in its response.\nRange: 1 to 4,294,967,295. Typical values: 256-4096 for most use cases.\n").optional(), "temperature": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Float. Controls randomness/creativity of responses.\nRange: 0.0 to 2.0 (provider-dependent)\n- 0.0 = deterministic, focused responses\n- 0.7 = balanced (common default)\n- 1.0+ = more creative/random\n").optional(), "max_iterations": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Number. Limits how many times the agent can loop through reasoning and tool use.\nRange: 1-1000.\n").optional() }).describe("Input parameters for the AI agent mapped to their values"), "tools": z.array(z.object({ "id": z.string().describe("Unique identifier for this tool. Cannot contain spaces - use underscores instead (e.g., 'get_user_data' not 'get user data')"), "summary": z.string().describe("The name the AI agent calls this tool by, not a human label. On a flowmodule tool it must match ^[a-zA-Z0-9_]+$ - letters, numbers and underscores only (e.g. 'search_documentation', not 'Search documentation') - and always be set; on an mcp or websearch tool it is a plain label. Put the human-readable explanation in 'description'.").optional(), "description": z.string().describe("Free-text description of the tool given to the AI to decide when and how to call it. Overrides the description auto-derived from the underlying script.").optional(), "job_token_scopes": z.array(z.string()).nullable().describe("Scopes the token of this tool's jobs is restricted to, on top of the agent step's own restriction: a tool can only narrow it.").optional(), "value": z.any().superRefine((x, ctx) => { +export const flowModuleSchema = z.object({ "id": z.string().describe("Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"), "value": z.discriminatedUnion("type", [z.object({ "input_transforms": z.record(z.string(), z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs")).describe("Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments"), "content": z.string().describe("The script source code. Should export a 'main' function"), "language": z.enum(["deno","bun","bunnative","python3","go","bash","powershell","postgresql","mysql","bigquery","snowflake","mssql","oracledb","graphql","nativets","php","rust","ansible","csharp","nu","java","ruby","rlang","duckdb"]).describe("Programming language for this script"), "path": z.string().describe("Optional path for saving this script").optional(), "lock": z.string().describe("Lock file content for dependencies").optional(), "type": z.literal("rawscript"), "tag": z.string().describe("Worker group tag for execution routing").optional(), "concurrent_limit": z.number().describe("Maximum concurrent executions of this script").optional(), "concurrency_time_window_s": z.number().describe("Time window for concurrent_limit").optional(), "custom_concurrency_key": z.string().describe("Custom key for grouping concurrent executions").optional(), "is_trigger": z.boolean().describe("If true, this script is a trigger that can start the flow").optional(), "assets": z.array(z.object({ "path": z.string().describe("Path to the asset"), "kind": z.enum(["s3object","resource","ducklake","datatable","volume","dbt"]).describe("Type of asset"), "access_type": z.union([z.literal("r"), z.literal("w"), z.literal("rw"), z.literal(null)]).nullable().describe("Access level for this asset").optional(), "alt_access_type": z.union([z.literal("r"), z.literal("w"), z.literal("rw"), z.literal(null)]).nullable().describe("Alternative access level").optional() })).describe("External resources this script accesses (S3 objects, resources, etc.)").optional() }).describe("Inline script with code defined directly in the flow. Use 'bun' as default language if unspecified. The script receives arguments from input_transforms"), z.object({ "input_transforms": z.record(z.string(), z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs")).describe("Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments"), "path": z.string().describe("Path to the script in the workspace (e.g., 'f/scripts/send_email')"), "hash": z.string().describe("Optional specific version hash of the script to use").optional(), "type": z.literal("script"), "tag_override": z.string().describe("Override the script's default worker group tag").optional(), "is_trigger": z.boolean().describe("If true, this script is a trigger that can start the flow").optional() }).describe("Reference to an existing script by path. Use this when calling a previously saved script instead of writing inline code"), z.object({ "input_transforms": z.record(z.string(), z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs")).describe("Map of parameter names to their values (static or JavaScript expressions). These become the subflow's input arguments"), "path": z.string().describe("Path to the flow in the workspace (e.g., 'f/flows/process_user')"), "type": z.literal("flow") }).describe("Reference to an existing flow by path. Use this to call another flow as a subflow"), z.object({ "modules": z.array(z.lazy(() => flowModuleSchema)).describe("Steps to execute for each iteration. These can reference the iteration value via 'flow_input.iter.value'"), "iterator": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs"), "skip_failures": z.boolean().describe("If true, iteration failures don't stop the loop. Failed iterations return null"), "type": z.literal("forloopflow"), "parallel": z.boolean().describe("If true, iterations run concurrently (faster for I/O-bound operations). Use with parallelism to control concurrency").optional(), "parallelism": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "squash": z.boolean().optional() }).describe("Executes nested modules in a loop over an iterator. Inside the loop, use 'flow_input.iter.value' to access the current iteration value, and 'flow_input.iter.index' for the index. Supports parallel execution for better performance on I/O-bound operations"), z.object({ "modules": z.array(z.lazy(() => flowModuleSchema)).describe("Steps to execute in each iteration"), "skip_failures": z.boolean().describe("If true, iteration failures don't stop the loop. Failed iterations return null"), "type": z.literal("whileloopflow"), "parallel": z.boolean().describe("If true, iterations run concurrently (use with caution in while loops)").optional(), "parallelism": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "squash": z.boolean().optional() }).describe("Executes nested modules repeatedly until stopped. The implicit iterator is the iteration counter, so 'flow_input.iter.value' equals 'flow_input.iter.index' (0, 1, 2, ...) and never carries state. To carry state across iterations, a step reads its own previous-iteration result via 'results.<its_own_id>' with a first-iteration fallback - the loop's stop_after_if must then be on that inner step (a plain single-step body with stop_after_if on the loop module does not resolve 'results' across iterations and never terminates); plain counters can instead be derived from 'flow_input.iter.index', which works in every configuration. stop_after_if is evaluated after each iteration - on the loop module 'result' is the last iteration's result"), z.object({ "branches": z.array(z.object({ "summary": z.string().describe("Short description of this branch condition").optional(), "expr": z.string().describe("JavaScript expression that returns boolean. Can use 'results.step_id' or 'flow_input'. First true expr wins"), "modules": z.array(z.lazy(() => flowModuleSchema)).describe("Steps to execute if this branch's expr is true") })).describe("Array of branches to evaluate in order. The first branch with expr evaluating to true executes"), "default": z.array(z.lazy(() => flowModuleSchema)).describe("Steps to execute if no branch expressions match"), "type": z.literal("branchone") }).describe("Conditional branching where only the first matching branch executes. Branches are evaluated in order, and the first one with a true expression runs. If no branches match, the default branch executes"), z.object({ "branches": z.array(z.object({ "summary": z.string().describe("Short description of this branch's purpose").optional(), "skip_failure": z.boolean().describe("If true, failure in this branch doesn't fail the entire flow").optional(), "modules": z.array(z.lazy(() => flowModuleSchema)).describe("Steps to execute in this branch") })).describe("Array of branches that all execute (either in parallel or sequentially)"), "type": z.literal("branchall"), "parallel": z.boolean().describe("If true, all branches execute concurrently. If false, they execute sequentially").optional() }).describe("Parallel branching where all branches execute simultaneously. Unlike BranchOne, all branches run regardless of conditions. Useful for executing independent tasks concurrently"), z.object({ "type": z.literal("identity"), "flow": z.boolean().describe("If true, marks this as a flow identity (special handling)").optional() }).describe("Pass-through module that returns its input unchanged. Useful for flow structure or as a placeholder"), z.object({ "input_transforms": z.object({ "provider": z.discriminatedUnion("type", [z.object({ "value": z.object({ "kind": z.enum(["openai","azure_openai","azure_foundry","anthropic","mistral","deepseek","googleai","groq","openrouter","togetherai","customai","aws_bedrock","typesafe","cloudflare"]).describe("Supported AI provider types"), "resource": z.string().describe("Resource reference in format '$res:{resource_path}' pointing to provider credentials"), "model": z.string().describe("Model identifier (e.g., 'gpt-4', 'claude-3-opus-20240229', 'gemini-pro')"), "reasoning_effort": z.string().describe("Provider-native reasoning effort token (e.g. 'low', 'high', 'none') for models that support extended thinking. Optional; unset leaves the provider default.").optional() }).describe("Complete AI provider configuration with resource reference and model selection"), "type": z.literal("static") }).describe("Static provider configuration passed directly to the AI agent"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Provider configuration - can be static (ProviderConfig), JavaScript expression, or AI-determined").optional(), "output_type": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Output format type.\nValid values: 'text' (default) - plain text response, 'image' - image generation\n").optional(), "user_message": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("The user's prompt/message to the AI agent. Supports variable interpolation with\nflow.input syntax. Required unless memory is off and `previous_messages` supplies\nthe prompt; image output always needs it.\n").optional(), "system_prompt": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("System instructions that guide the AI's behavior, persona, and response style. Optional.").optional(), "streaming": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Boolean. If true, stream the AI response incrementally.\nStreaming events include: token_delta, reasoning_token_delta, tool_call, tool_call_arguments, tool_execution, tool_result\n").optional(), "memory": z.discriminatedUnion("type", [z.object({ "value": z.discriminatedUnion("kind", [z.object({ "kind": z.literal("off") }).describe("No conversation memory/context"), z.object({ "kind": z.literal("window"), "context_length": z.number().int().describe("Number of most recent messages to load and store. 0 turns memory off.") }).describe("Keeps the most recent messages of the memory named by the run's memory id (or the step's\n`memory_id`). Without a memory id the agent runs without memory.\n"), z.object({ "kind": z.literal("compaction"), "context_window": z.number().int().describe("Overrides the context window looked up from the model, in tokens. Only a model\nWindmill does not know needs one; those fall back to 128000.\n").optional() }).describe("Keeps the whole memory named by the run's memory id (or the step's `memory_id`), replacing\nits older part with a summary as the conversation approaches the model's context window.\nWithout a memory id the agent runs without memory, and compaction bounds the run's own loop.\n"), z.object({ "kind": z.literal("auto"), "context_length": z.number().int().describe("Maximum number of messages to retain in context").optional(), "memory_id": z.string().describe("Identifier for persistent memory across agent invocations").optional() }).describe("Deprecated, still read as it was written: the run's memory id, else the `memory_id` here.\nThe step's own `memory_id` is not read while this kind is set; switch the kind to `window`\nto use it. Without a `context_length`, or with 0, it is `off` and reads `previous_messages`.\n"), z.object({ "kind": z.literal("manual"), "messages": z.array(z.object({ "role": z.enum(["user","assistant","system"]), "content": z.string() }).describe("A single message in conversation history")) }).describe("Deprecated, still read as it was written. Move the step to `off` with `previous_messages` instead.")]).describe("Managed memory, stored by Windmill and replayed with each request. The memory is named by a memory id, see `memory_id`. While it is off, a step can supply its history in `previous_messages`."), "type": z.literal("static") }).describe("Static memory configuration passed directly to the AI agent"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Memory configuration - can be static (MemoryConfig), JavaScript expression, or AI-determined").optional(), "memory_id": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("String. Names the memory this step reads and writes, overriding the memory id the run\nwas started with (the chat conversation, an app chat session or the `memory_id` run\nparameter). Leave unset to use the run's memory id. A fixed value shares one memory\nacross every run; an expression such as `flow_input.customer_id` keeps one memory per\nkey. When it evaluates to an empty value the agent runs without memory. Read only\nwhile `memory` is `window` or `compaction`: it is ignored when memory is off, and an\nolder `auto` or `manual` memory reads neither history input.\n").optional(), "previous_messages": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Array of MemoryMessage. History supplied by the flow, sent between the system prompt\nand the user message. Read only while `memory` is off or absent: managed memory\nignores it, and an older `auto` or `manual` memory reads neither history input.\n").optional(), "output_schema": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("JSON Schema object defining structured output format. Used when you need the AI to return data in a specific shape.\nSupports standard JSON Schema properties: type, properties, required, items, enum, pattern, minLength, maxLength, minimum, maximum, etc.\nExample: { type: 'object', properties: { name: { type: 'string' }, age: { type: 'integer' } }, required: ['name'] }\n").optional(), "user_attachments": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Array of file references (images or PDFs) for the AI agent.\nFormat: Array<{ bucket: string, key: string }> - S3 object references\nExample: [{ bucket: 'my-bucket', key: 'documents/report.pdf' }]\n").optional(), "enabled_tools": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Array of strings naming which of the tools configured in `tools` the agent may call\nthis run. Leaving it unset carries every one of them; an empty array carries none.\nA tool is named as the model is shown it. An entry the model is shown nothing of is\nnamed by what identifies it instead: an MCP server by its resource path, carrying\nevery tool it exposes (which of them stays that entry's include_tools/exclude_tools),\nand a websearch entry by the reserved name '__wm_web_search', whatever summary it carries\n(no tool may take that name).\nExample: ['get_user', 'u/admin/github_mcp', '__wm_web_search']\n").optional(), "max_completion_tokens": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Integer. Maximum number of tokens the AI will generate in its response.\nRange: 1 to 4,294,967,295. Typical values: 256-4096 for most use cases.\n").optional(), "temperature": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Float. Controls randomness/creativity of responses.\nRange: 0.0 to 2.0 (provider-dependent)\n- 0.0 = deterministic, focused responses\n- 0.7 = balanced (common default)\n- 1.0+ = more creative/random\n").optional(), "max_iterations": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Number. Limits how many times the agent can loop through reasoning and tool use.\nRange: 1-1000.\n").optional(), "model": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("String. Only on a step linked to a saved agent (see `agent`): replaces the model\nsaved on the agent for this step's runs, on the agent's own provider resource. An\nempty value keeps the saved model. Set it to an expression such as\n`flow_input.model` to choose the model per run.\n").optional(), "reasoning_effort": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("String. Only on a step linked to a saved agent (see `agent`): replaces the reasoning\neffort saved on the agent for this step's runs, as a provider-native token (e.g.\n'low', 'high', 'none'). An empty value sends no effort, so the model runs at its\ndefault. Leave the input out to keep the saved effort, which holds only while the\nstep runs the saved model. A step that is not linked sets both inside `provider`.\n").optional() }).describe("Input parameters for the AI agent mapped to their values"), "tools": z.array(z.object({ "id": z.string().describe("Unique identifier for this tool. Cannot contain spaces - use underscores instead (e.g., 'get_user_data' not 'get user data')"), "summary": z.string().describe("The name the AI agent calls this tool by, not a human label. On a flowmodule tool it must match ^[a-zA-Z0-9_]+$ - letters, numbers and underscores only (e.g. 'search_documentation', not 'Search documentation') - and always be set; on an mcp or websearch tool it is a plain label. Put the human-readable explanation in 'description'.").optional(), "description": z.string().describe("Free-text description of the tool given to the AI to decide when and how to call it. Overrides the description auto-derived from the underlying script.").optional(), "job_token_scopes": z.array(z.string()).nullable().describe("Scopes the token of this tool's jobs is restricted to, on top of the agent step's own restriction: a tool can only narrow it.").optional(), "value": z.any().superRefine((x, ctx) => { const schemas = [z.intersection(z.object({ "tool_type": z.literal("flowmodule") }), z.lazy(() => flowModuleValueSchema)).describe("A tool implemented as a flow module (script, flow, etc.). The AI can call this like any other flow module"), z.object({ "tool_type": z.literal("mcp"), "resource_path": z.string().describe("Path to the MCP resource/server configuration"), "include_tools": z.array(z.string()).describe("Whitelist of specific tools to include from this MCP server").optional(), "exclude_tools": z.array(z.string()).describe("Blacklist of tools to exclude from this MCP server").optional() }).describe("Reference to an external MCP (Model Context Protocol) tool. The AI can call tools from MCP servers"), z.object({ "tool_type": z.literal("websearch") }).describe("A tool implemented as a websearch tool. The AI can call this like any other websearch tool")]; const errors = schemas.reduce<z.ZodError[]>( (errors, schema) => @@ -37,7 +37,7 @@ export const flowModuleSchema = z.object({ "id": z.string().describe("Unique ide message: "Invalid input: Should pass single schema", }); } - }).describe("The implementation of a tool. Can be a flow module (script/flow) or an MCP tool reference") }).describe("A tool available to an AI agent. Can be a flow module or an external MCP (Model Context Protocol) tool")).describe("Array of tools the agent can use. The agent decides which tools to call based on the task").optional(), "type": z.literal("aiagent"), "tag": z.string().describe("Worker group tag for execution routing. If not set, the AI agent step runs on the flow's tag (default `flow`)").optional(), "omit_output_from_conversation": z.boolean().describe("If true, this AI agent step does not persist its assistant or tool messages to the flow conversation when chat mode is enabled.").default(false), "agent": z.string().describe("Path of a reusable `ai_agent` resource (hybrid linking). When set, the agent brain\nconfig (provider/model/system prompt/etc.) and tool set are resolved at runtime from\nthat resource; the module's input_transforms then only carry the flow-local inputs\n(user_message, user_attachments, enabled_tools and the history inputs memory_id and previous_messages).\n").optional(), "tool_inputs": z.record(z.string(), z.record(z.string(), z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs"))).describe("Host-local wiring for an agent's tool inputs, keyed by tool id then input key. Binds the\nreferenced agent's tools to this flow's context (flow_input/results) without mutating the\nshared resource; overlaid onto the tools' input_transforms at runtime — including when\n`agent` is unset, since a step forked for editing keeps these overrides until it is saved\nback or unlinked.\n").optional(), "parallel": z.boolean().describe("If true, the agent can execute multiple tool calls in parallel").optional() }).describe("AI agent step that can use tools to accomplish tasks. The agent receives inputs and can call any of its configured tools to complete the task"), z.object({ "input_transforms": z.object({ "provider": z.discriminatedUnion("type", [z.object({ "value": z.object({ "kind": z.enum(["openai","azure_openai","azure_foundry","anthropic","mistral","deepseek","googleai","groq","openrouter","togetherai","customai","aws_bedrock","typesafe","cloudflare"]).describe("Supported AI provider types"), "resource": z.string().describe("Resource reference in format '$res:{resource_path}' pointing to provider credentials"), "model": z.string().describe("Model identifier (e.g., 'gpt-4', 'claude-3-opus-20240229', 'gemini-pro')"), "reasoning_effort": z.string().describe("Provider-native reasoning effort token (e.g. 'low', 'high', 'none') for models that support extended thinking. Optional; unset leaves the provider default.").optional() }).describe("Complete AI provider configuration with resource reference and model selection"), "type": z.literal("static") }).describe("Static provider configuration passed directly to the AI agent"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Provider configuration - can be static (ProviderConfig), JavaScript expression, or AI-determined"), "state": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("What the questions are asked about: a string, an object or an array of strings.\nAn object with descriptive keys holding only what the questions need works best.\nExample: { message: flow_input.message, plan: results.a.plan }\n"), "questions": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Object mapping each question name to { type, instructions, criteria }, where type is:\n- 'choice': criteria maps each option to its description (up to 255); the answer\n has choice, probabilities and confidence\n- 'score': criteria is an ordered array of 2 to 10 level descriptions; the answer\n has score, legend, probabilities and confidence\n- 'noul': yes/no, criteria optionally { true, false } descriptions; the answer has\n noul, the probability of yes (0 to 1)\nExample: { intent: { type: 'choice', instructions: 'What does the customer want?',\ncriteria: { refund: 'Money back', bug: 'Something is broken' } } }\n") }).describe("Input parameters for the decision mapped to their values"), "type": z.literal("aidecision"), "tag": z.string().describe("Worker group tag for execution routing. If not set, the step runs on the flow's tag (default `flow`)").optional() }).describe("AI decision step: one call to a decision model (TypeSafe's Jev, Cloudflare's\nJev-compatible Clef, or OpenAI's Decisions API) that answers typed questions about a\nstate with calibrated probabilities, instead of generating text.\nPrefer it over an AI agent to classify, route, score or check something: it is fast,\ncheap and its answers are structured. Its result is { output: { <question name>: answer },\nmodel, usage }, so a later step reads e.g. results.<id>.output.intent.choice. To route on\nthe answers, follow it with a branchone whose branch exprs read\nresults.<id>.output.<question>.choice. Usable as an AI agent tool, where the calling agent\nsupplies the state.\n")]).describe("The actual implementation of a flow step. Can be a script (inline or referenced), subflow, loop, branch, or special module type"), "stop_after_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised.").optional(), "error_include_result": z.boolean().describe("When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false.").optional() }).describe("Early termination condition for a module").optional(), "stop_after_all_iters_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised.").optional(), "error_include_result": z.boolean().describe("When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false.").optional() }).describe("Early termination condition for a module").optional(), "skip_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.<step_id>'") }).describe("Conditionally skip this step based on previous results or flow inputs").optional(), "sleep": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "cache_ttl": z.number().describe("Cache duration in seconds for this step's results").optional(), "cache_ignore_s3_path": z.boolean().optional(), "timeout": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "delete_after_secs": z.number().int().describe("If set, delete the step's args, result and logs after this many seconds following job completion").optional(), "summary": z.string().describe("Short description of what this step does").optional(), "mock": z.object({ "enabled": z.boolean().describe("If true, return mock value instead of executing").optional(), "return_value": z.any().describe("Value to return when mocked").optional() }).describe("Mock configuration for testing without executing the actual step").optional(), "suspend": z.object({ "required_events": z.number().int().describe("Number of approvals required before continuing").optional(), "timeout": z.number().int().describe("Timeout in seconds before auto-continuing or canceling").optional(), "resume_form": z.object({ "schema": z.record(z.string(), z.any()).describe("JSON Schema for the resume form").optional() }).describe("Form schema for collecting input when resuming").optional(), "user_auth_required": z.boolean().describe("If true, only authenticated users can approve").optional(), "user_groups_required": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "self_approval_disabled": z.boolean().describe("If true, the user who started the flow cannot approve").optional(), "hide_cancel": z.boolean().describe("If true, hide the cancel button on the approval form").optional(), "continue_on_disapprove_timeout": z.boolean().describe("If true, continue flow on timeout instead of canceling").optional(), "skin": z.enum(["detailed","minimal"]).describe("How the approval request is presented, on the approval page and in Slack/Teams approval messages. 'detailed' (used when unset) shows the flow details (arguments, graph, approvers); 'minimal' shows only the request: the step description, form and approve/reject actions").optional() }).describe("Configuration for approval/resume steps that wait for user input").optional(), "priority": z.number().describe("Execution priority for this step (higher numbers run first)").optional(), "continue_on_error": z.boolean().describe("If true, flow continues even if this step fails").optional(), "job_token_scopes": z.array(z.string()).nullable().describe("Scopes the token of this step's jobs is restricted to (domain:action[:resource], e.g. oidc:write), on top of the flow's own restriction: a step can only narrow it. Applies to everything the step runs (loop and branch bodies, AI agent tools).").optional(), "retry": z.object({ "constant": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "seconds": z.number().int().describe("Seconds to wait between retries").optional() }).describe("Retry with constant delay between attempts").optional(), "exponential": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "multiplier": z.number().int().describe("Multiplier for exponential backoff").optional(), "seconds": z.number().int().gte(1).describe("Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too").optional(), "random_factor": z.number().int().gte(0).lte(100).describe("Random jitter percentage (0-100) to avoid thundering herd").optional() }).describe("Retry with exponential backoff: the n-th retry waits multiplier × seconds^n").optional(), "retry_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables") }).describe("Conditional retry based on error or result").optional() }).describe("Retry configuration for failed module executions").optional(), "debouncing": z.object({ "debounce_delay_s": z.number().int().describe("Delay in seconds to debounce this step's executions across flow runs").optional(), "debounce_key": z.string().describe("Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/<flow_path>-<step_id>").optional(), "debounce_args_to_accumulate": z.array(z.string()).describe("Array-type arguments to accumulate across debounced executions").optional(), "max_total_debouncing_time": z.number().int().describe("Maximum total time in seconds before forced execution").optional(), "max_total_debounces_amount": z.number().int().describe("Maximum number of debounces before forced execution").optional() }).describe("Debounce configuration for this step (EE only)").optional() }).describe("A single step in a flow. Can be a script, subflow, loop, or branch") + }).describe("The implementation of a tool. Can be a flow module (script/flow) or an MCP tool reference") }).describe("A tool available to an AI agent. Can be a flow module or an external MCP (Model Context Protocol) tool")).describe("Array of tools the agent can use. The agent decides which tools to call based on the task").optional(), "type": z.literal("aiagent"), "tag": z.string().describe("Worker group tag for execution routing. If not set, the AI agent step runs on the flow's tag (default `flow`)").optional(), "omit_output_from_conversation": z.boolean().describe("If true, this AI agent step does not persist its assistant or tool messages to the flow conversation when chat mode is enabled.").default(false), "agent": z.string().describe("Path of a reusable `ai_agent` resource (hybrid linking). When set, the agent brain\nconfig (provider/model/system prompt/etc.) and tool set are resolved at runtime from\nthat resource; the module's input_transforms then only carry the flow-local inputs\n(user_message, user_attachments, enabled_tools and the history inputs memory_id and previous_messages)\nand, optionally, the `model` and `reasoning_effort` overrides of what the agent saved.\n").optional(), "tool_inputs": z.record(z.string(), z.record(z.string(), z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs"))).describe("Host-local wiring for an agent's tool inputs, keyed by tool id then input key. Binds the\nreferenced agent's tools to this flow's context (flow_input/results) without mutating the\nshared resource; overlaid onto the tools' input_transforms at runtime — including when\n`agent` is unset, since a step forked for editing keeps these overrides until it is saved\nback or unlinked.\n").optional(), "parallel": z.boolean().describe("If true, the agent can execute multiple tool calls in parallel").optional() }).describe("AI agent step that can use tools to accomplish tasks. The agent receives inputs and can call any of its configured tools to complete the task"), z.object({ "input_transforms": z.object({ "provider": z.discriminatedUnion("type", [z.object({ "value": z.object({ "kind": z.enum(["openai","azure_openai","azure_foundry","anthropic","mistral","deepseek","googleai","groq","openrouter","togetherai","customai","aws_bedrock","typesafe","cloudflare"]).describe("Supported AI provider types"), "resource": z.string().describe("Resource reference in format '$res:{resource_path}' pointing to provider credentials"), "model": z.string().describe("Model identifier (e.g., 'gpt-4', 'claude-3-opus-20240229', 'gemini-pro')"), "reasoning_effort": z.string().describe("Provider-native reasoning effort token (e.g. 'low', 'high', 'none') for models that support extended thinking. Optional; unset leaves the provider default.").optional() }).describe("Complete AI provider configuration with resource reference and model selection"), "type": z.literal("static") }).describe("Static provider configuration passed directly to the AI agent"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Provider configuration - can be static (ProviderConfig), JavaScript expression, or AI-determined"), "state": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("What the questions are asked about: a string, an object or an array of strings.\nAn object with descriptive keys holding only what the questions need works best.\nExample: { message: flow_input.message, plan: results.a.plan }\n"), "questions": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").describe("Object mapping each question name to { type, instructions, criteria }, where type is:\n- 'choice': criteria maps each option to its description (up to 255); the answer\n has choice, probabilities and confidence\n- 'score': criteria is an ordered array of 2 to 10 level descriptions; the answer\n has score, legend, probabilities and confidence\n- 'noul': yes/no, criteria optionally { true, false } descriptions; the answer has\n noul, the probability of yes (0 to 1)\nExample: { intent: { type: 'choice', instructions: 'What does the customer want?',\ncriteria: { refund: 'Money back', bug: 'Something is broken' } } }\n") }).describe("Input parameters for the decision mapped to their values"), "type": z.literal("aidecision"), "tag": z.string().describe("Worker group tag for execution routing. If not set, the step runs on the flow's tag (default `flow`)").optional() }).describe("AI decision step: one call to a decision model (TypeSafe's Jev, Cloudflare's\nJev-compatible Clef, or OpenAI's Decisions API) that answers typed questions about a\nstate with calibrated probabilities, instead of generating text.\nPrefer it over an AI agent to classify, route, score or check something: it is fast,\ncheap and its answers are structured. Its result is { output: { <question name>: answer },\nmodel, usage }, so a later step reads e.g. results.<id>.output.intent.choice. To route on\nthe answers, follow it with a branchone whose branch exprs read\nresults.<id>.output.<question>.choice. Usable as an AI agent tool, where the calling agent\nsupplies the state.\n")]).describe("The actual implementation of a flow step. Can be a script (inline or referenced), subflow, loop, branch, or special module type"), "stop_after_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised.").optional(), "error_include_result": z.boolean().describe("When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false.").optional() }).describe("Early termination condition for a module").optional(), "stop_after_all_iters_if": z.object({ "skip_if_stopped": z.boolean().describe("If true, following steps are skipped when this condition triggers").optional(), "expr": z.string().describe("JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"), "error_message": z.string().nullable().describe("Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised.").optional(), "error_include_result": z.boolean().describe("When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false.").optional() }).describe("Early termination condition for a module").optional(), "skip_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.<step_id>'") }).describe("Conditionally skip this step based on previous results or flow inputs").optional(), "sleep": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "cache_ttl": z.number().describe("Cache duration in seconds for this step's results").optional(), "cache_ignore_s3_path": z.boolean().optional(), "timeout": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "delete_after_secs": z.number().int().describe("If set, delete the step's args, result and logs after this many seconds following job completion").optional(), "summary": z.string().describe("Short description of what this step does").optional(), "mock": z.object({ "enabled": z.boolean().describe("If true, return mock value instead of executing").optional(), "return_value": z.any().describe("Value to return when mocked").optional() }).describe("Mock configuration for testing without executing the actual step").optional(), "suspend": z.object({ "required_events": z.number().int().describe("Number of approvals required before continuing").optional(), "timeout": z.number().int().describe("Timeout in seconds before auto-continuing or canceling").optional(), "resume_form": z.object({ "schema": z.record(z.string(), z.any()).describe("JSON Schema for the resume form").optional() }).describe("Form schema for collecting input when resuming").optional(), "user_auth_required": z.boolean().describe("If true, only authenticated users can approve").optional(), "user_groups_required": z.discriminatedUnion("type", [z.object({ "value": z.any().describe("The static value. For resources, use format '$res:path/to/resource'").optional(), "type": z.literal("static") }).describe("Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'"), z.object({ "expr": z.string().describe("JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"), "type": z.literal("javascript") }).describe("JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')"), z.object({ "type": z.literal("ai") }).describe("Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.")]).describe("Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs").optional(), "self_approval_disabled": z.boolean().describe("If true, the user who started the flow cannot approve").optional(), "hide_cancel": z.boolean().describe("If true, hide the cancel button on the approval form").optional(), "continue_on_disapprove_timeout": z.boolean().describe("If true, continue flow on timeout instead of canceling").optional(), "skin": z.enum(["detailed","minimal"]).describe("How the approval request is presented, on the approval page and in Slack/Teams approval messages. 'detailed' (used when unset) shows the flow details (arguments, graph, approvers); 'minimal' shows only the request: the step description, form and approve/reject actions").optional() }).describe("Configuration for approval/resume steps that wait for user input").optional(), "priority": z.number().describe("Execution priority for this step (higher numbers run first)").optional(), "continue_on_error": z.boolean().describe("If true, flow continues even if this step fails").optional(), "job_token_scopes": z.array(z.string()).nullable().describe("Scopes the token of this step's jobs is restricted to (domain:action[:resource], e.g. oidc:write), on top of the flow's own restriction: a step can only narrow it. Applies to everything the step runs (loop and branch bodies, AI agent tools).").optional(), "retry": z.object({ "constant": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "seconds": z.number().int().describe("Seconds to wait between retries").optional() }).describe("Retry with constant delay between attempts").optional(), "exponential": z.object({ "attempts": z.number().int().describe("Number of retry attempts").optional(), "multiplier": z.number().int().describe("Multiplier for exponential backoff").optional(), "seconds": z.number().int().gte(1).describe("Base of the exponential (seconds); the n-th retry waits multiplier × seconds^n, where n counts constant retries too").optional(), "random_factor": z.number().int().gte(0).lte(100).describe("Random jitter percentage (0-100) to avoid thundering herd").optional() }).describe("Retry with exponential backoff: the n-th retry waits multiplier × seconds^n").optional(), "retry_if": z.object({ "expr": z.string().describe("JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables") }).describe("Conditional retry based on error or result").optional() }).describe("Retry configuration for failed module executions").optional(), "debouncing": z.object({ "debounce_delay_s": z.number().int().describe("Delay in seconds to debounce this step's executions across flow runs").optional(), "debounce_key": z.string().describe("Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/<flow_path>-<step_id>").optional(), "debounce_args_to_accumulate": z.array(z.string()).describe("Array-type arguments to accumulate across debounced executions").optional(), "max_total_debouncing_time": z.number().int().describe("Maximum total time in seconds before forced execution").optional(), "max_total_debounces_amount": z.number().int().describe("Maximum number of debounces before forced execution").optional() }).describe("Debounce configuration for this step (EE only)").optional() }).describe("A single step in a flow. Can be a script, subflow, loop, or branch") export const flowModulesSchema = z.array(flowModuleSchema) diff --git a/frontend/src/lib/components/copilot/chat/global/core.test.ts b/frontend/src/lib/components/copilot/chat/global/core.test.ts index d510b21826..546459cee2 100644 --- a/frontend/src/lib/components/copilot/chat/global/core.test.ts +++ b/frontend/src/lib/components/copilot/chat/global/core.test.ts @@ -241,6 +241,7 @@ vi.mock('$lib/gen', async () => { throw new Error('getResource mock not configured') }), createResource: vi.fn(async () => 'created'), + createResourceType: vi.fn(async () => 'created'), updateResource: vi.fn(async () => 'updated'), deleteResource: vi.fn(async () => 'deleted'), // A workspace with no skills, which is what makes `read_skill` refuse a path @@ -415,6 +416,7 @@ import { import { devopsRole, superadmin, userStore, usersWorkspaceStore } from '$lib/stores' import { processSecretArgs } from '$lib/components/secretArgUtils' import { clearWorkspaceRoleCache } from '$lib/user' +import { resourceTypesStore } from '$lib/components/resourceTypesStore' import { get } from 'svelte/store' import type { Tool, ToolCallbacks } from '../shared' @@ -446,7 +448,7 @@ const toolCallbacks: ToolCallbacks = { removeToolStatus: vi.fn(), // Every host that can run a script mounts the form, so the default answers it with what it // opened with. A test meaning to exercise a host without one overrides this with undefined. - requestRunArgs: async (_toolId, form) => form.args + requestRunArgs: async (_toolId, form) => ({ kind: 'args', args: form.args }) } function getGlobalTool(name: string): Tool<{}> { @@ -1209,6 +1211,28 @@ describe('global AI tools', () => { expect(raw).not.toContain('db_draft_input') }) + // The flow read is rebuilt field by field for the model, so a field missing there is + // silently absent and reads as "shared with nobody". + it('reports who a deployed flow is shared with', async () => { + vi.mocked(FlowService.getFlowByPath).mockResolvedValueOnce({ + path: 'f/flows/shared', + summary: 'Shared flow', + value: { modules: [] }, + schema: {}, + extra_perms: { 'g/finance': false } + } as any) + + const item = JSON.parse( + await callGlobalTool('read_workspace_item', { + type: 'flow', + path: 'f/flows/shared', + version: 'deployed' + }) + ) + + expect(item.extraPerms).toEqual({ 'g/finance': false }) + }) + it('redacts variable draft values when reading workspace items', async () => { await callGlobalTool('write_variable', { path: 'f/secrets/api_key', @@ -4771,6 +4795,39 @@ describe('global AI tools', () => { ).resolves.toBe(code) }) + // The worker reuses a non-empty step lock, so an edited step keeping its lock deploys + // against the old dependencies. + it('set_flow_module_code drops the lock of the edited step only', async () => { + const step = (id: string) => ({ + id, + value: { + type: 'rawscript', + language: 'python3', + content: 'import requests', + lock: 'requests==2.0', + input_transforms: {} + } + }) + seedBackendDraft('flow', 'f/flows/locked', { + path: 'f/flows/locked', + summary: 'f', + description: '', + value: { modules: [step('edited'), step('untouched')] }, + schema: {} + }) + + await callGlobalTool('set_flow_module_code', { + path: 'f/flows/locked', + module_id: 'edited', + code: 'import yaml' + }) + + const [edited, untouched] = getBackendDraft('flow', 'f/flows/locked').value.modules + expect(edited.value.content).toBe('import yaml') + expect(edited.value).not.toHaveProperty('lock') + expect(untouched.value.lock).toBe('requests==2.0') + }) + it('warns about every empty rawscript body (top-level, nested, preprocessor, failure) and skips populated ones', async () => { const result = JSON.parse( await callGlobalTool('write_flow', { @@ -5200,7 +5257,7 @@ describe('global AI tools', () => { opened = form.args kind = form.kind helperSource = { code: form.code, lang: form.lang } - return { name: 'Grace' } + return { kind: 'args', args: { name: 'Grace' } } } } ) @@ -5241,7 +5298,10 @@ describe('global AI tools', () => { vi.mocked(ScriptService.getScriptByPath).mockResolvedValueOnce(script) const statuses: any[] = [] - const requestRunArgs = vi.fn(async (_toolId: string, form: any) => form.args) + const requestRunArgs = vi.fn(async (_toolId: string, form: any) => ({ + kind: 'args', + args: form.args + })) const yolo = { ...toolCallbacks, setToolStatus: (_toolId: string, status: any) => statuses.push(status), @@ -5299,7 +5359,7 @@ describe('global AI tools', () => { ...toolCallbacks, setToolStatus: (_toolId: string, status: any) => statuses.push(status), shouldAutoAcceptToolConfirmations: () => true, - requestRunArgs: async (_toolId: string, form: any) => form.args + requestRunArgs: async (_toolId: string, form: any) => ({ kind: 'args', args: form.args }) } ) ) @@ -5330,7 +5390,7 @@ describe('global AI tools', () => { { ...toolCallbacks, shouldAutoAcceptToolConfirmations: () => true, - requestRunArgs: async (_toolId: string, form: any) => form.args + requestRunArgs: async (_toolId: string, form: any) => ({ kind: 'args', args: form.args }) } ) ) @@ -5361,7 +5421,7 @@ describe('global AI tools', () => { { ...toolCallbacks, shouldAutoAcceptToolConfirmations: () => true, - requestRunArgs: async (_toolId: string, form: any) => form.args + requestRunArgs: async (_toolId: string, form: any) => ({ kind: 'args', args: form.args }) } ) ) @@ -5394,6 +5454,124 @@ describe('global AI tools', () => { expect(refused).toContain('cannot show a run form') }) + // A surface that confirmed the run is waiting for the job it was promised, and a refused + // start is the one end it cannot see for itself: the call is neither pending nor cancelled, + // and nothing else tells it to stop offering a Run that would never reach a job. + it('run_script says the form is over when the job is refused', async () => { + vi.mocked(ScriptService.getScriptByPath).mockResolvedValue({ + path: 'f/scripts/refused', + schema: { properties: { name: { type: 'string' } } } + } as any) + vi.mocked(JobService.runScriptByPath).mockRejectedValueOnce(new Error('not permitted')) + const markRunFormEnded = vi.fn() + + await expect( + callGlobalTool( + 'run_script', + { path: 'f/scripts/refused', args: { name: 'Ada' } }, + { ...toolCallbacks, markRunFormEnded } + ) + ).rejects.toThrow('not permitted') + + expect(markRunFormEnded).toHaveBeenCalledWith(expect.any(String)) + }) + + // A chat-enabled flow's deployed page is a conversation with no run form, so it is opened + // to look at and the card keeps the run. The card reads this off the form rather than + // fetching the flow again. + it('run_flow marks a chat-enabled flow as conversational on its form', async () => { + vi.mocked(FlowService.getFlowByPath).mockResolvedValue({ + path: 'f/flows/chat', + schema: { properties: { user_message: { type: 'string' } } }, + value: { modules: [], chat_input_enabled: true } + } as any) + + const statuses: any[] = [] + await withCompletedTestJob(() => + callGlobalTool( + 'run_flow', + { path: 'f/flows/chat', args: { user_message: 'hi' } }, + { ...toolCallbacks, setToolStatus: (_id: string, s: any) => statuses.push(s) } + ) + ) + + expect(statuses.find((s) => s.runForm)?.runForm?.conversational).toBe(true) + }) + + // A run confirmed on the item's own page answers with the job it started, so this tool + // never sees a submission: the card and the model would otherwise be left describing the + // proposal as what ran, which is wrong as soon as the reader edits a field. + it('run_script reports an adopted job with the arguments that page sent', async () => { + vi.mocked(ScriptService.getScriptByPath).mockResolvedValue({ + path: 'f/scripts/adopted', + schema: { properties: { name: { type: 'string' } } } + } as any) + + const statuses: any[] = [] + const result = await withCompletedTestJob(() => + callGlobalTool( + 'run_script', + { path: 'f/scripts/adopted', args: { name: 'Ada' } }, + { + ...toolCallbacks, + setToolStatus: (_id: string, s: any) => statuses.push(s), + requestRunArgs: async () => ({ + kind: 'job', + jobId: 'job-123', + args: { name: 'Grace' }, + schema: { properties: { name: { type: 'string' } } } + }) + } + ) + ) + + // Started by the page, so this tool must not start one of its own. + expect(JobService.runScriptByPath).not.toHaveBeenCalled() + expect(statuses.filter((s) => s.parameters).at(-1)?.parameters).toEqual({ name: 'Grace' }) + expect(result).toContain('Grace') + expect(result).not.toContain('Ada') + }) + + // Redaction only visits the leaves the schema it is given declares, and the page runs the + // deployed version as it is now — which a deploy can have given an argument this call's + // schema never had. Redacting with ours would put the bytes in the persisted card and in + // the model's context. + it('run_script redacts an adopted job against the schema that page ran', async () => { + vi.mocked(ScriptService.getScriptByPath).mockResolvedValue({ + path: 'f/scripts/redeployed', + schema: { properties: { name: { type: 'string' } } } + } as any) + + const statuses: any[] = [] + const result = await withCompletedTestJob(() => + callGlobalTool( + 'run_script', + { path: 'f/scripts/redeployed', args: { name: 'Ada' } }, + { + ...toolCallbacks, + setToolStatus: (_id: string, s: any) => statuses.push(s), + requestRunArgs: async () => ({ + kind: 'job', + jobId: 'job-123', + args: { name: 'Grace', attachment: 'QUJDREVG' }, + // The deployed version the page loaded declares a file this call never saw. + schema: { + properties: { + name: { type: 'string' }, + attachment: { type: 'string', contentEncoding: 'base64' } + } + } + }) + } + ) + ) + + const parameters = statuses.filter((s) => s.parameters).at(-1)?.parameters + expect(parameters?.name).toBe('Grace') + expect(parameters?.attachment).not.toBe('QUJDREVG') + expect(result).not.toContain('QUJDREVG') + }) + // The posture answers wherever it is set, form or no form: what it answers is consent, and a // host without one has nothing left to ask. A secret still becomes a reference first, which // is the only thing the missing form would have done. @@ -5447,7 +5625,7 @@ describe('global AI tools', () => { setToolStatus: (_toolId: string, status: any) => statuses.push(status), // The user pastes into the field the model left small: the model's own // proposal is bounded by what it can emit, this is not. - requestRunArgs: async () => ({ blob: huge }) + requestRunArgs: async () => ({ kind: 'args', args: { blob: huge } }) } ) ) @@ -5507,7 +5685,10 @@ describe('global AI tools', () => { callGlobalTool( 'test_run_script', { path: 'f/scripts/noargs-test', args: { force_delete: true } }, - { ...toolCallbacks, requestRunArgs: async (_toolId, form) => form.args } + { + ...toolCallbacks, + requestRunArgs: async (_toolId, form) => ({ kind: 'args', args: form.args }) + } ) ) @@ -5532,7 +5713,10 @@ describe('global AI tools', () => { callGlobalTool( 'run_script', { path: 'f/scripts/host-literal', args: { token: 'hunter2' } }, - { ...toolCallbacks, requestRunArgs: async (_toolId, form) => form.args } + { + ...toolCallbacks, + requestRunArgs: async (_toolId, form) => ({ kind: 'args', args: form.args }) + } ) ) @@ -5555,7 +5739,7 @@ describe('global AI tools', () => { { ...toolCallbacks, shouldAutoAcceptToolConfirmations: () => true, - requestRunArgs: async (_toolId: string, form: any) => form.args + requestRunArgs: async (_toolId: string, form: any) => ({ kind: 'args', args: form.args }) } ) ) @@ -5659,7 +5843,10 @@ describe('global AI tools', () => { path: 'u/admin/live_flow', args: { name: 'Ada' } }, - { ...toolCallbacks, requestRunArgs: async () => ({ name: 'Grace' }) }, + { + ...toolCallbacks, + requestRunArgs: async () => ({ kind: 'args', args: { name: 'Grace' } }) + }, { testActiveFlow } ) ) @@ -5836,7 +6023,7 @@ describe('global AI tools', () => { ...toolCallbacks, requestRunArgs: async (_toolId, f) => { form = f - return { name: 'Grace' } + return { kind: 'args', args: { name: 'Grace' } } } } ) @@ -5902,7 +6089,7 @@ describe('global AI tools', () => { storagePath: 'u/admin/other_flow', effectivePath: 'u/admin/other_flow' }) - return form.args + return { kind: 'args', args: form.args } } }, { testActiveFlow } @@ -6005,7 +6192,7 @@ describe('global AI tools', () => { ...toolCallbacks, requestRunArgs: async (_toolId, f) => { form = f - return { name: 'Grace' } + return { kind: 'args', args: { name: 'Grace' } } } }, { testActiveFlow } @@ -6237,7 +6424,7 @@ describe('global AI tools', () => { ...toolCallbacks, requestRunArgs: async (_toolId, form) => { opened = form - return form.args + return { kind: 'args', args: form.args } } } ) @@ -6294,9 +6481,12 @@ describe('global AI tools', () => { // string, a list as `[]`. callbacks: { requestRunArgs: async (_toolId: string, form: any) => ({ - ...form.args, - user_message: '', - enabled_tools: form.args.enabled_tools ?? [] + kind: 'args' as const, + args: { + ...form.args, + user_message: '', + enabled_tools: form.args.enabled_tools ?? [] + } }) } }, @@ -6304,7 +6494,7 @@ describe('global AI tools', () => { answer: 'the bypass posture', callbacks: { shouldAutoAcceptToolConfirmations: () => true, - requestRunArgs: async (_toolId: string, form: any) => form.args + requestRunArgs: async (_toolId: string, form: any) => ({ kind: 'args', args: form.args }) } } ])( @@ -6406,7 +6596,7 @@ describe('global AI tools', () => { ...toolCallbacks, requestRunArgs: async (_toolId, form) => { opened = form - return form.args + return { kind: 'args', args: form.args } } } ) @@ -6451,7 +6641,7 @@ describe('global AI tools', () => { ...toolCallbacks, requestRunArgs: async (_toolId, f) => { form = f - return { name: 'Grace' } + return { kind: 'args', args: { name: 'Grace' } } } } ) @@ -6497,7 +6687,10 @@ describe('global AI tools', () => { callGlobalTool( 'test_run_step', { path: 'f/flows/drifted-step', stepId: 'call_script', args: { name: 'Ada' } }, - { ...toolCallbacks, requestRunArgs: async (_toolId, f) => ((form = f), f.args) } + { + ...toolCallbacks, + requestRunArgs: async (_toolId, f) => ((form = f), { kind: 'args', args: f.args }) + } ) ) @@ -6536,7 +6729,10 @@ describe('global AI tools', () => { callGlobalTool( 'test_run_step', { path: 'f/flows/secretful-step', stepId: 'call_secretful', args: {} }, - { ...toolCallbacks, requestRunArgs: async (_toolId, f) => ((form = f), f.args) } + { + ...toolCallbacks, + requestRunArgs: async (_toolId, f) => ((form = f), { kind: 'args', args: f.args }) + } ) ) @@ -6565,7 +6761,10 @@ describe('global AI tools', () => { callGlobalTool( 'test_run_step', { path: 'f/flows/preprocessed', stepId: 'preprocessor', args: { event: 'signup' } }, - { ...toolCallbacks, requestRunArgs: async (_toolId, f) => ((form = f), f.args) } + { + ...toolCallbacks, + requestRunArgs: async (_toolId, f) => ((form = f), { kind: 'args', args: f.args }) + } ) ) @@ -6649,7 +6848,10 @@ describe('global AI tools', () => { reset = form.resetKeys // What the user does with the form: attaches the file no model can produce, // and names a variable for the secret it was not allowed to fill. - return { ...form.args, doc: bytes, token: '$var:u/ada/prod_api_key' } + return { + kind: 'args', + args: { ...form.args, doc: bytes, token: '$var:u/ada/prod_api_key' } + } } } ) @@ -6712,7 +6914,7 @@ describe('global AI tools', () => { isPlanModeActive: () => planning, requestRunArgs: async (_toolId, form) => { planning = true - return form.args + return { kind: 'args', args: form.args } } } ) @@ -6742,7 +6944,7 @@ describe('global AI tools', () => { isPlanModeActive: () => planning, requestRunArgs: async (_toolId, form) => { formOpened = true - return form.args + return { kind: 'args', args: form.args } } } ) @@ -6762,7 +6964,10 @@ describe('global AI tools', () => { callGlobalTool( 'run_script', { path: 'f/scripts/greet', args: { name: 'Ada' } }, - { ...toolCallbacks, requestRunArgs: async () => ({ name: 'Grace' }) } + { + ...toolCallbacks, + requestRunArgs: async () => ({ kind: 'args', args: { name: 'Grace' } }) + } ) ) @@ -6789,7 +6994,10 @@ describe('global AI tools', () => { callGlobalTool( 'run_script', { path: 'f/scripts/greet', args: { name: 'Ada' } }, - { ...toolCallbacks, requestRunArgs: async (_toolId, form) => form.args } + { + ...toolCallbacks, + requestRunArgs: async (_toolId, form) => ({ kind: 'args', args: form.args }) + } ) ) @@ -7223,7 +7431,7 @@ describe('prepareGlobalSystemMessage', () => { }) expect(content).toContain('As a workspace admin you can write to any existing folder.') expect(content).toContain( - 'Folders here include `f/marketing`, `f/data_engineering` (you can also write to others not listed).' + 'Folders here include `f/marketing`, `f/data_engineering` (you can also write to others not listed; list_workspace_items with type "folder" lists them all).' ) expect(content).toContain( 'If the user names a folder, use it; if they explicitly ask for a new folder, create it with `create_folder`; otherwise ask them which folder to use rather than guessing or creating one unprompted.' @@ -8147,3 +8355,27 @@ describe('global prompt identity', () => { expect(get(userStore)?.folders).toEqual(['alice_stuff']) }) }) + +describe('create_resource_type', () => { + // The Add resource type form prefixes custom types with c_ unless an admin turns it off, so a + // hub type synced later under the same name cannot clash with one the chat created. + it.each([ + ['acme_billing', 'c_acme_billing'], + ['c_acme_billing', 'c_acme_billing'] + ])('creates %s as %s', async (given, created) => { + vi.mocked(ResourceService.createResourceType).mockClear() + resourceTypesStore.set(['postgresql']) + + const result = await callGlobalTool('create_resource_type', { + name: given, + description: 'Acme billing', + schema: { type: 'object' } + }) + + expect(vi.mocked(ResourceService.createResourceType).mock.calls[0][0].requestBody.name).toBe( + created + ) + expect(result).toContain(created) + expect(get(resourceTypesStore)).toBeUndefined() + }) +}) diff --git a/frontend/src/lib/components/copilot/chat/global/core.ts b/frontend/src/lib/components/copilot/chat/global/core.ts index 3e3baa36d7..a830d4d404 100644 --- a/frontend/src/lib/components/copilot/chat/global/core.ts +++ b/frontend/src/lib/components/copilot/chat/global/core.ts @@ -1,11 +1,13 @@ import { randomUUID } from '$lib/utils/uuid' import { AppService, + AssetService, AzureTriggerService, EmailTriggerService, FlowService, FolderService, GcpTriggerService, + GroupService, HttpTriggerService, JobService, KafkaTriggerService, @@ -25,7 +27,7 @@ import { import { createTwoFilesPatch } from 'diff' import { deepEqual } from 'fast-equals' import { promptSafe, type ArtifactVersionTarget } from '$lib/components/sessions/previewRouter' -import { canWrite } from '$lib/utils' +import { canDraftItem, roleCanDraft } from '$lib/editRights' import { $ScriptLang } from '$lib/gen/schemas.gen' import type { AppWithLastVersion, @@ -45,15 +47,17 @@ import type { ScriptLang } from '$lib/gen/types.gen' import { loadSchemaFromModule, memoryPropertyFor } from '$lib/components/flows/flowInfers' -import { flowLocalAgentSchema } from '$lib/components/flows/agentResourceUtils' +import { linkedAgentStepSchema } from '$lib/components/flows/agentResourceUtils' import { AGENT_FIELDS, initialVisibleAgentFields } from '$lib/components/flows/agentFormFields' import { withAgentDrafts } from '$lib/components/flows/linkedAgentDrafts' import { resolveLinkedAgentTools } from '$lib/components/flows/flowState' import { enabledToolNames, type AgentTool } from '$lib/components/flows/agentToolUtils' import { evalValue } from '$lib/components/flows/utils.svelte' +import { dropStaleStepLocks } from '$lib/components/flows/staleStepLocks' import { quickjsReady } from '$lib/utils/quickjsEval.svelte' import { updateRawAppPolicy } from '$lib/components/raw_apps/rawAppPolicy' import { + BUILDER_FRAMEWORK_TEMPLATES, FRAMEWORK_TEMPLATES, STARTER_RUNNABLES, type FrameworkKey @@ -67,12 +71,15 @@ import { stripFileArgs } from '$lib/components/job_args' import { processSecretArgs } from '$lib/components/secretArgUtils' +import { parsePipelineAnnotations } from '$lib/components/assets/AssetGraph/parsePipelineAnnotations' import { PLAN_MODE_MESSAGES } from '../planModeMessages' import { DEFAULT_DATA as DEFAULT_RAW_APP_DATA, formatDataTableRef } from '$lib/components/raw_apps/dataTableRefUtils' import { appSourceToDraftValue } from '$lib/components/raw_apps/rawAppDraftValue' +import { conformBuilderAppPolicy } from '$lib/components/raw_apps/builderAppPolicy' +import { operatorBuilderAppsIn } from '$lib/operatorWriteRights' import type { RawAppDomQuery } from '$lib/components/raw_apps/rawAppDom' import { dataUrlToImagePart, normalizeImageDataUrl, type AttachedImage } from '../imageUtils' import { sanitizeAttachmentName, textLineCount, type AttachedTextFile } from '../textFileUtils' @@ -104,7 +111,12 @@ import { createInlineScriptSession, findUnresolvedInlineScriptRefs } from '../flow/inlineScriptsUtils' -import { searchNpmPackagesTool } from '../script/core' +import { + resourceTypeSyncBlock, + searchNpmPackagesTool, + searchResourceTypes, + type ResourceTypeSync +} from '../script/core' import type { McpServer } from './mcpTools' import { logFeatureUsage } from '$lib/utils/featureUsage' import { isSkillEnabled } from '../skills/enabledSkills' @@ -117,6 +129,8 @@ import { } from '../skills/skillResources' import { MAX_SKILL_DESCRIPTION_LENGTH, MAX_SKILL_INSTRUCTIONS_LENGTH } from '../skills/skillMd' import { + getDatatablePrompt, + getWorkspaceSettingsPrompt, getDatatableSdkReference, getFlowPrompt, getPipelinePrompt, @@ -146,6 +160,7 @@ import { SPECIAL_MODULE_IDS, type CreatedResourceTriggerKind, type PreviewCardKind, + type RunFormAnswer, type RunFormDisplay, type ToolCallbacks, type ToolCodeDiff, @@ -157,6 +172,7 @@ import { searchDocsTool, readDocsPageTool } from '../docs/core' import { createDbSchemaTool } from '../script/core' import type { ContextElement } from '../context' import { getDatatableTools } from '../datatableTools' +import { getDatatableMigrationTools } from '../datatableMigrationTools' import { getDucklakeTools } from '../ducklakeTools' import { fileTools } from '../files/fileTools' import type { AttachedFilesStore } from '../files/attachedFiles.svelte' @@ -197,6 +213,7 @@ import { } from '$lib/stores' import { getWorkspaceRole, type RoleLookup } from '$lib/user' import { refreshSuperadmin } from '$lib/refreshUser' +import { resourceTypesStore } from '$lib/components/resourceTypesStore' import { get } from 'svelte/store' import { canonicalDraftSideValue, @@ -204,20 +221,30 @@ import { getDraftDiffValues } from '$lib/utils_draft_deploy' import { changedLineIndices, draftDeployedPatch, windowPatch } from './draftDiff' +import { workspaceSettingsTools } from './workspaceSettingsTools' import { getRun, summarizeRun } from './flowRunTree' import { UserDraftDbSyncer } from '$lib/userDraftDbSyncer.svelte' import { invalidateWorkspaceComparison } from '$lib/workspaceComparison' import type { UserDraftItemKind } from '$lib/gen' import { bundleRawAppDraft } from './rawAppBundlerBridge' import { + canOpenEditor, DEPLOY, NONE, + RUN_FLOW_PREVIEW, RUN_PREVIEW, + WRITE_APP_DRAFT, WRITE_DRAFT, + WRITE_FLOW_DRAFT, + WRITE_SCHEDULE_DRAFT, + WRITE_TRIGGER_DRAFT, + WRITE_RESOURCE_DRAFT, + WRITE_VARIABLE_DRAFT, type SessionAccess, type SessionTool, type SessionToolPolicy } from '../sessionCapabilities' +import { OPERATOR_SETTINGS_LOCATION } from '../assistantPermissions' import { buildRunsUrl, buildSchedulesUrl, @@ -239,7 +266,6 @@ import { parseItemsMaskParam } from '$lib/components/sessions/modifiedItemsMask' import { - pageHref, TRIGGER_PAGES, type TriggerKind as PageTriggerKind } from '$lib/components/sessions/previewRouter' @@ -299,7 +325,8 @@ const INSTRUCTION_SUBJECTS = [ // datatable SDK reference (the wmill.datatable() runnable API) the same way. // `pipeline` likewise isn't an item type — a data pipeline is a set of // annotated scripts in a folder, so it gets authoring guidance, not a CRUD type. -const INSTRUCTION_SUBJECTS_EXTRA = ['datatable', 'pipeline'] as const +// `workspace_settings` is the settings document an admin reads and changes. +const INSTRUCTION_SUBJECTS_EXTRA = ['datatable', 'pipeline', 'workspace_settings'] as const const ALL_INSTRUCTION_SUBJECTS = [...INSTRUCTION_SUBJECTS, ...INSTRUCTION_SUBJECTS_EXTRA] as const const MAX_LIST_LIMIT = 100 type ActiveGlobalEditorType = Extract<WorkspaceItemType, 'script' | 'flow' | 'app'> @@ -329,7 +356,7 @@ export type GlobalActiveEditorContext = { export type GlobalActivePreviewContext = { /** Page name as the tab strip shows it, e.g. "Schedules". */ label: string - /** Base-stripped page path plus the request params the page declares — values kept + /** Page path plus the request params the page declares — values kept * only for the ones addressing a workspace object, and percent-encoded. Never a raw * location: a tab can host a legacy app whose hash is app state, and a filter value * can be free text the user typed. Build it with `previewLocationContext`. */ @@ -348,16 +375,26 @@ export type GlobalUserMessageOptions = { /** Text files attached to this message; listed by reference below — the model * reads their content on demand via the file tools. */ files?: AttachedTextFile[] + /** From `resolveResourceTypeSync`; absent on a synced instance, which is told nothing. */ + resourceTypeSync?: ResourceTypeSync } const itemTypeSchema = z.enum(ITEM_TYPES) +// Folders and groups only carry permissions, so they are readable but kept out of +// `itemTypeSchema`, which the draft, deploy and delete tools share. +const ACCESS_TYPES = ['folder', 'group'] as const +type AccessType = (typeof ACCESS_TYPES)[number] +const readableTypeSchema = z.enum([...ITEM_TYPES, ...ACCESS_TYPES]) +function isAccessType(type: string): type is AccessType { + return (ACCESS_TYPES as readonly string[]).includes(type) +} const instructionSubjectSchema = z.enum(ALL_INSTRUCTION_SUBJECTS) const triggerKindSchema = z.enum(TRIGGER_KINDS) const scriptLangSchema = z.enum($ScriptLang.enum) const getInstructionsSchema = z.object({ subject: instructionSubjectSchema.describe( - 'What to get authoring instructions for: a workspace item type (script, flow, resource, app), "pipeline" for building a data pipeline (a DAG of annotated scripts wired by storage assets — NOT a flow), or "datatable" for the wmill.datatable() SQL SDK used inside runnables. Schedules, triggers, and variables don\'t need instructions — their tool schemas describe everything.' + 'What to get authoring instructions for: a workspace item type (script, flow, resource, app), "pipeline" for building a data pipeline (a DAG of annotated scripts wired by storage assets — NOT a flow), or "datatable" for how data tables work (schema changes and migrations, roles and permissions) plus the wmill.datatable() SQL SDK used inside runnables, or "workspace_settings" for the keys and rules of the workspace settings (admins only). Schedules, triggers, and variables don\'t need instructions — their tool schemas describe everything.' ), language: scriptLangSchema .optional() @@ -423,12 +460,14 @@ const updateUserInstructionsSchema = z.object({ ) }) +const listPipelinesSchema = z.object({}) + const listWorkspaceItemsSchema = z.object({ types: z - .array(itemTypeSchema) + .array(readableTypeSchema) .optional() .describe( - 'Optional item types to list. Defaults to scripts and flows. Pass schedule or trigger explicitly when needed (listing triggers spans 9 kinds and is heavier).' + 'Optional item types to list. Defaults to scripts and flows. Pass schedule or trigger explicitly when needed (listing triggers spans 9 kinds and is heavier). "folder" lists folders with their owners and extraPerms; "group" lists groups with their extraPerms (read one for its members). path_prefix does not apply to these two.' ), query: z.string().optional().describe('Optional case-insensitive path or summary search string.'), path_prefix: z @@ -455,11 +494,11 @@ const listWorkspaceItemsSchema = z.object({ }) const readWorkspaceItemSchema = z.object({ - type: itemTypeSchema, + type: readableTypeSchema, path: z .string() .describe( - 'Workspace path of the item to read, or a hub/<version>/<app>/<name> path from search_hub_scripts to read a hub script.' + 'Workspace path of the item to read, or a hub/<version>/<app>/<name> path from search_hub_scripts to read a hub script. For a folder or group, its name.' ), trigger_kind: triggerKindSchema .optional() @@ -721,6 +760,20 @@ const searchResourceTypesSchema = z.object({ .describe('Max number of resource types to return. Defaults to 5.') }) +const createResourceTypeSchema = z.object({ + name: z + .string() + .describe( + 'Type name with the c_ prefix of custom types, e.g. c_acme_billing (added when missing): 1 to 50 letters, digits, "_" or "-". Resources and resource-typed parameters refer to it by this name.' + ), + description: z.string().describe('What a resource of this type connects to.'), + schema: z + .record(z.string(), z.any()) + .describe( + 'JSON Schema of a resource value of this type: { "type": "object", "properties": {...}, "required": [...] }, with every connection field, secrets included (a resource fills those with "$var:" references).' + ) +}) + const getRunSchema = z.object({ id: z.string().describe('The UUID of the run (job) to inspect.'), step: z @@ -759,7 +812,7 @@ const listRunsSchema = z.object({ // superadmin caller; every other caller gets the hedge even where nothing is hidden. const NO_WORKERS_VISIBLE_MESSAGE = 'No workers came back. This does NOT establish that no workers are running: an instance can hide workers from callers without the devops role, and it does so by returning an empty list rather than an error. ' + - 'Tell the user you cannot see any workers and that worker visibility may be restricted for your account, and suggest they check the Workers page themselves. Never state that no workers are online or that the instance has none.' + 'Tell the user you cannot see any workers and that worker visibility may be restricted for your account, and suggest they check the Workers page themselves if they can open it, or ask a workspace admin otherwise. Never state that no workers are online or that the instance has none.' const NO_WORKERS_CONNECTED_MESSAGE = 'No workers are connected to this instance (none pinged in the last 5 minutes). Queued runs will stay queued until a worker starts.' const WORKER_PAGE_SIZE = 100 @@ -954,7 +1007,7 @@ const runScriptSchema = z.object({ const runScriptToolDef = createToolDef( runScriptSchema, 'run_script', - 'Run a DEPLOYED script for real, under the user\'s own permissions. Fill in every argument you can infer: the user gets an argument form prefilled with `args` and decides what runs. For a secret argument prefer `$var:<path>` naming an existing workspace variable; a literal is minted into a short-lived secret before the run, but stays in this call. A required file is the user\'s to attach, so call this even when you cannot supply one rather than asking in chat. Use only when the user names the deployed version ("the deployed X", "in production", "for real").', + 'Run a DEPLOYED script for real, under the user\'s own permissions. Fill in every argument you can infer: the user gets an argument form prefilled with `args` and decides what runs. In an AI session the user can open that form on the script\'s own deployed page instead; either way this call waits for them and runs what they confirm. For a secret argument prefer `$var:<path>` naming an existing workspace variable; a literal is minted into a short-lived secret before the run, but stays in this call. A required file is the user\'s to attach, so call this even when you cannot supply one rather than asking in chat. Use only when the user names the deployed version ("the deployed X", "in production", "for real").', { strict: false } ) @@ -993,7 +1046,7 @@ const runFlowSchema = z.object({ const runFlowToolDef = createToolDef( runFlowSchema, 'run_flow', - 'Run a DEPLOYED flow for real, under the user\'s own permissions. Fill in every argument you can infer: the user gets an argument form prefilled with `args` and decides what runs. For a secret argument prefer `$var:<path>` naming an existing workspace variable; a literal is minted into a short-lived secret before the run, but stays in this call. A required file is the user\'s to attach, so call this even when you cannot supply one rather than asking in chat. Use only when the user names the deployed version ("the deployed X", "in production", "for real").', + 'Run a DEPLOYED flow for real, under the user\'s own permissions. Fill in every argument you can infer: the user gets an argument form prefilled with `args` and decides what runs. In an AI session the user can open that form on the flow\'s own deployed page instead; either way this call waits for them and runs what they confirm. For a secret argument prefer `$var:<path>` naming an existing workspace variable; a literal is minted into a short-lived secret before the run, but stays in this call. A required file is the user\'s to attach, so call this even when you cannot supply one rather than asking in chat. Use only when the user names the deployed version ("the deployed X", "in production", "for real").', { strict: false } ) @@ -1040,6 +1093,12 @@ const backendRunnableSchema = z .optional() .describe( 'Required when type is "script", "flow", or "hubscript". Workspace path of the runnable.' + ), + viewerDataAccess: z + .boolean() + .optional() + .describe( + "Inline only. When true, the runnable reads data as the person viewing the app instead of as the app's identity: data table connections that name no role hold the viewer's roles, and object storage permission rules are checked against the viewer, so row-level security and per-user storage paths answer per viewer. Resources and variables stay the app's. Anonymous viewers are refused. Omit to keep the current setting." ) }) .describe( @@ -1180,7 +1239,14 @@ const openPreviewSchema = z.object({ * it can open, so it is not offered. Per-PATH write permission is unknowable here — * a workspace capability says nothing about `f/finance/*` — and is resolved in the * handler instead. Mirrors `open_page` re-narrowing its page enum per user. */ +const openPreviewNoPipelineKind = z + .enum(['script', 'flow', 'raw_app']) + .describe( + 'Item kind to preview. Use "raw_app" for code-based apps. The legacy drag-and-drop app builder ("app") is not previewable in the session panel — don\'t pass it.' + ) + const openPreviewViewOnlySchema = openPreviewSchema.extend({ + kind: openPreviewNoPipelineKind, mode: z .literal('view') .optional() @@ -1189,6 +1255,21 @@ const openPreviewViewOnlySchema = openPreviewSchema.extend({ ) }) +/** A builder operator: the editors of the kinds they compose, and the deployed page for + * everything else. */ +const openPreviewBuilderEditorSchema = (flows: boolean, apps: boolean) => + openPreviewSchema.extend({ + kind: openPreviewNoPipelineKind, + mode: z + .enum(['edit', 'view']) + .optional() + .describe( + flows && apps + ? 'Which side to show. "edit" opens the flow or app editor and works for flows and raw apps only: the only editors you can open in this workspace. Pass "view" for a script, the deployed page with its run form, triggers and past runs.' + : `Which side to show. "edit" opens the ${flows ? 'flow' : 'app'} editor and works for ${flows ? 'flows' : 'raw apps'} only: the only editor you can open in this workspace. Pass "view" for a script or ${flows ? 'app' : 'flow'}, the deployed page with its run form, triggers and past runs.` + ) + }) + const OPEN_PREVIEW_DESCRIPTION = 'Open the live preview / editor for a workspace item in the side panel next to the chat. ONLY works inside an AI session — call this after writing or editing a script, flow, or raw app to let the user see and interact with it. The path you pass is the path of the item; for code-based apps use kind="raw_app" (legacy drag-and-drop apps are not previewable). Returns an error if there is no active session.' @@ -1280,12 +1361,7 @@ const readDomSchema = z.object({ const takeScreenshotSchema = z.object({}) -const FRAMEWORK_KEYS = [ - 'react19', - 'react18', - 'svelte5', - 'vue' -] as const satisfies readonly FrameworkKey[] +const FRAMEWORK_KEYS = ['react19', 'react18', 'svelte5'] as const satisfies readonly FrameworkKey[] const initAppSchema = z.object({ path: z @@ -1316,6 +1392,8 @@ const initAppSchema = z.object({ ) }) +const INIT_APP_DESCRIPTION = 'Initialize a draft raw app from a framework template.' + // Mirrors the backend VALID_FOLDER_NAME check so an invalid name fails before the // network round-trip (the server enforces the same rule). const VALID_FOLDER_NAME = /^[a-zA-Z_0-9-]+$/ @@ -1331,16 +1409,19 @@ const createFolderSchema = z.object({ // `folders`/`foldersRead` are undefined when the user's role in this workspace could not // be resolved. -type FolderPromptContext = { folders?: string[]; foldersRead?: string[]; isAdmin: boolean } +type FolderPromptContext = { + folders?: string[] + foldersRead?: string[] + groups?: string[] + isAdmin: boolean +} // Renders the folders the current user can act on into the system prompt so the -// model can pick an `f/<folder>/...` path without a discovery round-trip (there -// is no folder-listing tool). For a non-admin, `folders` (from whoami) is exactly -// the writable set, so read-only folders are listed separately as off-limits. -// Admins bypass folder ACLs and can write anywhere, but `folders` only carries -// their explicitly-permissioned subset, so for admins it is offered as a -// non-exhaustive hint alongside permission-agnostic guidance (the complete set -// needs a folder-listing tool — follow-up). +// model can pick an `f/<folder>/...` path without a discovery round-trip. For a +// non-admin, `folders` (from whoami) is exactly the writable set, so read-only +// folders are listed separately as off-limits. Admins bypass folder ACLs and can +// write anywhere, but `folders` only carries their explicitly-permissioned subset, +// so for admins it is a non-exhaustive hint and list_workspace_items has the rest. // Capped so a folder-heavy workspace can't dominate the prompt. function buildFolderGuidance( username: string, @@ -1360,7 +1441,7 @@ function buildFolderGuidance( if (ctx.isAdmin) { const known = writable.length > 0 - ? ` Folders here include ${fmt(writable)} (you can also write to others not listed).` + ? ` Folders here include ${fmt(writable)} (you can also write to others not listed; list_workspace_items with type "folder" lists them all).` : '' return `- As a workspace admin you can write to any existing folder.${known} If the user names a folder, use it;${canCreateFolder ? ' if they explicitly ask for a new folder, create it with `create_folder`;' : ''} otherwise ask them which folder to use rather than guessing${canCreateFolder ? ' or creating one unprompted' : ''}.` } @@ -1392,6 +1473,9 @@ function buildFolderGuidance( return lines.join('\n') } +const listJoin = (items: (string | false)[], type: 'conjunction' | 'disjunction' = 'conjunction') => + new Intl.ListFormat('en', { type }).format(items.filter((i): i is string => !!i)) + const buildGlobalSystemPrompt = ( username: string, previewTools: boolean, @@ -1403,14 +1487,74 @@ const buildGlobalSystemPrompt = ( // Each `can*` mirrors the capability the matching tools declare in `requires`, so a // rule cannot outlive the tool it describes. An unresolved profile keeps every block. const canWriteDraft = !access || access.has('write_draft') + const canWriteFlowDraft = !access || access.has('write_flow_draft') + const canWriteAppDraft = !access || access.has('write_app_draft') + const canDraftSchedules = !access || access.has('write_schedule_draft') + const canDraftTriggers = !access || access.has('write_trigger_draft') + const canDraftResources = !access || access.has('write_resource_draft') + const canDraftVariables = !access || access.has('write_variable_draft') + // A builder operator: drafts of the kinds the workspace lets them compose, and nothing else. + // Blocks about drafting in general follow `canWriteAnyDraft`; blocks naming scripts or the + // other kinds keep `canWriteDraft`. + const buildsFlows = canWriteFlowDraft && !canWriteDraft + const buildsApps = canWriteAppDraft && !canWriteDraft + const canWriteAnyDraft = + canWriteDraft || + canWriteFlowDraft || + canWriteAppDraft || + canDraftSchedules || + canDraftTriggers || + canDraftResources || + canDraftVariables + const canDeploy = !access || access.has('deploy') + // Whether deploy_workspace_item and delete_workspace_item keep any kind: only schedules and + // triggers skip the deploy rules, and an admin passes them. + const canDeployAnyKind = + canDeploy || access.has('manage_schedules') || access.has('manage_triggers') + // These read only where `write_draft` is missing: it implies the other draft rights. + const draftedKinds = [ + canDraftResources && 'resources', + canDraftVariables && 'variables', + canDraftSchedules && 'schedules', + canDraftTriggers && 'triggers' + ].filter((k): k is string => !!k) + const draftedOperatorKinds = listJoin(draftedKinds) + // Resources and variables deploy under the rules; schedules and triggers under the right + // that also lets them be drafted. + const deployableKinds = draftedKinds.filter( + (k) => canDeploy || k === 'schedules' || k === 'triggers' + ) + const refusedKinds = [ + !buildsFlows && 'flows', + 'scripts', + !buildsApps && 'apps', + !canDraftSchedules && 'schedules', + !canDraftTriggers && 'triggers', + !canDraftResources && 'resources', + !canDraftVariables && 'variables' + ].filter((k): k is string => !!k) + const refusedCode = ['scripts', !buildsFlows && 'flows', !buildsApps && 'apps'].filter( + (k): k is string => !!k + ) const canRunPreview = !access || access.has('run_preview') - // The deploy tools take their kind as an argument, so `deploy` gates only the folder text. + const canManageSchedules = !access || access.has('manage_schedules') + const canManageTriggers = !access || access.has('manage_triggers') + // The deploy tools take their kind as an argument, so `deploy` gates only the folder and + // resource type text. const canCreateFolder = !access || access.has('deploy') + const canCreateResourceType = !access || access.has('deploy') // Each gated block carries its own leading newline, so dropping one leaves no blank // line behind and a full-access prompt is byte-for-byte the ungated text. const when = (cond: boolean, block: string) => (cond ? block : '') const folderGuidance = buildFolderGuidance(username, folderCtx, canCreateFolder) const folderGuidanceBlock = folderGuidance ? `\n${folderGuidance}` : '' + // A grant to `g/<group>` reaches the user only through membership, which no permission + // list shows. Outside the folder guidance, which a role that cannot draft never gets. + const memberOf = (folderCtx?.groups ?? []).filter((g) => g !== 'all') + const groupMembershipRule = + memberOf.length > 0 + ? `- The user is a member of ${memberOf.map((g) => `\`g/${g}\``).join(', ')}, so a grant to one of those groups is a grant to them.\n` + : '' // `previewTools` doubles as "this is a session chat" — sessions are the only // chats that get the preview tool set. The alpha heads-up only makes sense // there, where the chat actively builds the pipeline on the canvas; the @@ -1424,7 +1568,17 @@ const buildGlobalSystemPrompt = ( const activePreviewRule = previewTools ? '\n- If the user message includes an ACTIVE PREVIEW section, that is the page the side panel is showing — resolve "this page", "here" and "it" against it, and against `open` (the item the user has open in its editor) when there is one. It already tells you what get_preview_status would, so do not call that tool to learn what is on screen; call it only to check the panel\'s *other* tabs.' : '' - const pipelineBullet = `- A "data pipeline" is NOT a flow: it is a DAG of independent scripts in one folder, wired by storage assets (DuckLake/data tables/S3) and triggers via top-of-file \`pipeline\` / \`on <ref>\` annotation comments written in each script's comment syntax (\`--\` for SQL, \`#\` for Python/Bash, \`//\` for TS — a \`//\` line in a SQL node is a syntax error). When the user asks for a data pipeline (or to ingest/transform/materialize data across steps), call get_instructions with subject "pipeline" and build annotated script drafts — do not build a flow.${pipelineAlphaNote}` + const pipelineBullet = `- A "data pipeline" is NOT a flow: it is a DAG of independent scripts in one folder, wired by storage assets (DuckLake/data tables/S3) and triggers via top-of-file \`pipeline\` / \`on <ref>\` annotation comments written in each script's comment syntax (\`--\` for SQL, \`#\` for Python/Bash, \`//\` for TS — a \`//\` line in a SQL node is a syntax error). When the user asks for a data pipeline (or to ingest/transform/materialize data across steps), call get_instructions with subject "pipeline" and build annotated script drafts — do not build a flow. list_pipelines lists the existing ones by folder.${pipelineAlphaNote}` + // Roles need a self-hosted Enterprise Edition. The edition is knowable only in the browser, + // so elsewhere the guidance stays and nothing is claimed about the instance. + const datatableRolesAvailable = !isCloudHosted() && (!BROWSER || !!get(enterpriseLicense)) + const datatableRolesBullet = datatableRolesAvailable + ? ` +- A datatable can be under roles; list_datatables then reports its \`usable_roles\` and \`default_role\`. When working on a raw app that pins a role (\`data.roles\` in its raw_app.yaml), pass that role to the datatable tools, and to wmill.datatable in its runnables, so you see and change only what the app itself can. For anything else about roles, grants or a \`permission denied\`, call get_instructions with subject "datatable".` + : BROWSER + ? ` +- Datatable roles and permissions are not available on this instance (they need a self-hosted Enterprise Edition): everyone who can use a datatable reaches all of it, so do not promise per-user, per-schema or per-row access on one.` + : '' // Hosting and edition come from the hostname and a store the app populates at init, so // they are knowable only in the browser: a non-browser caller reads false for both and // would be told "self-hosted Community Edition" whatever it targets. No base URL here @@ -1444,9 +1598,33 @@ The current user's workspace username is "${username}".${instanceLine} ${ canWriteDraft ? 'Use tools to inspect workspace items and create per-user drafts (saved server-side, visible only to this user — not deployed) for scripts, flows, schedules, triggers, resources, variables, and raw apps.' - : "Use tools to inspect workspace items and the workspace's run history, and to run items that are already deployed. You cannot create or edit scripts, flows, apps, schedules, triggers, resources or variables here — this user's role does not allow it — so when they ask for such a change, say plainly that you cannot make it rather than describing steps as if you had. Their role is refused scripts, flows and apps outside this chat too, so for those suggest asking a workspace admin rather than creating them in the editor." + : `Use tools to inspect workspace items and the workspace's run history, and to run items that are already deployed. You cannot create or edit ${listJoin(refusedKinds, 'disjunction')} here — this user's role does not allow it — so when they ask for such a change, say plainly that you cannot make it rather than describing steps as if you had. Their role is refused ${listJoin(refusedCode)} outside this chat too, so for those suggest asking a workspace admin, who grants operators more in ${OPERATOR_SETTINGS_LOCATION}, rather than creating them in the editor.${when( + canManageSchedules, + ' To make something recur, they can schedule a deployed script or flow themselves; only when none does the job is there something to ask an admin for, and it is that script.' + )} When you decline something, give the reason stated here and keep to it.${when( + buildsFlows, + '\n\nFlows are the exception: this workspace lets them compose flows out of scripts and flows that are already deployed. Write flow drafts with write_flow and patch_flow_json, using only steps that call a deployed script or flow by path. The server refuses inline code anywhere in the flow, so never add a rawscript step or inline code; when the flow needs logic no deployed script provides, say so and suggest asking a workspace admin for that script.' + )}${when( + buildsApps, + `\n\nRaw apps are ${buildsFlows ? 'an exception too' : 'the exception'}: this workspace lets them build raw apps whose backend calls scripts and flows that are already deployed. Call get_instructions with subject "app" first, then write app drafts with init_app and the app file and runnable tools, making every backend runnable a path runnable to a deployed script or flow. The server refuses inline and hub runnables, so never write one; when the app needs logic no deployed script provides, say so and suggest asking a workspace admin for that script. An app this user deploys always runs sandboxed, and runs its runnables as the user who deployed it: turning the sandbox off or running them as the viewer is refused. If asked, say operators cannot, because the app's code would then run with the permissions of whoever opens it.` + )}${when( + !!draftedOperatorKinds, + `\n\nThis workspace lets them create and edit ${draftedOperatorKinds}: write them as drafts with ${listJoin( + [ + canDraftResources && 'write_resource (call search_resource_types first)', + canDraftVariables && 'write_variable', + canDraftSchedules && 'write_schedule', + canDraftTriggers && + 'write_trigger (call get_trigger_schema first: the config fields differ per kind)' + ] + )}${ + deployableKinds.length + ? `, then deploy ${deployableKinds.length === draftedKinds.length ? 'them' : listJoin(deployableKinds)} with deploy_workspace_item once the user asks` + : '' + }.` + )}` }${when( - canWriteDraft, + canWriteAnyDraft, ` Path conventions: @@ -1459,42 +1637,70 @@ Path conventions: '; create one with `create_folder` only when the user explicitly asks for a new folder' )}.${folderGuidanceBlock}` )}${when( - canCreateFolder && !canWriteDraft, + canCreateFolder && !canWriteAnyDraft, '\n- You can create a shared folder with `create_folder` when the user explicitly asks for one. You cannot create anything inside it here, so do not offer to.' )} Rules:${when( - canWriteDraft, + canWriteAnyDraft, ` - Draft tools create or update drafts only; they do not deploy or mutate deployed workspace items.` )} - Use list_workspace_items to find items and read_workspace_item before changing an existing item. For triggers, pass trigger_kind. +${groupMembershipRule}- Listings and reads return only what this user can see: items in folders they cannot read are hidden from you both. When an item the user names is missing, say it is not among what they can see and may be in a folder they cannot read, where someone with access can run it — never state that it does not exist or is not deployed. +- An agent, as the Agents page lists it, is a resource of type \`ai_agent\`: read it with read_workspace_item type "resource".${when( + canDraftResources, + " You may draft a change to an agent, but never deploy or rename one here: the user reviews and deploys it from the agent's page, `/agents/edit/<path>`, so point them there." + )} - If the user message includes an ACTIVE EDITOR section, treat it as the currently open item and use it for references like "this", "current", or "open editor".${activePreviewRule}${when( - canWriteDraft, + canWriteAnyDraft && canDeployAnyKind, ` -- Use deploy_workspace_item only after the user explicitly asks to deploy. It persists a draft to the workspace. -- To undo something you created or changed in this chat, use discard_local_draft: everything you write is a draft until it is explicitly deployed, so "delete it" / "never mind" / "remove that" about your own work means discarding the draft (it also clears the matching open editor draft). Use delete_workspace_item only to remove an item that is already deployed in the workspace; it mutates the workspace and fails if nothing is deployed at that path.` +- Use deploy_workspace_item only after the user explicitly asks to deploy. It persists a draft to the workspace.` )}${when( - !canWriteDraft, + canWriteAnyDraft, ` -- Three changes are still open to you where the server allows them: discard_local_draft drops a draft this user left behind, deploy_workspace_item deploys one when the user asks, and delete_workspace_item removes an item already deployed in the workspace. You cannot create or edit one.` +- To undo something you created or changed in this chat, use discard_local_draft: everything you write is a draft until it is explicitly deployed, so "delete it" / "never mind" / "remove that" about your own work means discarding the draft (it also clears the matching open editor draft).${when( + canDeployAnyKind, + ' Use delete_workspace_item only to remove an item that is already deployed in the workspace; it mutates the workspace and fails if nothing is deployed at that path.' + )}` + )}${when( + !canWriteAnyDraft, + ` +- Three changes are still open to you where the server allows them: discard_local_draft drops a draft this user left behind, deploy_workspace_item deploys one when the user asks, and delete_workspace_item removes an item already deployed in the workspace — each only for the kinds its type lists. You cannot create or edit one.` + )}${when( + !canManageSchedules || !canManageTriggers, + ` +- This workspace does not let this user change ${ + !canManageSchedules && !canManageTriggers + ? 'schedules or triggers' + : !canManageSchedules + ? 'schedules' + : 'triggers' + }, here or in the editor, so never ask them to create or edit one: suggest asking a workspace admin.` )} - Use diff to review changes — before deploying, or when the user asks what changed. It is read-only: without arguments it lists every draft in the workspace with its change status; with type+path it returns that item's unified diff (for multi-file apps, pass file to read one file's diff). In a fork, pass against="parent_workspace" to compare the deployed fork with its parent workspace instead. Pass search to grep changed lines across all diffs.${when( + canDraftVariables, + ` +- You can never read a variable's value, secret or not, so never invent one: when editing an existing variable, omit value (and is_secret) from write_variable and pass only the fields you are actually changing. The user can reveal a value in the variable editor; you cannot, so never tell them a value is unreadable in general. "$var:path/to/variable" is how a resource value references a variable — it is never a variable's own value.` + )}${when( canWriteDraft, ` -- You can never read a variable's value, secret or not, so never invent one: when editing an existing variable, omit value (and is_secret) from write_variable and pass only the fields you are actually changing. The user can reveal a value in the variable editor; you cannot, so never tell them a value is unreadable in general. "$var:path/to/variable" is how a resource value references a variable — it is never a variable's own value. - Use search_resource_types before write_resource, and get_trigger_schema before write_trigger: the trigger config fields differ per kind and are not listed in the write_trigger definition. - When script or raw app code needs an external npm package you are not fully familiar with, use search_npm_packages to find it and get its documentation and type definitions. Link the package documentation in your answer when you rely on it. - Hub scripts are prebuilt, vetted integrations for third-party services, hosted outside the workspace under \`hub/<version>/<app>/<name>\` paths. Check search_hub_scripts before hand-writing code against a third-party API, even when the user never mentions the hub; read a result with read_workspace_item type "script" and its hub path to get its code, language, and input schema. Use what you find in whichever way fits: reference the hub path directly from a flow module or app runnable when a script already does the job, copy it into a workspace draft and adapt it when it is close (note the source hub path in a comment at the top of the code), or take it as a worked example and write your own. A script that does not do what the user asked is still worth reading when it is the only example of that integration: pass its \`integration\` back to search_hub_scripts to list that integration's other scripts with their descriptions, or use the \`suggested_integrations\` a search hands back when it finds nothing. - Before writing your own code against an integration the hub covers, call get_hub_integration with its slug: it returns the resource type to take, its auth fields and the integration's most-used scripts, which beats inferring them from script bodies. Call it for the integration you are about to write against, whichever it is. A search marks an integration \`documented\` when the hub additionally holds provider knowledge checked against the live API — pagination, enums, error codes and gotchas — so read that closely where it appears rather than trusting your own memory of the API. - If you have a web search tool and the hub does not cover a third-party API, search for the vendor's own API documentation rather than writing its endpoints and auth from memory, and link the page you relied on. Reserve it for external APIs: search_docs answers questions about Windmill itself. -${when(canRunPreview, '- Use get_db_schema with a database resource path to fetch its tables and columns before writing SQL (or a script querying that database).\n')}- Use get_instructions before writing scripts, flows, resources, or apps. For scripts, pass the target language. +${when(canCreateResourceType, '- create_resource_type creates a resource type the workspace lacks. The user confirms the schema in the call itself, so that is where you propose it rather than asking first in chat.\n')}${when(!canCreateResourceType, '- This user cannot create a resource type here, in chat or on the Resources page, since the workspace refuses their direct deployment: when one is needed, give them its name and JSON Schema to pass to a workspace admin, who can add it.\n')}${when(canRunPreview, '- Use get_db_schema with a database resource path to fetch its tables and columns before writing SQL (or a script querying that database).\n')}- Use get_instructions before writing scripts, flows, resources, or apps. For scripts, pass the target language. ${pipelineBullet}` )}${when( canRunPreview && canWriteDraft, ` - After creating or editing a script or flow draft, run test_run_script, test_run_flow, or test_run_step with representative args before reporting that it works. These tools prefer drafts, so testing does not require deployment. - Do the same for a raw app: run test_run_app_runnable on each backend runnable you wrote or changed before saying the app works. A bundle that compiles proves nothing about whether the runnables run. An inline runnable executes the app's draft code; a path runnable executes the DEPLOYED script/flow it names, so a path runnable aimed at something you have not deployed fails here — that failure is the point: report it and offer to deploy that one target. The app itself does not need deploying to be tested.` + )}${when( + buildsFlows && (!access || access.has('run_flow_preview')), + ` +- After creating or editing a flow draft, run test_run_flow with representative args before reporting that it works. It prefers drafts, so testing does not require deployment.` )} - Use list_runs to find recent runs (optionally filtered by path, creator, label, or status), then get_run with a returned id to see what that run was called with, what it returned and what it logged — without starting a new test run. - get_run also covers what a flow run did per step — statuses and results across the whole execution tree, subflow steps and loop iterations included — and works while the flow is still running. Pass step to read one step's result in full (capped at 12k chars). @@ -1519,12 +1725,18 @@ ${pipelineBullet}` ? `${when( !canWriteDraft, ` -- open_preview(kind, path) shows a deployed script / flow / app in the side panel next to the chat — its run form, triggers and past runs, which the user can act on there. Use it when you surface an item they will want to run or inspect. You cannot open item editors in this workspace, so it only ever opens the deployed page.` +- open_preview(kind, path) shows a deployed script / flow / app in the side panel next to the chat — its run form, triggers and past runs, which the user can act on there. Use it when you surface an item they will want to run or inspect. ${ + buildsFlows && buildsApps + ? 'The flow and app editors are the only editors you can open here: after writing or editing a flow or app draft, show it with open_preview(kind="flow" or "raw_app", path, mode="edit").' + : buildsFlows || buildsApps + ? `The ${buildsFlows ? 'flow' : 'app'} editor is the only editor you can open here: after writing or editing ${buildsFlows ? 'a flow' : 'an app'} draft, show it with open_preview(kind="${buildsFlows ? 'flow' : 'raw_app'}", path, mode="edit").` + : 'You cannot open item editors in this workspace, so it only ever opens the deployed page.' + }` )}${when( canWriteDraft, ` - After writing or substantially editing a script / flow / app draft, show it via open_preview(kind, path) so the user sees the editor and live preview right next to the chat. First check whether it is already shown: if unsure, call get_preview_status. Only call open_preview (or offer to) when no preview is open or it is showing a different item — don't re-open a preview already showing the item you just edited. -- Building a data pipeline: call open_preview(kind="pipeline", path="<folder>") as the FIRST step, before creating any node — this opens the pipeline editor the user reviews in. path is the folder, not an item; an empty ${when(canCreateFolder, 'or not-yet-created ')}folder is fine${when(canCreateFolder, ' (create_folder first if needed, then open it)')}. Opening it registers build_pipeline_node / edit_pipeline_node — use ONLY those to add or change pipeline nodes, never write_script for a pipeline node — they apply directly as unsaved drafts on the canvas (no separate accept/reject step) that the user reviews and deploys. Do not write pipeline scripts without first opening the editor.` +- Building a data pipeline: call open_preview(kind="pipeline", path="<folder>") as the FIRST step, before creating any node — this opens the pipeline editor the user reviews in. path is the folder, not an item; an empty ${when(canCreateFolder, 'or not-yet-created ')}folder is fine${when(canCreateFolder, ' (create_folder first if needed, then open it)')}. Opening it adds build_pipeline_node / edit_pipeline_node to your tools from the next step on — they are not in your tool list before open_preview returns, so call open_preview on its own, wait for its result, then build. They then stay available for the rest of the session even while another tab (a page, another preview) is shown: a call brings the pipeline editor back by itself, so do not re-open it first. Use ONLY those to add or change pipeline nodes, never write_script for a pipeline node — they apply directly as unsaved drafts on the canvas (no separate accept/reject step) that the user reviews and deploys. Do not write pipeline scripts without first opening the editor.` )} - When debugging a running raw app, call get_app_runtime_logs to read the live preview's browser console output. It needs the raw app preview open (open_preview kind="raw_app"). - Writing an app file does not compile it: the open preview rebuilds it afterwards. After editing a raw app's frontend files with its preview open, call get_app_runtime_logs to check the build — when it failed, it returns the build errors (e.g. syntax or import errors) and bundler logs to fix. @@ -1551,7 +1763,7 @@ Documentation: Flows: - read_workspace_item returns compact flow JSON. Inline script bodies appear as "inline_script.<moduleId>". - Use read_flow_module_code${when(canWriteDraft, ' and set_flow_module_code')} for inline script bodies.${when( - canWriteDraft, + canWriteFlowDraft, ` - Use patch_flow_json for structural flow edits and write_flow for full flow rewrites.` )} @@ -1559,12 +1771,16 @@ Flows: Raw apps: - The app tools below only work on raw (code) apps. \`rawApp\` says which: false is a drag-and-drop app: you can list it and read its metadata, but not read its contents, edit it or deploy it. Check it before offering to change an app. - read_workspace_item returns app metadata only. Use read_app_file for file and inline runnable contents.${when( - canWriteDraft, + canWriteAppDraft, ` - A draft app is reachable by nobody; deploying is what exposes its backend runnables. deploy_workspace_item says so when the deploy widens who may open the app: anonymous means anyone with the URL, without logging in; guest means anyone the instance's identity provider authenticates, member of this workspace or not. Relay that in plain words and carry on. This is disclosure, not a gate: do not stop and ask for permission, and do not refuse the deploy. You cannot change who may open an app from chat; it is set on the app's deploy settings. - Use write_app_file, patch_app_file, and delete_app_file for frontend files. - Use write_app_runnable and delete_app_runnable for backend runnables. -- Use init_app for a new app, with framework react19 unless the user named one or points at an app to follow: do not ask about the framework, and write the summary and pick the path (path conventions above) yourself. When the app has to store data and the user did not say where, settle the data setup with askUserQuestion BEFORE init_app or any SQL (get_instructions subject "app" lists the questions, one askUserQuestion each), then pass the outcome as init_app's data. +- Use init_app for a new app, with framework react19 unless the user named one or points at an app to follow: do not ask about the framework, and write the summary and pick the path (path conventions above) yourself. ${ + buildsApps + ? 'An app this user builds reads and stores data only through the deployed runnables it calls: do not ask about a data setup or pass init_app a data config.' + : 'When the app has to store data and the user did not say where, settle the data setup with askUserQuestion BEFORE init_app or any SQL (get_instructions subject "app" lists the questions, one askUserQuestion each), then pass the outcome as init_app\'s data.' + } - Use deploy_workspace_item after explicit user deploy intent; raw app deploy bundles JS/CSS before saving.` )} @@ -1574,13 +1790,9 @@ Data Tables: - Use get_datatable_table_schema only when you need a table's column names/types; list_datatables is enough for table-list or availability summaries.${when( canRunPreview, ` -- Use exec_datatable_sql to explore data, run queries, mutate rows, or change schema (CREATE/ALTER/DROP). Creating a table is a normal CREATE TABLE statement — it appears in list_datatables afterward, with no registration step.` - )}${ - isCloudHosted() - ? '' - : ` -- A raw app may use a datatable through a role (\`data.roles\` in its raw_app.yaml). When working on such an app, pass that role to the datatable tools, and to wmill.datatable in its runnables, so you see and change only what the app itself can.` - }${when( +- Use exec_datatable_sql to explore data, run queries, mutate rows, or change schema (CREATE/ALTER/DROP). Creating a table is a normal CREATE TABLE statement — it appears in list_datatables afterward, with no registration step. +- A datatable that list_datatables reports with \`migrations_enabled\` keeps its schema as versioned migrations: change its schema with create_datatable_migration, never exec_datatable_sql. list_datatable_migrations reads them, run_datatable_migrations applies what is pending, rollback_datatable_migration undoes one. A migration is applied for real, not drafted, so call get_instructions with subject "datatable" before your first one.` + )}${datatableRolesBullet}${when( canWriteDraft, ` - When writing runnable code (inline app runnables, scripts, flow modules) that reads or writes datatable data at runtime, it accesses a datatable via wmill.datatable(). Default to TypeScript (bun) unless the user asked for another language. Call get_instructions with subject "datatable" and language "bun" for the TypeScript SQL SDK reference (or language "python3" for Python) — it returns only that language so you get just what you need.` @@ -1663,6 +1875,7 @@ function serializeWorkspaceItemForRead(item: WorkspaceItem): unknown { path: item.path, summary: item.summary, isSecret: item.isSecret, + extraPerms: item.extraPerms, isDraft: item.isDraft } } @@ -1680,6 +1893,7 @@ function serializeWorkspaceItemForRead(item: WorkspaceItem): unknown { value: summarizeAppValue(item.value as AppDraftValue), rawApp: item.rawApp, executionMode: item.executionMode, + extraPerms: item.extraPerms, isDraft: item.isDraft } } @@ -1693,6 +1907,7 @@ function serializeWorkspaceItemForRead(item: WorkspaceItem): unknown { path: item.path, summary: item.summary, value: editable, + extraPerms: item.extraPerms, isDraft: item.isDraft } } @@ -1765,6 +1980,7 @@ function convertPersistedToBackendRunnable( content: persisted.inlineScript.content ?? '' } } + if (persisted.viewer_data_access === true) out.viewerDataAccess = true } else if (persisted.type === 'path' || persisted.type === 'runnableByPath') { if (persisted.runType === 'flow') out.type = 'flow' else if (persisted.runType === 'hubscript') out.type = 'hubscript' @@ -1802,7 +2018,14 @@ function buildPersistedRunnable( // `type` (isRunnableByName / isRunnableByPath), so a leftover does not change which code // runs — it contradicts it: a runnable reported back as inline still names a flow in // `path`, and that is what the model reads on its next turn. - const { runType: _runType, path: _path, inlineScript: _inlineScript, ...carried } = existing ?? {} + const { + runType: _runType, + path: _path, + inlineScript: _inlineScript, + viewer_data_access: carriedAsViewer, + ...carried + }: Partial<PersistedRunnable> = existing ?? {} + const viewerDataAccess = input.viewerDataAccess ?? carriedAsViewer === true // `schema` describes the item a path runnable points at, so it only survives while that // target is unchanged. Carried across a retarget it types `backend.<key>(args)` from the @@ -1824,6 +2047,7 @@ function buildPersistedRunnable( content: input.inlineScript.content, language: input.inlineScript.language }, + ...(viewerDataAccess && { viewer_data_access: true }), fields } } @@ -2016,6 +2240,11 @@ async function saveAppDraft( path: string, value: AppDraftValue ): Promise<DraftPersistResult> { + if (operatorBuilderAppsIn(workspace)) { + const role = await roleForWorkspace(workspace) + value.policy ??= {} + conformBuilderAppPolicy(value.policy, role.kind === 'resolved' ? role.user : undefined) + } return saveGlobalAppDraft(workspace, path, value) } @@ -2201,34 +2430,43 @@ async function readWorkspaceItem( getDraft: !deployedOnly }) const draft = deployedOnly ? undefined : (script.draft as Script | undefined) - return scriptToItem(draft ?? script, true) + return { ...scriptToItem(draft ?? script, true), extraPerms: script.extra_perms } } case 'flow': { // Prefer the DB draft (newer than the deployed version) when one exists, // unless the caller explicitly asked for the deployed state. const flow = await FlowService.getFlowByPath({ workspace, path, getDraft: !deployedOnly }) const draft = deployedOnly ? undefined : (flow.draft as Flow | undefined) - return flowToItem(draft ?? flow, true) + return { ...flowToItem(draft ?? flow, true), extraPerms: flow.extra_perms } } - case 'schedule': - return scheduleToItem(await ScheduleService.getSchedule({ workspace, path }), true) - case 'trigger': + case 'schedule': { + const schedule = await ScheduleService.getSchedule({ workspace, path }) + return { ...scheduleToItem(schedule, true), extraPerms: schedule.extra_perms } + } + case 'trigger': { if (!triggerKind) { throw new Error('trigger_kind is required when type is trigger.') } - return triggerToItem( - triggerKind, - await triggerServices[triggerKind].get({ workspace, path }), - true - ) - case 'resource': - return resourceToItem(await ResourceService.getResource({ workspace, path }), true) - case 'variable': + const trigger = await triggerServices[triggerKind].get({ workspace, path }) + return { + ...triggerToItem(triggerKind, trigger, true), + extraPerms: (trigger as { extra_perms?: Record<string, boolean> }).extra_perms + } + } + case 'resource': { + const resource = await ResourceService.getResource({ workspace, path }) + return { ...resourceToItem(resource, true), extraPerms: resource.extra_perms } + } + case 'variable': { // Never expose the value, even when read directly. Pass decryptSecret=false // to avoid materializing secret values server-side. - return variableToItem( - await VariableService.getVariable({ workspace, path, decryptSecret: false }) - ) + const variable = await VariableService.getVariable({ + workspace, + path, + decryptSecret: false + }) + return { ...variableToItem(variable), extraPerms: variable.extra_perms } + } case 'app': { // Returns lightweight metadata only — file/runnable contents come via read_app_file. const app = await AppService.getAppByPath({ workspace, path }) @@ -2242,6 +2480,7 @@ async function readWorkspaceItem( summary: app.summary, rawApp: false, executionMode, + extraPerms: app.extra_perms, isDraft: false } } @@ -2254,12 +2493,78 @@ async function readWorkspaceItem( value: metadata as unknown as AppDraftValue, rawApp: app.raw_app, executionMode, + extraPerms: app.extra_perms, isDraft: false } } } } +// Accepts the `f/<name>` / `g/<name>` form the model sees in extra_perms keys and paths. +function accessEntityName(type: AccessType, path: string): string { + const prefix = type === 'folder' ? 'f/' : 'g/' + const name = path.startsWith(prefix) ? path.slice(prefix.length) : path + return name.replace(/\/+$/, '') +} + +async function readAccessEntity(type: AccessType, path: string, workspace: string) { + const name = accessEntityName(type, path) + if (type === 'folder') { + const folder = await FolderService.getFolder({ workspace, name }) + return { + type, + name: folder.name, + summary: folder.summary, + owners: folder.owners, + extraPerms: folder.extra_perms, + defaultPermissionedAs: folder.default_permissioned_as + } + } + const group = await GroupService.getGroup({ workspace, name }) + return { + type, + name: group.name, + summary: group.summary, + members: group.members, + extraPerms: group.extra_perms + } +} + +type AccessEntityRow = { + type: AccessType + path: string + summary?: string + owners?: string[] + extraPerms?: Record<string, boolean> +} + +// Group rows omit members: the list endpoint does not return them. +async function listAccessEntities( + types: AccessType[], + workspace: string, + perPage: number, + page?: number +): Promise<AccessEntityRow[]> { + const rows: AccessEntityRow[] = [] + if (types.includes('folder')) { + for (const f of await FolderService.listFolders({ workspace, perPage, page })) { + rows.push({ + type: 'folder', + path: f.name, + summary: f.summary, + owners: f.owners, + extraPerms: f.extra_perms + }) + } + } + if (types.includes('group')) { + for (const g of await GroupService.listGroups({ workspace, perPage, page })) { + rows.push({ type: 'group', path: g.name, summary: g.summary, extraPerms: g.extra_perms }) + } + } + return rows +} + async function listWorkspaceItems( types: WorkspaceItemType[], workspace: string, @@ -2379,7 +2684,10 @@ function getScriptInstructions(language: ScriptLang | undefined): string { ${getScriptPrompt(selected)}` } -async function getFlowInstructions(workspace: string | undefined): Promise<string> { +async function getFlowInstructions( + workspace: string | undefined, + composeOnly: boolean +): Promise<string> { const aiAgentProviders = formatAiAgentProvidersPrompt( await getAiAgentProviderCatalog(workspace), { @@ -2395,15 +2703,22 @@ async function getFlowInstructions(workspace: string | undefined): Promise<strin - Top-level flow settings appear as top-level keys of the compact flow value and can be added, edited, or removed with \`patch_flow_json\`: ${FLOW_VALUE_SETTINGS_KEYS.join(', ')}. For example, \`chat_input_enabled: true\` marks a flow as chat-style (flow-as-chat); keep it intact when restructuring such a flow. - \`modules\` contains normal sequential modules. Use top-level \`preprocessor_module\` and \`failure_module\` for special modules; do not put \`preprocessor\` or \`failure\` in \`modules\`. - Every module needs a stable unique \`id\` and a useful \`summary\` when the schema supports it. -- Prefer path/script/flow modules when composing existing workspace logic. Use rawscript modules only when new inline code is needed. -- When writing rawscript module code, call \`get_instructions\` with \`subject: "script"\` and the rawscript language first. +${ + composeOnly + ? '- Compose only path modules (`script` / `flow`) that reference items already deployed in the workspace. Rawscript modules and hub scripts are refused for this user.' + : `- Prefer path/script/flow modules when composing existing workspace logic. Use rawscript modules only when new inline code is needed. +- When writing rawscript module code, call \`get_instructions\` with \`subject: "script"\` and the rawscript language first.` +} ## Groups and notes - Add \`groups\` to any non-trivial flow without being asked; "Organizing Flows: Groups and Notes" in the reference below gives the fields and the rules the editor enforces. Pass \`null\` to \`write_flow\` to clear them, and the same for \`notes\`. - With \`patch_flow_json\`, edit \`groups\` and \`notes\` the same way as any other field — they appear as top-level keys in the compact flow value. -## Compact view: how rawscript bodies surface in tool I/O +${ + composeOnly + ? '' + : `## Compact view: how rawscript bodies surface in tool I/O - \`read_workspace_item\` and \`patch_flow_json\` operate on a **compact view** of the flow: every rawscript module's \`value.content\` is replaced with the placeholder \`"inline_script.<moduleId>"\` so inline script bodies don't bloat tool I/O. Schema, groups, notes, preprocessor_module and failure_module are all shown in this view. - Inline rawscript content is **not** part of the JSON \`patch_flow_json\` sees. Edits to inline bodies happen via dedicated tools: @@ -2414,15 +2729,16 @@ async function getFlowInstructions(workspace: string | undefined): Promise<strin - \`write_flow\` is for full overwrites / create-from-scratch. Its \`modules\`, \`preprocessor_module\`, and \`failure_module\` arguments are **non-compact** flow modules: inline each rawscript body directly in \`content\` by default. But if a body is long or quote/backslash-heavy enough that escaping it into the JSON string is error-prone — or if a \`write_flow\` call comes back with a JSON parse error — create that module with **empty content** (\`"content": ""\`) and fill it with \`set_flow_module_code(path, module_id, code)\`, whose \`code\` is a plain argument with no nested escaping. \`write_flow\` reports which modules still have empty bodies so you know what to fill. - When overwriting an **existing** flow, set \`"content": "inline_script.<moduleId>"\` on any rawscript module whose code you are not changing — the placeholder resolves to that module's current body, so you never re-send (or re-read) unchanged code. Placeholders that match no existing rawscript module and are not the module's own id are rejected. -${aiAgentProviders ? `\n${aiAgentProviders}\n` : ''} +` +}${aiAgentProviders ? `\n${aiAgentProviders}\n` : ''} # Windmill flow authoring reference -${getFlowPrompt()}` +${composeOnly ? 'This reference is written for every author. For this user, skip what it says about inline code (rawscript steps, inline AI agent tools) and hub scripts: the server refuses them. Compose only path steps that reference deployed scripts and flows.\n\n' : ''}${getFlowPrompt()}` } type InstructionSubject = (typeof ALL_INSTRUCTION_SUBJECTS)[number] -function getAppInstructions(language?: ScriptLang): string { +function getAppInstructions(language: ScriptLang | undefined, composeOnly: boolean): string { // getRawAppPrompt swaps in the Python SDK for python3, so the pointer has to swap with // it: telling the model to re-fetch a reference it is already holding wastes a turn, and // naming the wrong SDK contradicts the text right below the sentence. @@ -2434,21 +2750,40 @@ function getAppInstructions(language?: ScriptLang): string { - Global mode edits raw app drafts only; it does not save or deploy unless the user explicitly asks to deploy. - App drafts are addressed by workspace path. Follow the path conventions in the system prompt: default to \`u/<current-user>/<name>\` for bare names; only use \`f/<folder>/<name>\` when the folder is known to exist. The first write tool snapshots the workspace app onto the draft, and subsequent writes accumulate. -- To create a new app, use \`init_app\` with a path, optional summary, a framework (\`react19\` / \`react18\` / \`svelte5\` / \`vue\`) and, for an app that stores data, its \`data\` setup. "Starting a new app" below decides the framework and when the data setup is asked. Ask each of its questions with \`askUserQuestion\`, one question per call with the suggested answer first, before \`init_app\` and before any SQL. \`init_app\` only records \`data\`: a new schema is yours to create with the datatable SQL tool. \`init_app\` errors if an app already exists at the path or a draft is already in flight; in that case, edit the existing one rather than re-initializing. -- \`init_app\` seeds a starter inline runnable named \`a\` (bun, \`main(x: string) => string\`) so the React/Svelte demo button works on first render. Replace or remove it once you start building real backend runnables. +- To create a new app, use \`init_app\` with a path, optional summary, a framework (\`react19\` / \`react18\` / \`svelte5\`)${ + composeOnly + ? '. "Starting a new app" below decides the framework. No data setup: the app reads and stores data only through the deployed runnables it calls.' + : ' and, for an app that stores data, its `data` setup. "Starting a new app" below decides the framework and when the data setup is asked. Ask each of its questions with `askUserQuestion`, one question per call with the suggested answer first, before `init_app` and before any SQL. `init_app` only records `data`: a new schema is yours to create with the datatable SQL tool.' + } \`init_app\` errors if an app already exists at the path or a draft is already in flight; in that case, edit the existing one rather than re-initializing. +${ + composeOnly + ? '- `init_app` starts from a static page with no backend runnables.' + : `- \`init_app\` seeds the starter inline runnables ${Object.keys(STARTER_RUNNABLES) + .map((k) => `\`${k}\``) + .join( + ', ' + )} so the demo tour works on first render. Replace or remove them once you start building real backend runnables.` +} - Frontend file paths start with \`/\` (e.g. \`/index.tsx\`, \`/App.tsx\`, \`/styles.css\`). Use \`write_app_file\` / \`patch_app_file\` / \`delete_app_file\`. -- Backend inline runnables are addressed as \`backend/<key>/main.{ts|py}\` from the file tools, but you create or update them via \`write_app_runnable\` / \`delete_app_runnable\` (which take the runnable shape directly: \`{ name, type, inlineScript?, path?, staticInputs? }\`). -- \`/wmill.d.ts\` (or \`wmill.ts\`) is generated automatically from the backend runnables — never write it directly. -- Inline runnables only support \`bun\` or \`python3\` in chat. Path runnables (\`script\`/\`flow\`/\`hubscript\`) reference an existing item. +${ + composeOnly + ? '- Every backend runnable is a path runnable (`script` / `flow`) referencing an item already deployed in the workspace, created with `write_app_runnable` and removed with `delete_app_runnable`. Inline and hub runnables are refused for this user.' + : `- Backend inline runnables are addressed as \`backend/<key>/main.{ts|py}\` from the file tools, but you create or update them via \`write_app_runnable\` / \`delete_app_runnable\` (which take the runnable shape directly: \`{ name, type, inlineScript?, path?, staticInputs? }\`).` +} +- \`/wmill.d.ts\` (or \`wmill.ts\`) is generated automatically from the backend runnables — never write it directly.${ + composeOnly + ? '' + : ` +- Inline runnables only support \`bun\` or \`python3\` in chat. Path runnables (\`script\`/\`flow\`/\`hubscript\`) reference an existing item.` + } - When a path runnable points at a draft (see "Draft code vs deployed code" below), offer to deploy just that flow/script with deploy_workspace_item, not through the compare page. -${sdkLine} -- Use \`deploy_workspace_item\` after explicit user deploy intent. The deploy tool bundles JS/CSS before saving the raw app. +${composeOnly ? '' : `${sdkLine}\n`}- Use \`deploy_workspace_item\` after explicit user deploy intent. The deploy tool bundles JS/CSS before saving the raw app. - Use \`read_workspace_item\` with \`type: 'app'\` for a metadata summary (file paths and runnable list, no contents). Use \`read_app_file\` to read an individual file; large files are truncated to a head slice, so pass \`offset\`/\`limit\` to page through the rest rather than re-reading the whole file. - To find where a symbol or string lives across the app, call \`search_app\` (greps every frontend file and inline runnable, returns matching \`file:line\` rows) instead of reading files one by one — then \`read_app_file\` only the ranges you need. The loop is list (\`read_workspace_item\`) → locate (\`search_app\`) → inspect (\`read_app_file\` with \`offset\`/\`limit\`). # Windmill raw app authoring reference -${getRawAppPrompt(language)}` +${composeOnly ? 'This reference is written for every author. For this user, skip what it says about inline runnables, hub scripts and the data setup: the server refuses inline and hub runnables. Every runnable is a path runnable referencing a deployed script or flow.\n\n' : ''}${getRawAppPrompt(language)}` } function getResourceInstructions(): string { @@ -2471,7 +2806,9 @@ ${getResourcePrompt()}` function getDatatableInstructions(language?: ScriptLang): string { // Default to the TypeScript SDK so we return only what's needed, not both. const lang = language ?? 'bun' - return `# Datatable SQL SDK reference + return `${getDatatablePrompt()} + +# Datatable SQL SDK reference Datatables are workspace-scoped managed PostgreSQL databases. In chat, explore and shape them with the datatable tools you were given. The reference below is for code you author inside runnables (inline app runnables, scripts, or flow rawscript modules) that reads or writes datatable data at runtime. @@ -2488,21 +2825,24 @@ function getPipelineInstructions(): string { function getInstructions( subject: InstructionSubject, language: ScriptLang | undefined, - workspace: string | undefined + workspace: string | undefined, + composeOnly: boolean ): string | Promise<string> { switch (subject) { case 'script': return getScriptInstructions(language) case 'flow': - return getFlowInstructions(workspace) + return getFlowInstructions(workspace, composeOnly) case 'resource': return getResourceInstructions() case 'app': - return getAppInstructions(language) + return getAppInstructions(language, composeOnly) case 'datatable': return getDatatableInstructions(language) case 'pipeline': return getPipelineInstructions() + case 'workspace_settings': + return getWorkspaceSettingsPrompt() } } @@ -2543,8 +2883,23 @@ export function getSessionContextPromptSection( // Concatenated onto an already capability-gated prompt, so it has to honour the same // profile rather than assume the gating happened upstream. const canDeploy = !access || access.has('deploy') - const canWriteDraft = !access || access.has('write_draft') - const canRunPreview = !access || access.has('run_preview') + const canWriteDraft = + !access || + access.has('write_draft') || + access.has('write_flow_draft') || + access.has('write_app_draft') || + access.has('write_schedule_draft') || + access.has('write_trigger_draft') || + access.has('write_resource_draft') || + access.has('write_variable_draft') + const canRunPreview = !access || access.has('run_preview') || access.has('run_flow_preview') + // The kinds no deploy rule reaches, unless the workspace withdrew them from this user. + const unruledKinds = [ + (!access || access.has('manage_schedules')) && 'schedules', + (!access || access.has('manage_triggers')) && 'triggers' + ].filter((k): k is string => !!k) + // With no kind left to deploy, the deploy tool is not shipped, so the lines below cannot name it. + const deployer = canDeploy || unruledKinds.length ? 'deploy_workspace_item' : 'A deploy' const targets = ['reads', canWriteDraft && 'drafts', canRunPreview && 'test runs', 'deploys'] .filter(Boolean) .join(', ') @@ -2560,19 +2915,19 @@ export function getSessionContextPromptSection( ) } else if (ctx.parentWorkspaceId && ctx.isDevWorkspace) { lines.push( - `- Operating workspace: "${ctx.workspaceId}" — the user's persistent DEV WORKSPACE, forked from workspace "${ctx.parentWorkspaceId}". deploy_workspace_item publishes into the dev workspace only; the user reviews & promotes changes into "${ctx.parentWorkspaceId}" from the session's deploy panel. Never present a change as live in "${ctx.parentWorkspaceId}".` + `- Operating workspace: "${ctx.workspaceId}" — the user's persistent DEV WORKSPACE, forked from workspace "${ctx.parentWorkspaceId}". ${deployer} publishes into the dev workspace only; the user reviews & promotes changes into "${ctx.parentWorkspaceId}" from the session's deploy panel. Never present a change as live in "${ctx.parentWorkspaceId}".` ) } else if (ctx.parentWorkspaceId) { lines.push( - `- Operating workspace: "${ctx.workspaceId}" — an ephemeral STAGED FORK of workspace "${ctx.parentWorkspaceId}", created for session work. deploy_workspace_item publishes into the fork only, and the user reviews & promotes fork changes into "${ctx.parentWorkspaceId}" from the session's deploy panel. Never present a change as live in "${ctx.parentWorkspaceId}".` + `- Operating workspace: "${ctx.workspaceId}" — an ephemeral STAGED FORK of workspace "${ctx.parentWorkspaceId}", created for session work. ${deployer} publishes into the fork only, and the user reviews & promotes fork changes into "${ctx.parentWorkspaceId}" from the session's deploy panel. Never present a change as live in "${ctx.parentWorkspaceId}".` ) } else if (ctx.forkParentUnknown) { lines.push( - `- Operating workspace: "${ctx.workspaceId}" — a fork whose parent workspace is not currently visible to this user. deploy_workspace_item publishes into the fork only; the user promotes changes from the session's deploy panel. Never present a change as live in any other workspace.` + `- Operating workspace: "${ctx.workspaceId}" — a fork whose parent workspace is not currently visible to this user. ${deployer} publishes into the fork only; the user promotes changes from the session's deploy panel. Never present a change as live in any other workspace.` ) } else if (ctx.workspaceId) { lines.push( - `- Operating workspace: "${ctx.workspaceId}" — the live workspace itself, not a fork. deploy_workspace_item publishes directly to everyone in it.` + `- Operating workspace: "${ctx.workspaceId}" — the live workspace itself, not a fork. ${deployer} publishes directly to everyone in it.` ) } else { lines.push( @@ -2583,9 +2938,20 @@ export function getSessionContextPromptSection( // promotes the rest instead. The rules gate deletes too, so it is owed to every such profile. if (!canDeploy) { lines.push( - "- This workspace refuses direct deployment for this user, except for schedules and triggers — those are the only kinds deploy_workspace_item and delete_workspace_item can still act on. Scripts, flows, apps, resources and variables must be promoted from the session's deploy panel (fork or pull request); do not offer to deploy or delete them directly." + `- This workspace refuses direct deployment for this user${ + unruledKinds.length === 2 + ? ', except for schedules and triggers — those are the only kinds deploy_workspace_item and delete_workspace_item can still act on' + : unruledKinds.length === 1 + ? `, except for ${unruledKinds[0]} — the only kind deploy_workspace_item and delete_workspace_item can still act on` + : '' + }. Scripts, flows, apps, resources and variables must be promoted from the session's deploy panel (fork or pull request); do not offer to deploy or delete them directly.` ) } + lines.push( + '- Sessions are saved: the sidebar lists them under AI Sessions, and the user can reopen any of them.', + '- The composer has a permission mode picker: Ask permission, Auto-accept edits, Yolo (bypass permissions: tool confirmations are accepted without asking) and Plan (read-only). Some modes are hidden where they do not apply.', + "- The sliders button next to the model picker opens Assistant settings. Its Permissions section shows what the user's role lets them change and what you can change for them; point them there when they ask what they are allowed to do." + ) return lines.join('\n') } @@ -2790,6 +3156,7 @@ export type GlobalPromptIdentity = { is_admin?: boolean folders?: string[] folders_read?: string[] + groups?: string[] } // `userWorkspaces` carries the real per-workspace username for every membership at no @@ -2812,7 +3179,8 @@ export async function resolveGlobalPromptIdentity( username: u.username, is_admin: u.is_admin, folders: u.folders, - folders_read: u.folders_read + folders_read: u.folders_read, + groups: u.groups } } // Headless callers (the eval harness) hold no workspace and pass their own identity. @@ -3390,7 +3758,7 @@ export const openPageTool: SessionTool<{}> = { // is no active session, in which case we offer a link chip instead. const previewResult = openPagePreview({ sessionId: sessionIdFromCtx(ctx), - href: pageHref(url), + href: url, label: pageLabel, newTab: parsed.new_tab ?? false }) @@ -3418,7 +3786,7 @@ export const globalTools: SessionTool<{}>[] = [ def: createToolDef( getInstructionsSchema, 'get_instructions', - 'Get authoring guidance for scripts, flows, data pipelines, resources, apps, or the datatable SQL SDK (wmill.datatable()) used inside runnables.' + 'Get authoring guidance for scripts, flows, data pipelines, resources, apps, or data tables: their migrations and permissions, and the SQL SDK (wmill.datatable()) used inside runnables.' ), planModeSafe: true, fn: async (ctx) => { @@ -3427,9 +3795,19 @@ export const globalTools: SessionTool<{}>[] = [ // Every subject is authoring guidance written around the draft tools by name, and a // tool result is the one place the toolset filter cannot reach. const access = (ctx.helpers as GlobalToolHelpers | undefined)?.access - if (access && !access.has('write_draft')) { + if (parsed.subject === 'workspace_settings' && access && !access.has('admin')) { + toolCallbacks.setToolStatus(toolId, { content: 'No workspace settings guidance' }) + return 'Only a workspace admin can read or change the workspace settings. Tell the user plainly that you cannot, and suggest asking a workspace admin.' + } + const canAuthor = + !access || + access.has('write_draft') || + (parsed.subject === 'flow' && access.has('write_flow_draft')) || + (parsed.subject === 'app' && access.has('write_app_draft')) || + (parsed.subject === 'resource' && access.has('write_resource_draft')) + if (!canAuthor) { const message = - 'This session cannot create or edit workspace items, so there is no authoring guidance to give. Tell the user plainly rather than describing how it would be done.' + 'This session cannot create or edit this kind of item, so there is no authoring guidance to give for it. Tell the user plainly rather than describing how it would be done.' toolCallbacks.setToolStatus(toolId, { content: 'No authoring guidance' }) return message } @@ -3438,7 +3816,10 @@ export const globalTools: SessionTool<{}>[] = [ ? `${parsed.subject} (${parsed.language})` : parsed.subject toolCallbacks.setToolStatus(toolId, { content: `Loaded ${label} instructions` }) - return getInstructions(parsed.subject, parsed.language, ctx.workspace) + // Past the gate without `write_draft` means a builder: guidance for inline code would + // steer the model at writes the server refuses and tools it was not given. + const composeOnly = !!access && !access.has('write_draft') + return getInstructions(parsed.subject, parsed.language, ctx.workspace, composeOnly) } }, createSearchHubScriptsTool(false), @@ -3599,10 +3980,23 @@ export const globalTools: SessionTool<{}>[] = [ planModeSafe: true, fn: async ({ args, workspace, toolId, toolCallbacks }) => { const parsed = listWorkspaceItemsSchema.parse(args) - const types = getRequestedTypes(parsed.types) + const accessTypes = (parsed.types ?? []).filter(isAccessType) + const itemTypes = (parsed.types ?? []).filter((t): t is WorkspaceItemType => !isAccessType(t)) + // Asking only for folders or groups must not fall back to the default scripts and flows. + const types = + accessTypes.length > 0 && itemTypes.length === 0 ? [] : getRequestedTypes(itemTypes) const limit = parsed.limit ?? 50 toolCallbacks.setToolStatus(toolId, { content: 'Listing workspace items...' }) + const accessRows = ( + await listAccessEntities( + accessTypes, + workspace, + Math.min(limit, MAX_LIST_LIMIT), + parsed.page + ) + ).filter((row) => itemMatches(row, parsed.query)) + const byKey = new Map<string, WorkspaceItem>() const workspaceItems = await listWorkspaceItems( types, @@ -3646,7 +4040,10 @@ export const globalTools: SessionTool<{}>[] = [ // No cross-type truncation: each type is already capped at `limit` rows by // its own list call, and slicing the concatenation would silently drop the // later types' rows while their next page skips past them. - const results = Array.from(byKey.values()).filter((item) => itemMatches(item, parsed.query)) + const results = [ + ...Array.from(byKey.values()).filter((item) => itemMatches(item, parsed.query)), + ...accessRows + ] toolCallbacks.setToolStatus(toolId, { content: `Listed ${results.length} workspace item(s)` @@ -3654,17 +4051,41 @@ export const globalTools: SessionTool<{}>[] = [ return JSON.stringify(results, null, 2) } }, + { + requires: NONE, + def: createToolDef( + listPipelinesSchema, + 'list_pipelines', + 'List the data pipelines of the workspace: each folder holding at least one pipeline script, with its number of scripts. A pipeline is named by its folder, not by an item path.' + ), + planModeSafe: true, + fn: async ({ workspace, toolId, toolCallbacks }) => { + toolCallbacks.setToolStatus(toolId, { content: 'Listing data pipelines...' }) + const pipelines = await AssetService.listPipelineFolders({ workspace }) + toolCallbacks.setToolStatus(toolId, { + content: `Listed ${pipelines.length} data pipeline(s)` + }) + return JSON.stringify(pipelines) + } + }, { requires: NONE, def: createToolDef( readWorkspaceItemSchema, 'read_workspace_item', - 'Read one workspace item or draft. Prefers your draft when one exists; pass version: "deployed" to read the deployed state instead.' + 'Read one workspace item or draft. Prefers your draft when one exists; pass version: "deployed" to read the deployed state instead. A deployed item carries extraPerms (a draft does not; pass version: "deployed" for it): who it is shared with beyond its owner, as u/<user> or g/<group> → true (write) or false (read-only). A folder returns its owners and extraPerms; a group returns its members and extraPerms (who may manage it). For a folder or group, path is its name. A g/<group> entry grants every member of that group (g/all is everyone), and workspace admins can read and write every folder and item whatever these lists say.' ), planModeSafe: true, fn: async ({ args, workspace, toolId, toolCallbacks }) => { const parsed = readWorkspaceItemSchema.parse(args) - if (parsed.type === 'trigger' && !parsed.trigger_kind) { + const { type } = parsed + if (isAccessType(type)) { + toolCallbacks.setToolStatus(toolId, { content: `Reading ${type} "${parsed.path}"...` }) + const entity = await readAccessEntity(type, parsed.path, workspace) + toolCallbacks.setToolStatus(toolId, { content: `Read ${type} "${entity.name}"` }) + return JSON.stringify(entity, null, 2) + } + if (type === 'trigger' && !parsed.trigger_kind) { const message = 'trigger_kind is required when type is trigger.' toolCallbacks.setToolStatus(toolId, { content: message, error: message }) return JSON.stringify({ success: false, error: message }) @@ -3672,16 +4093,16 @@ export const globalTools: SessionTool<{}>[] = [ const draft = parsed.version === 'deployed' || isHubPath(parsed.path) ? null - : await getGlobalDraft(workspace, parsed.type, parsed.path, parsed.trigger_kind) + : await getGlobalDraft(workspace, type, parsed.path, parsed.trigger_kind) if (draft) { toolCallbacks.setToolStatus(toolId, { - content: `Read draft ${parsed.type} "${parsed.path}"` + content: `Read draft ${type} "${parsed.path}"` }) // The mode reported is the draft's, which is what deploying it will write. The // deployed app's own mode is a different question, asked with version: // "deployed", and must not be fetched here. const executionMode = - parsed.type === 'app' + type === 'app' ? await describeAppExposure( workspace, (draft.value as AppDraftValue)?.policy?.execution_mode @@ -3691,16 +4112,16 @@ export const globalTools: SessionTool<{}>[] = [ } toolCallbacks.setToolStatus(toolId, { - content: `Reading ${parsed.type} "${parsed.path}"...` + content: `Reading ${type} "${parsed.path}"...` }) const item = await readWorkspaceItem( - parsed.type, + type, parsed.path, workspace, parsed.trigger_kind, parsed.version === 'deployed' ) - toolCallbacks.setToolStatus(toolId, { content: `Read ${parsed.type} "${parsed.path}"` }) + toolCallbacks.setToolStatus(toolId, { content: `Read ${type} "${parsed.path}"` }) return JSON.stringify(serializeWorkspaceItemForRead(item), null, 2) } }, @@ -3760,7 +4181,7 @@ export const globalTools: SessionTool<{}>[] = [ } }, { - requires: WRITE_DRAFT, + requires: WRITE_FLOW_DRAFT, def: createToolDef(writeFlowSchema, 'write_flow', 'Create or overwrite a draft flow.'), showDetails: true, streamArguments: true, @@ -3802,7 +4223,7 @@ export const globalTools: SessionTool<{}>[] = [ } }, { - requires: WRITE_DRAFT, + requires: WRITE_SCHEDULE_DRAFT, def: createToolDef( writeScheduleToolSchema, 'write_schedule', @@ -3828,7 +4249,7 @@ export const globalTools: SessionTool<{}>[] = [ } }, { - requires: WRITE_DRAFT, + requires: WRITE_TRIGGER_DRAFT, def: createToolDef( writeTriggerSchema, 'write_trigger', @@ -3894,7 +4315,7 @@ export const globalTools: SessionTool<{}>[] = [ } }, { - requires: WRITE_DRAFT, + requires: WRITE_FLOW_DRAFT, def: createToolDef( patchFlowJsonSchema, 'patch_flow_json', @@ -3938,13 +4359,15 @@ export const globalTools: SessionTool<{}>[] = [ // No requiresConfirmation, for the reason test_run_script carries. bypassedByAutoAccept: true, confirmationMessage: 'Run a deployed script', + // Both endings start the same way: the arguments are read, then either a form opens + // here or the script's own deployed page does. streamingLabel: 'Preparing the run form...', queuedLabel: (args) => `Run ${args?.path ?? 'a script'}`, showDetails: true, autoCollapseDetails: false }, { - requires: RUN_PREVIEW, + requires: RUN_FLOW_PREVIEW, def: testRunFlowToolDef, fn: async (ctx) => { const parsed = testRunFlowSchema.parse(ctx.args) @@ -4124,16 +4547,17 @@ export const globalTools: SessionTool<{}>[] = [ // turns on the kind. Each kind's handler, reached through `deployDraft`'s switch: requires: NONE, kindRequires: { - // scripts.rs `create_script_internal`, flows.rs `create_flow`/`update_flow` and - // apps.rs `create_app_raw`/`update_app_raw` refuse operators; all run the rules. + // scripts.rs `create_script_internal` refuses operators, flows.rs `create_flow`/ + // `update_flow` and apps.rs `create_app_raw`/`update_app_raw` those without the + // matching builder right; all run the rules. script: ['deploy', 'manage_code'], - flow: ['deploy', 'manage_code'], - app: ['deploy', 'manage_code'], + flow: ['deploy', 'manage_flows'], + app: ['deploy', 'manage_apps'], resource: DEPLOY, variable: DEPLOY, - // The schedule and trigger handlers check neither. - schedule: NONE, - trigger: NONE + // No deploy rules here, but `gate_operator_writes` on their routers. + schedule: ['manage_schedules'], + trigger: ['manage_triggers'] } satisfies Record<(typeof ITEM_TYPES)[number], SessionToolPolicy>, def: createToolDef( deployWorkspaceItemSchema, @@ -4151,8 +4575,20 @@ export const globalTools: SessionTool<{}>[] = [ } }, { - // Rebasing writes a fresh draft, so drafts.rs `require_can_write_path` applies. - requires: WRITE_DRAFT, + // Rebasing writes a fresh draft, so drafts.rs `require_can_write_path` applies per kind. + requires: NONE, + kindRequires: { + script: WRITE_DRAFT, + flow: WRITE_FLOW_DRAFT, + app: WRITE_APP_DRAFT, + resource: WRITE_DRAFT, + variable: WRITE_DRAFT, + // Not the per-kind draft rights: `rebaseDraft` has no handler for resources, variables, + // schedules or triggers, so an operator holding only those rights would be offered a + // tool that always throws. + schedule: WRITE_DRAFT, + trigger: WRITE_DRAFT + } satisfies Record<(typeof ITEM_TYPES)[number], SessionToolPolicy>, def: createToolDef( rebaseDraftSchema, 'rebase_draft', @@ -4197,13 +4633,14 @@ export const globalTools: SessionTool<{}>[] = [ kindRequires: { // scripts.rs `delete_script_by_path` calls `require_admin`; a non-admin archives. script: ['admin'], - // flows.rs `delete_flow_by_path` and apps.rs `delete_app` refuse operators. - flow: ['deploy', 'manage_code'], - app: ['deploy', 'manage_code'], + // flows.rs `delete_flow_by_path` and apps.rs `delete_app` refuse operators without + // the matching builder right. + flow: ['deploy', 'manage_flows'], + app: ['deploy', 'manage_apps'], resource: DEPLOY, variable: DEPLOY, - schedule: NONE, - trigger: NONE + schedule: ['manage_schedules'], + trigger: ['manage_triggers'] } satisfies Record<(typeof ITEM_TYPES)[number], SessionToolPolicy>, def: createToolDef( deleteWorkspaceItemSchema, @@ -4239,7 +4676,7 @@ export const globalTools: SessionTool<{}>[] = [ } }, { - requires: WRITE_DRAFT, + requires: WRITE_RESOURCE_DRAFT, def: createToolDef( writeResourceSchema, 'write_resource', @@ -4255,7 +4692,7 @@ export const globalTools: SessionTool<{}>[] = [ } }, { - requires: WRITE_DRAFT, + requires: WRITE_VARIABLE_DRAFT, def: createToolDef( writeVariableSchema, 'write_variable', @@ -4283,22 +4720,72 @@ export const globalTools: SessionTool<{}>[] = [ toolCallbacks.setToolStatus(toolId, { content: `Searching resource types for "${parsed.query}"...` }) - const results = await ResourceService.queryResourceTypes({ + const { resourceTypes, note } = await searchResourceTypes( + parsed.query, workspace, - text: parsed.query, - limit: parsed.limit ?? 5 - }) + parsed.limit ?? 5 + ) toolCallbacks.setToolStatus(toolId, { - content: `Found ${results.length} resource type(s) for "${parsed.query}"` + content: `Found ${resourceTypes.length} resource type(s) for "${parsed.query}"` }) - return JSON.stringify( - results.map((rt) => ({ + const listing = JSON.stringify( + resourceTypes.map((rt) => ({ name: rt.name, schema: rt.schema })), null, 2 ) + // On an unsynced instance the dedicated type is only missing until a sync, so its note + // replaces the "no dedicated type" one, which would have the model create a duplicate. + if (note) { + return `${listing}\n\n${note}` + } + // The search is semantic and always returns its closest types, so a miss reads + // like a hit unless the absence is spelled out. + const words = (parsed.query.toLowerCase().match(/[a-z0-9]+/g) ?? []).filter( + (w) => w.length >= 3 + ) + const named = resourceTypes.some((rt) => words.some((w) => rt.name.toLowerCase().includes(w))) + return named || words.length === 0 + ? listing + : `${listing}\n\nNo resource type name contains "${parsed.query}": these are only the nearest matches, so no dedicated type exists. Searching again with synonyms will not find one — use a fitting generic type above, or create a custom c_<name> type.` + } + }, + { + // Not a draft: resource types have no draft kind, so this writes the workspace once the + // user confirms, under the same right as a deploy. + requires: DEPLOY, + def: createToolDef( + createResourceTypeSchema, + 'create_resource_type', + 'Create a resource type in the workspace. Mutates the workspace once the user confirms the schema.', + { strict: false } + ), + showDetails: true, + requiresConfirmation: true, + confirmationMessage: 'Create resource type', + fn: async ({ args, workspace, toolId, toolCallbacks }) => { + const parsed = createResourceTypeSchema.parse(args) + // The prefix the Add resource type form adds unless an admin turns it off: a hub type + // of the same name, synced later, would otherwise clash with this one. + const name = parsed.name.startsWith('c_') ? parsed.name : `c_${parsed.name}` + await ResourceService.createResourceType({ + workspace, + requestBody: { + name, + description: parsed.description, + schema: parsed.schema + } + }) + // Forms show a resource picker only for a type in this cached list, so a script + // written against the new type would otherwise get a plain object input. + resourceTypesStore.set(undefined) + toolCallbacks.setToolStatus(toolId, { content: `Created resource type ${name}` }) + return JSON.stringify({ + success: true, + message: `Created resource type ${name}. Refer to it by this name.` + }) } }, createDbSchemaTool<{}>({ @@ -4335,13 +4822,15 @@ export const globalTools: SessionTool<{}>[] = [ } }, { - requires: WRITE_DRAFT, - def: createToolDef( - initAppSchema, - 'init_app', - 'Initialize a draft raw app from a framework template.', - { strict: false } - ), + requires: WRITE_APP_DRAFT, + def: createToolDef(initAppSchema, 'init_app', INIT_APP_DESCRIPTION, { strict: false }), + // A builder has no data setup: it needs SQL and inline runnables. + schemaFor: async (helpers) => { + const access = (helpers as GlobalToolHelpers | undefined)?.access + const schema = + access && !access.has('write_draft') ? initAppSchema.omit({ data: true }) : initAppSchema + return createToolDef(schema, 'init_app', INIT_APP_DESCRIPTION, { strict: false }) + }, showDetails: true, showFade: true, fn: async (ctx) => { @@ -4376,7 +4865,7 @@ export const globalTools: SessionTool<{}>[] = [ } }, { - requires: WRITE_DRAFT, + requires: WRITE_APP_DRAFT, def: createToolDef( writeAppFileSchema, 'write_app_file', @@ -4391,7 +4880,7 @@ export const globalTools: SessionTool<{}>[] = [ } }, { - requires: WRITE_DRAFT, + requires: WRITE_APP_DRAFT, def: createToolDef( deleteAppFileSchema, 'delete_app_file', @@ -4403,7 +4892,7 @@ export const globalTools: SessionTool<{}>[] = [ } }, { - requires: WRITE_DRAFT, + requires: WRITE_APP_DRAFT, def: createToolDef( patchAppFileSchema, 'patch_app_file', @@ -4418,7 +4907,7 @@ export const globalTools: SessionTool<{}>[] = [ } }, { - requires: WRITE_DRAFT, + requires: WRITE_APP_DRAFT, def: createToolDef( writeAppRunnableSchema, 'write_app_runnable', @@ -4434,7 +4923,7 @@ export const globalTools: SessionTool<{}>[] = [ } }, { - requires: WRITE_DRAFT, + requires: WRITE_APP_DRAFT, def: createToolDef( deleteAppRunnableSchema, 'delete_app_runnable', @@ -4465,17 +4954,26 @@ export const globalTools: SessionTool<{}>[] = [ { requires: NONE, def: createToolDef(openPreviewSchema, 'open_preview', OPEN_PREVIEW_DESCRIPTION), - // Withhold the editor side from a session that cannot write drafts, so the model - // never offers the user a panel it would not get. + // Withhold the editors a session cannot save, so the model never offers the user a + // panel it would not get. schemaFor: async (helpers) => { const access = (helpers as GlobalToolHelpers | undefined)?.access - return access && !access.has('write_draft') + if (canOpenEditor(access, 'script')) { + return createToolDef(openPreviewSchema, 'open_preview', OPEN_PREVIEW_DESCRIPTION) + } + const flows = canOpenEditor(access, 'flow') + const apps = canOpenEditor(access, 'raw_app') + return flows || apps ? createToolDef( + openPreviewBuilderEditorSchema(flows, apps), + 'open_preview', + OPEN_PREVIEW_DESCRIPTION + ) + : createToolDef( openPreviewViewOnlySchema, 'open_preview', OPEN_PREVIEW_VIEW_ONLY_DESCRIPTION ) - : createToolDef(openPreviewSchema, 'open_preview', OPEN_PREVIEW_DESCRIPTION) }, fn: async (ctx) => { const parsed = openPreviewSchema.parse(ctx.args) @@ -4663,10 +5161,12 @@ export const globalTools: SessionTool<{}>[] = [ }, // Workspace-scoped datatable tools (unrestricted: no whitelist, no creation policy) ...getDatatableTools(), + ...getDatatableMigrationTools(), // Workspace DuckLake: pipeline storage prerequisite, and declared measures ...getDucklakeTools(), // Read-only tools over files the user attached to the conversation - ...fileTools + ...fileTools, + ...workspaceSettingsTools ] // Tools that only make sense inside an AI session (they drive the session's @@ -4811,22 +5311,25 @@ async function openSessionPreview( if (!openPreviewHandler) { return 'Error: open_preview is only available inside an AI session. Tell the user to switch to a session to view the preview, or describe the item textually.' } - // A pipeline has only an editor, and its own capability gates already cover it. + // A pipeline has only an editor, so a session that cannot save its nodes has nothing to open. if (args.kind === 'pipeline') { + if (!canOpenEditor(access, 'pipeline')) { + return 'Error: you cannot open the pipeline editor in this workspace: this user cannot save drafts. Show its scripts with open_preview mode "view" instead.' + } return await openPreviewHandler({ ...args, mode: undefined, sessionId }) } // Resolved before the gates, not after: the handler reads a missing mode as the editor, so // gating on `args.mode === 'edit'` would wave through every call that simply omitted it — // which is what a model whose schema only offers 'view' does. const mode: 'edit' | 'view' = args.mode ?? 'edit' - // The advertised schema already withholds 'edit' from a session that cannot write - // drafts; re-check so a model asking outside the enum can't act outside it either. - if (mode === 'edit' && access && !access.has('write_draft')) { + // The advertised schema already narrows 'edit' to what this session can save; re-check so + // a model asking outside the enum can't act outside it either. + if (mode === 'edit' && !canOpenEditor(access, args.kind)) { const opened = await openPreviewHandler({ ...args, mode: 'view', sessionId }) - return `${opened}\nOpened the deployed page instead: you cannot open item editors in this workspace.` + return `${opened}\nOpened the deployed page instead: you cannot open ${args.kind === 'raw_app' ? 'app' : args.kind} editors in this workspace.` } - // `write_draft` is a workspace capability and says nothing about this path, so an - // edit that survived it is still checked against the item's own permissions. + // The draft capability is workspace-wide and says nothing about this path, so an edit + // that survived it is still checked against the item's own permissions. if (mode === 'edit' && workspace) { const verdict = await canEditItemPath(workspace, args.kind, args.path) if (verdict !== 'allowed') { @@ -4854,10 +5357,12 @@ async function canEditItemPath( const role = await roleForWorkspace(workspace) if (role.kind === 'not_a_member') return 'denied' if (role.kind !== 'resolved' || !role.user) return 'unverified' - if (role.user.operator) return 'denied' + const user = role.user + const settings = get(userWorkspaces).find((w) => w.id === workspace)?.operator_settings + if (!roleCanDraft(kind, user, settings)) return 'denied' // Folder and ownership rules answer most calls without a request. An item's own // `extra_perms` can only widen them, so the item is fetched only to overturn a denial. - if (canWrite(path, {}, role.user)) return 'allowed' + if (canDraftItem(kind, path, {}, user, settings)) return 'allowed' try { const extraPerms = kind === 'script' @@ -4865,7 +5370,7 @@ async function canEditItemPath( : kind === 'flow' ? (await FlowService.getFlowByPath({ workspace, path })).extra_perms : (await AppService.getAppByPath({ workspace, path })).extra_perms - return canWrite(path, extraPerms ?? {}, role.user) ? 'allowed' : 'denied' + return canDraftItem(kind, path, extraPerms, user, settings) ? 'allowed' : 'denied' } catch (e) { // Nothing deployed means no sharing to widen the folder rules with. return (e as { status?: number } | null | undefined)?.status === 404 ? 'denied' : 'unverified' @@ -5427,7 +5932,12 @@ type ScriptDraftArgs = { const SCRIPT_SPEC: WriteSpec<NewScript, ScriptDraftArgs> = { probe: (workspace, path) => ScriptService.existsScriptByPath({ workspace, path }), fetchDeployed: async (workspace, path) => { - const existing = await ScriptService.getScriptByPath({ workspace, path }) + // The deployed lock describes the deployed content, not the draft's; the deploy recomputes it. + const { + lock: _lock, + lock_error_logs: _lockErrorLogs, + ...existing + } = await ScriptService.getScriptByPath({ workspace, path }) return { ...(existing as unknown as NewScript), parent_hash: existing.hash } }, buildDraft: async (base, args, path) => { @@ -5471,6 +5981,17 @@ function writeScriptDraft( ctx: WriteDraftCtx, codeDiff?: ToolCodeDiff ): Promise<string> { + // A session builds pipeline nodes into the folder's pipeline draft; a script draft + // written here never reaches the pipeline graph, and saving the pipeline drops it. + if ( + (ctx.sessionId ?? sessionIdFromCtx(ctx)) && + parsePipelineAnnotations(args.content).inPipeline + ) { + const folder = args.path.match(/^f\/([^/]+)\//)?.[1] ?? '<folder>' + throw new Error( + `"${args.path}" is a data pipeline node (its source starts with the pipeline annotation). In a session, pipeline nodes are not script drafts: call open_preview(kind="pipeline", path="${folder}") if that folder's pipeline editor is not open yet, then use build_pipeline_node (new node) or edit_pipeline_node (existing node). Nothing was written.` + ) + } return writeDraft(SCRIPT_SPEC, 'script', args.path, args, ctx, { override: args.override, codeDiff: @@ -5515,6 +6036,8 @@ const FLOW_SPEC: WriteSpec<Flow, FlowDraftArgs> = { } } } + // Also checked at deploy; dropped here too because a test run of the draft reads the locks. + dropStaleStepLocks(value, base?.value) return base ? { ...structuredClone(base), @@ -5961,9 +6484,9 @@ async function agentStepRunForm( ): Promise<{ schema: Record<string, any>; args: Record<string, any> }> { const transforms = (module.value as { input_transforms?: Record<string, any> }).input_transforms // A linked step's brain belongs to the resource rather than to this flow, so only the inputs - // this flow supplies are its to edit. + // this flow supplies, and its overrides, are its to edit. const full = (await loadSchemaFromModule(module, workspace)).schema - const schema = (module.value as { agent?: string }).agent ? flowLocalAgentSchema(full) : full + const schema = (module.value as { agent?: string }).agent ? linkedAgentStepSchema(full) : full const visible = initialVisibleAgentFields(transforms, schema.properties) // What the model asked to set, shown even where the step configures nothing: this form has no @@ -6108,6 +6631,8 @@ type FormRunSpec = { label?: string /** Whether the bypass posture may answer this form with what it opened with. */ autoAcceptable?: boolean + /** Whether this item's deployed page is a conversation rather than a run form. */ + conversational?: boolean background?: boolean detachAfterMs?: number startJob: (submitted: Record<string, any>) => Promise<string> @@ -6191,6 +6716,7 @@ async function runThroughForm(spec: FormRunSpec, ctx: WriteDraftCtx): Promise<st summary: spec.summary || undefined, kind: spec.kind, runnableKind: spec.contextName, + conversational: spec.conversational || undefined, schema: autoAccepted ? undefined : schema, code: autoAccepted ? undefined : spec.code, lang: autoAccepted ? undefined : spec.lang, @@ -6217,10 +6743,10 @@ async function runThroughForm(spec: FormRunSpec, ctx: WriteDraftCtx): Promise<st }) // `form`, not `persisted`: a password field mints from what it opens with. - const submitted = toolCallbacks.requestRunArgs + const answer: RunFormAnswer | undefined = toolCallbacks.requestRunArgs ? await toolCallbacks.requestRunArgs(toolId, form, { autoAccepted }) - : proposed - if (!submitted) { + : { kind: 'args', args: proposed } + if (!answer) { toolCallbacks.setToolStatus(toolId, { content: `Run of "${spec.path}" cancelled by user`, isLoading: false, @@ -6231,8 +6757,17 @@ async function runThroughForm(spec: FormRunSpec, ctx: WriteDraftCtx): Promise<st return runFormCancelled(spec.toolName, noun) } - const blockedBeforeRun = blockedByPlanMode() - if (blockedBeforeRun) return blockedBeforeRun + // A run the reader started on the item's own page. It is already going, at that page's own + // version and with arguments its own form coerced and minted — so there is nothing here to + // gate or process, only a job to follow and its arguments to show. + const adopted = answer.kind === 'job' ? answer : undefined + const submitted = answer.args + + const blockedBeforeRun = adopted ? undefined : blockedByPlanMode() + if (blockedBeforeRun) { + toolCallbacks.markRunFormEnded?.(toolId) + return blockedBeforeRun + } // Every job leaves through here, so this is where a sensitive argument becomes a reference: // the form mints as the user types and the bypass mints in its stead, but a host answering @@ -6240,7 +6775,7 @@ async function runThroughForm(spec: FormRunSpec, ctx: WriteDraftCtx): Promise<st // the two that already minted pay a walk and no round trip. let toRun: Record<string, any> try { - toRun = await processSecretArgs(submitted, schema as any, workspace) + toRun = adopted ? submitted : await processSecretArgs(submitted, schema as any, workspace) } catch (e) { const message = `Failed to store the sensitive arguments of "${spec.path}": ${e}` toolCallbacks.setToolStatus(toolId, { @@ -6249,13 +6784,19 @@ async function runThroughForm(spec: FormRunSpec, ctx: WriteDraftCtx): Promise<st isStreamingArguments: false, error: message }) + toolCallbacks.markRunFormEnded?.(toolId) return message } // The card's details pane must show what ran, not what was proposed. Bytes are marked by // size because the card is persisted; everything else stands as the run page shows it for // the same job. - const forCard = redactFileArgs(toRun, schema as any) + // The page's own, for an adopted run: a deploy between this call reading the schema and the + // reader pressing Run can have added arguments, and redaction only visits the leaves the + // schema it is given declares — so a file argument missing from ours would keep its bytes + // through both the persisted card and the model's result. + const ranAgainst = (adopted?.schema ?? schema) as any + const forCard = redactFileArgs(toRun, ranAgainst) // The transcript is re-cloned into IndexedDB on every save and a form carries whatever was // pasted into it, so past what the pane would render the card reads the arguments off the // job instead. Only once there is a job to read them from: substituting the marker any @@ -6263,11 +6804,26 @@ async function runThroughForm(spec: FormRunSpec, ctx: WriteDraftCtx): Promise<st const oversized = JSON.stringify(forCard).length > MAX_PERSISTED_ARGS_LENGTH if (!oversized) { toolCallbacks.setToolStatus(toolId, { parameters: forCard }) + } else if (adopted) { + // Its job exists already, so the marker can stand in now rather than in `jobStarter`. + toolCallbacks.setToolStatus(toolId, { parameters: { reason: 'WINDMILL_TOO_BIG' } }) } const outcome = await executeTestRun({ jobStarter: async () => { - const jobId = await spec.startJob(toRun) + if (adopted) { + toolCallbacks.markRunFormStarted?.(toolId) + return adopted.jobId + } + let jobId: string + try { + jobId = await spec.startJob(toRun) + } catch (e) { + // The ordinary refusal — gone, renamed, not permitted — and the surface that + // confirmed the run is still waiting for the job it was promised. + toolCallbacks.markRunFormEnded?.(toolId) + throw e + } // The form's own submitted flag flips a round trip earlier, when the user presses // Run; only from here is there a job for a stopped turn to say it left running. toolCallbacks.markRunFormStarted?.(toolId) @@ -6309,7 +6865,7 @@ async function runThroughForm(spec: FormRunSpec, ctx: WriteDraftCtx): Promise<st : '' // Redacted for the model alone: what it proposed is already in its own tool call, but a // secret the user typed into the form would be entering its context here. - const redacted = redactFileArgs(redactSecretArgs(toRun, schema as any), schema as any) + const redacted = redactFileArgs(redactSecretArgs(toRun, ranAgainst), ranAgainst) const submittedJson = JSON.stringify(redacted) const shown = submittedJson.length > MAX_SUBMITTED_ARGS_LENGTH @@ -6321,6 +6877,11 @@ async function runThroughForm(spec: FormRunSpec, ctx: WriteDraftCtx): Promise<st const ran = deepEqual(redacted, proposed) ? 'Ran with the arguments the form opened with, unedited.' : `Ran with arguments: ${shown}` + // The notes below say what THIS form did to the proposal, and an adopted run went through + // the page's form instead — so they describe a submission that never happened. + if (adopted) { + return `The user ran it on the ${spec.contextName}'s own page, at the version that page showed. ${ran}\n${outcome}` + } return `${ran}${cleared}${reset}${stripped}${undeclared}\n${outcome}` } @@ -6377,6 +6938,8 @@ async function runDeployedFlow( schema: (flow.schema as Record<string, any>) ?? {}, summary: flow.summary, kind: 'run', + // Its deployed page is a conversation with no run form, so the card keeps this run. + conversational: flow.value?.chat_input_enabled ?? false, // No code/lang: the dynamic-option pickers come from the deployed flow, not an inline copy. schemaNoun: 'deployed', toolName: 'run_flow', @@ -6391,6 +6954,11 @@ async function runDeployedFlow( workspace, path: args.path, requestBody: submitted, + // A chat-enabled flow is refused without one, and it names a conversation rather + // than being a flow argument, so nothing in `args` could carry it. A fresh id: + // this run is its own conversation on the flow's page, not a turn appended to + // one someone is reading there. + memoryId: chatMemoryId(flow.value), // As the flow's own run page does: the form fills the main input schema, and a // preprocessor would take these arguments for a webhook body and hand the flow // its own output instead. @@ -6570,11 +7138,13 @@ async function initApp( content: `Saving app "${path}" draft (${framework} template)…` }) - const template = FRAMEWORK_TEMPLATES[framework] + // A builder can save no inline runnable, so they start from a static page instead of the tour. + const builder = operatorBuilderAppsIn(workspace) const value: AppDraftValue = { summary, - files: { ...template }, - runnables: structuredClone(STARTER_RUNNABLES), + files: { ...(builder ? BUILDER_FRAMEWORK_TEMPLATES : FRAMEWORK_TEMPLATES)[framework] }, + runnables: builder ? {} : structuredClone(STARTER_RUNNABLES), + policy: { sandbox: true }, ...(data && { data: { tables: (data.tables ?? []).map((ref) => appTableRef(data.datatable, data.schema, ref)), @@ -6587,7 +7157,7 @@ async function initApp( const result = await saveAppDraft(workspace, path, value) return finishAppDraftWrite(result, ctx, () => ({ content: `Saved app "${path}" draft (${framework})`, - message: `Initialized a per-user draft app "${path}" from the ${framework} template (saved server-side, not a deployed workspace item). The template is a demo tour with starter runnables ${Object.keys(STARTER_RUNNABLES).join(', ')}: replace its UI and delete the runnables the app does not need (delete_app_runnable). Use write_app_file / write_app_runnable to evolve it.${data?.schema ? ` Its data config names schema "${data.schema}" of data table "${data.datatable}" without creating it: if it does not exist yet, create it before the tables that go in it.` : ''}` + message: `Initialized a per-user draft app "${path}" from the ${framework} template (saved server-side, not a deployed workspace item). ${builder ? 'The template is a static page with no runnables: replace its UI, and add only deployed scripts and flows, by path.' : `The template is a demo tour with starter runnables ${Object.keys(STARTER_RUNNABLES).join(', ')}: replace its UI and delete the runnables the app does not need (delete_app_runnable).`} Use write_app_file / write_app_runnable to evolve it.${data?.schema ? ` Its data config names schema "${data.schema}" of data table "${data.datatable}" without creating it: if it does not exist yet, create it before the tables that go in it.` : ''}` })) } @@ -8925,6 +9495,7 @@ export function prepareGlobalSystemMessage( ? { folders: user.folders, foldersRead: user.folders_read ?? user.folders, + groups: user.groups, isAdmin: user.is_admin ?? false } : undefined @@ -9049,6 +9620,10 @@ export function prepareGlobalUserMessage( content += '\n' } + if (options.resourceTypeSync) { + content += resourceTypeSyncBlock(options.resourceTypeSync) + } + content += `## INSTRUCTIONS:\n${instructions}` const images = options.images ?? [] diff --git a/frontend/src/lib/components/copilot/chat/global/gate.ts b/frontend/src/lib/components/copilot/chat/global/gate.ts index d1dafe29ed..506f230027 100644 --- a/frontend/src/lib/components/copilot/chat/global/gate.ts +++ b/frontend/src/lib/components/copilot/chat/global/gate.ts @@ -25,14 +25,35 @@ export function isGlobalAiEnabled(): boolean { } } +const OPERATOR_SESSIONS_KEY = 'wm_operator_ai_sessions' + +/** + * Operators get AI sessions only in a browser that opted in, until the operator experience + * has been tested; everywhere else they keep the docked chat and `/sessions` refuses them. + * Set with `localStorage.setItem('wm_operator_ai_sessions', '1')` and reload. To ship it, + * delete this and `sessionsAllowedFor`, and drop the `isOperator` argument from every caller. + */ +function operatorSessionsEnabled(): boolean { + if (typeof localStorage === 'undefined') return false + try { + return localStorage.getItem(OPERATOR_SESSIONS_KEY) === '1' + } catch { + return false + } +} + +/** Whether this user's role may use AI sessions at all. */ +export function sessionsAllowedFor(isOperator: boolean | undefined): boolean { + return !isOperator || operatorSessionsEnabled() +} + /** * Whether an AI entry point hands off to a session instead of driving the docked * chat. Deliberately the same condition as the root layout's `disableAi`, so a * caller falling back on `false` always has a mounted pane to fall back to. - * Operators keep that pane (`/sessions` refuses them) until the operator chat ships. */ export function prefersSessionHandoff(isOperator: boolean | undefined): boolean { - return isGlobalAiEnabled() && !isOperator + return isGlobalAiEnabled() && sessionsAllowedFor(isOperator) } /** Clear the opt-out, then hard-reload so every gated site re-reads it. */ diff --git a/frontend/src/lib/components/copilot/chat/global/globalAssembly.test.ts b/frontend/src/lib/components/copilot/chat/global/globalAssembly.test.ts index feffda425e..dcb46ca148 100644 --- a/frontend/src/lib/components/copilot/chat/global/globalAssembly.test.ts +++ b/frontend/src/lib/components/copilot/chat/global/globalAssembly.test.ts @@ -15,22 +15,17 @@ vi.mock('@codingame/monaco-vscode-languages-service-override', () => ({ default: vi.mock('$lib/components/vscode', () => ({})) import { getSessionContextPromptSection, type SessionPromptContext } from './core' -import { getPipelinePromptSection, type PipelineContext } from '../pipeline/core' +import { getPipelinePromptSection } from '../pipeline/core' import { assembleGlobalSystemMessage, assembleGlobalTools } from './globalAssembly' const sessionContext: SessionPromptContext = { workspaceId: 'ws', parentWorkspaceId: 'parent' } -const pipelineContext: PipelineContext = { - folder: 'myfolder', - mode: 'edit', - nodes: [], - assets: [] -} +const pipelineFolders = ['myfolder'] describe('assembleGlobalTools', () => { it('includes the pipeline tools only when a pipeline editor is active', () => { const names = (opts: Parameters<typeof assembleGlobalTools>[0]) => assembleGlobalTools(opts).map((t) => t.def.function.name) - expect(names({ pipelineContext })).toContain('get_pipeline_graph') + expect(names({ pipelineFolders })).toContain('get_pipeline_graph') expect(names({})).not.toContain('get_pipeline_graph') }) }) @@ -41,13 +36,13 @@ describe('assembleGlobalSystemMessage', () => { it('carries both optional sections when both contexts are given', () => { const content = assembleGlobalSystemMessage(undefined, { sessionContext, - pipelineContext + pipelineFolders }).content as string expect(content).toContain(getSessionContextPromptSection(sessionContext)) - expect(content).toContain(getPipelinePromptSection(pipelineContext)) + expect(content).toContain(getPipelinePromptSection(pipelineFolders)) // Order is part of the assembled output, so it is pinned too. expect(content.indexOf(getSessionContextPromptSection(sessionContext))).toBeLessThan( - content.indexOf(getPipelinePromptSection(pipelineContext)) + content.indexOf(getPipelinePromptSection(pipelineFolders)) ) }) @@ -58,6 +53,6 @@ describe('assembleGlobalSystemMessage', () => { // shares, so a stray section built from any other context still trips them. const heading = (s: string) => s.trim().split('\n')[0] expect(content).not.toContain(heading(getSessionContextPromptSection(sessionContext))) - expect(content).not.toContain(heading(getPipelinePromptSection(pipelineContext))) + expect(content).not.toContain(heading(getPipelinePromptSection(pipelineFolders))) }) }) diff --git a/frontend/src/lib/components/copilot/chat/global/globalAssembly.ts b/frontend/src/lib/components/copilot/chat/global/globalAssembly.ts index a291e93ec7..d1fe80f13d 100644 --- a/frontend/src/lib/components/copilot/chat/global/globalAssembly.ts +++ b/frontend/src/lib/components/copilot/chat/global/globalAssembly.ts @@ -12,7 +12,7 @@ import { type SessionPromptContext } from './core' import { createMcpTools } from './mcpTools' -import { getPipelinePromptSection, pipelineTools, type PipelineContext } from '../pipeline/core' +import { getPipelinePromptSection, pipelineTools } from '../pipeline/core' import { getFolderInstructionsPromptSection, type FolderInstruction } from '../folderInstructions' // Derived, not retyped: an option added to prepareGlobalSystemMessage is reachable @@ -21,7 +21,8 @@ import { getFolderInstructionsPromptSection, type FolderInstruction } from '../f // directly — would get it. export type GlobalAssemblyOpts = NonNullable<Parameters<typeof prepareGlobalSystemMessage>[1]> & { sessionContext?: SessionPromptContext - pipelineContext?: PipelineContext + /** Folders of the open pipeline editors; the pipeline tools and prompt come with any. */ + pipelineFolders?: readonly string[] folderInstructions?: readonly FolderInstruction[] } @@ -34,8 +35,8 @@ export function assembleGlobalSystemMessage( if (opts.sessionContext) { systemMessage.content += getSessionContextPromptSection(opts.sessionContext, opts.access) } - if (opts.pipelineContext) { - systemMessage.content += getPipelinePromptSection(opts.pipelineContext, opts.access) + if (opts.pipelineFolders?.length) { + systemMessage.content += getPipelinePromptSection(opts.pipelineFolders, opts.access) } return systemMessage } @@ -43,7 +44,7 @@ export function assembleGlobalSystemMessage( export function assembleGlobalTools(opts: GlobalAssemblyOpts): SessionTool<any>[] { return [ ...globalToolsFor({ sessionPreview: opts.previewTools ?? false }), - ...(opts.pipelineContext ? pipelineTools : []), + ...(opts.pipelineFolders?.length ? pipelineTools : []), ...createMcpTools(opts.mcpServers ?? []) ] } diff --git a/frontend/src/lib/components/copilot/chat/global/sessionAccess.test.ts b/frontend/src/lib/components/copilot/chat/global/sessionAccess.test.ts index 82ad8162d3..38718ed1b4 100644 --- a/frontend/src/lib/components/copilot/chat/global/sessionAccess.test.ts +++ b/frontend/src/lib/components/copilot/chat/global/sessionAccess.test.ts @@ -8,7 +8,7 @@ const { whoami, deployRules } = vi.hoisted(() => ({ vi.mock('$lib/gen', () => ({ UserService: { whoami } })) vi.mock('$lib/utils_workspace_deploy', () => ({ checkDeployRules: deployRules })) -import { resolveSessionAccess } from './sessionAccess' +import { capabilitiesForRole, resolveSessionAccess } from './sessionAccess' import { clearWorkspaceRoleCache } from '$lib/user' type WhoamiOverrides = { is_admin?: boolean; is_super_admin?: boolean; operator?: boolean } @@ -45,20 +45,51 @@ describe('resolveSessionAccess', () => { it('gives a developer every capability but admin', async () => { const caps = await capabilitiesFor({}) - expect([...caps].sort()).toEqual(['deploy', 'manage_code', 'run_preview', 'write_draft']) + expect([...caps].sort()).toEqual([ + 'deploy', + 'manage_apps', + 'manage_code', + 'manage_flows', + 'manage_schedules', + 'manage_triggers', + 'run_flow_preview', + 'run_preview', + 'write_app_draft', + 'write_draft', + 'write_flow_draft', + 'write_resource_draft', + 'write_schedule_draft', + 'write_trigger_draft', + 'write_variable_draft' + ]) }) // The folder, resource and variable handlers run the rules but have no operator check, // so withholding `deploy` from an operator would be stricter than the server. it('leaves an operator the deploy-rule capability, and nothing their token refuses', async () => { const caps = await capabilitiesFor({ operator: true }) - expect([...caps]).toEqual(['deploy']) + expect([...caps].sort()).toEqual([ + 'deploy', + 'manage_schedules', + 'manage_triggers', + 'write_resource_draft', + 'write_schedule_draft', + 'write_trigger_draft', + 'write_variable_draft' + ]) }) it('takes deploy from the rules alone, so a rule blocks an operator too', async () => { deployRules.mockResolvedValue({ ok: false, refusedBy: 'DisableDirectDeployment' }) const caps = await capabilitiesFor({ operator: true }) - expect([...caps]).toEqual([]) + expect([...caps].sort()).toEqual([ + 'manage_schedules', + 'manage_triggers', + 'write_resource_draft', + 'write_schedule_draft', + 'write_trigger_draft', + 'write_variable_draft' + ]) }) // Both spellings of `authed.is_admin`, which the draft path honours and the handlers @@ -67,7 +98,19 @@ describe('resolveSessionAccess', () => { 'lets an admin who is also an operator draft and deploy, but not preview or manage code (%o)', async (role) => { const caps = await capabilitiesFor({ ...role, operator: true }) - expect([...caps].sort()).toEqual(['admin', 'deploy', 'write_draft']) + expect([...caps].sort()).toEqual([ + 'admin', + 'deploy', + 'manage_schedules', + 'manage_triggers', + 'write_app_draft', + 'write_draft', + 'write_flow_draft', + 'write_resource_draft', + 'write_schedule_draft', + 'write_trigger_draft', + 'write_variable_draft' + ]) } ) @@ -82,6 +125,64 @@ describe('resolveSessionAccess', () => { expect(caps.has('write_draft')).toBe(true) }) + // flows.rs, drafts.rs and run_preview_flow all let a builder through for flows, and + // nothing else moves: scripts, apps and their previews stay refused. + it("gives a builder operator the flow capabilities and nothing a script's handler refuses", () => { + const caps = capabilitiesForRole({ + isAdmin: false, + operator: true, + deployRulesPass: true, + operatorSettings: { builder_flows: true } + }) + expect([...caps].sort()).toEqual([ + 'deploy', + 'manage_flows', + 'manage_schedules', + 'manage_triggers', + 'run_flow_preview', + 'write_flow_draft', + 'write_resource_draft', + 'write_schedule_draft', + 'write_trigger_draft', + 'write_variable_draft' + ]) + }) + + // apps.rs and drafts.rs let an app builder through; nothing runs an app preview server-side. + it('gives an app builder operator the app capabilities alone', () => { + const caps = capabilitiesForRole({ + isAdmin: false, + operator: true, + deployRulesPass: true, + operatorSettings: { builder_apps: true } + }) + expect([...caps].sort()).toEqual([ + 'deploy', + 'manage_apps', + 'manage_schedules', + 'manage_triggers', + 'write_app_draft', + 'write_resource_draft', + 'write_schedule_draft', + 'write_trigger_draft', + 'write_variable_draft' + ]) + }) + + // A withdrawable right: only `false` withdraws it, as `gate_operator_writes` reads it. + it('withholds schedule and trigger writes only where the workspace set them to false', () => { + const caps = capabilitiesForRole({ + isAdmin: false, + operator: true, + deployRulesPass: true, + operatorSettings: { manage_schedules: false } + }) + expect(caps.has('manage_schedules')).toBe(false) + expect(caps.has('write_schedule_draft')).toBe(false) + expect(caps.has('manage_triggers')).toBe(true) + expect(caps.has('write_trigger_draft')).toBe(true) + }) + it('grants everything when the role cannot be resolved', async () => { whoami.mockRejectedValueOnce(new Error('network')) const access = await resolveSessionAccess('ws') diff --git a/frontend/src/lib/components/copilot/chat/global/sessionAccess.ts b/frontend/src/lib/components/copilot/chat/global/sessionAccess.ts index 1ac13136a4..86239f5b19 100644 --- a/frontend/src/lib/components/copilot/chat/global/sessionAccess.ts +++ b/frontend/src/lib/components/copilot/chat/global/sessionAccess.ts @@ -1,12 +1,32 @@ +import { get } from 'svelte/store' +import { userWorkspaces } from '$lib/stores' +import type { OperatorSettings } from '$lib/gen' import { getWorkspaceRole } from '$lib/user' +import { roleCanAuthor, roleCanDraft } from '$lib/editRights' import { checkDeployRules } from '$lib/utils_workspace_deploy' import type { SessionAccess, SessionCapability } from '../sessionCapabilities' +type OperatorRights = Pick< + NonNullable<OperatorSettings>, + 'builder_flows' | 'builder_apps' | 'manage_schedules' | 'manage_triggers' +> + const ALL_CAPABILITIES: SessionCapability[] = [ 'write_draft', + 'write_flow_draft', + 'write_app_draft', + 'write_schedule_draft', + 'write_trigger_draft', + 'write_resource_draft', + 'write_variable_draft', 'run_preview', + 'run_flow_preview', 'deploy', 'manage_code', + 'manage_flows', + 'manage_apps', + 'manage_schedules', + 'manage_triggers', 'admin' ] @@ -25,19 +45,53 @@ export function capabilitiesForRole(role: { isAdmin: boolean operator: boolean deployRulesPass: boolean + /** The workspace's `operator_settings`, null for a non-operator. */ + operatorSettings?: OperatorRights | null }): SessionAccess { const capabilities = new Set<SessionCapability>() - // Per-capability precedence, NOT a role ladder: drafts.rs `require_can_write_path` - // returns Ok on `authed.is_admin` BEFORE its operator branch, while jobs.rs - // `run_preview_*` and the script/flow/app handlers refuse `authed.is_operator` with no - // admin escape — and on the session path that flag is never cleared for an admin. - if (role.isAdmin || !role.operator) { + const user = { operator: role.operator, is_admin: role.isAdmin, is_super_admin: false } + const authorsCode = roleCanAuthor('script', user, role.operatorSettings) + const authorsFlows = roleCanAuthor('flow', user, role.operatorSettings) + // Drafts take the admin precedence `roleCanDraft` encodes; previews and the item handlers + // do not — and on the session path the operator flag is never cleared for an admin. + if (roleCanDraft('script', user, role.operatorSettings)) { capabilities.add('write_draft') } - if (!role.operator) { + if (roleCanDraft('flow', user, role.operatorSettings)) { + capabilities.add('write_flow_draft') + } + if (roleCanDraft('raw_app', user, role.operatorSettings)) { + capabilities.add('write_app_draft') + } + if (roleCanDraft('schedule', user, role.operatorSettings)) { + capabilities.add('write_schedule_draft') + } + if (roleCanDraft('trigger', user, role.operatorSettings)) { + capabilities.add('write_trigger_draft') + } + if (roleCanDraft('resource', user, role.operatorSettings)) { + capabilities.add('write_resource_draft') + } + if (roleCanDraft('variable', user, role.operatorSettings)) { + capabilities.add('write_variable_draft') + } + if (authorsCode) { capabilities.add('run_preview') capabilities.add('manage_code') } + if (authorsFlows) { + capabilities.add('run_flow_preview') + capabilities.add('manage_flows') + } + if (roleCanAuthor('raw_app', user, role.operatorSettings)) { + capabilities.add('manage_apps') + } + if (roleCanAuthor('schedule', user, role.operatorSettings)) { + capabilities.add('manage_schedules') + } + if (roleCanAuthor('trigger', user, role.operatorSettings)) { + capabilities.add('manage_triggers') + } // No operator term: the rules are their own gate, and the handlers that also refuse // operators say so through `manage_code`. Admins bypass the rules inside the check. if (role.deployRulesPass) { @@ -63,6 +117,7 @@ export async function resolveSessionAccess(workspace: string): Promise<SessionAc return capabilitiesForRole({ isAdmin: !!me.is_admin || !!me.is_super_admin, operator: !!me.operator, - deployRulesPass: (await checkDeployRules(workspace, me)).ok + deployRulesPass: (await checkDeployRules(workspace, me)).ok, + operatorSettings: get(userWorkspaces).find((w) => w.id === workspace)?.operator_settings }) } diff --git a/frontend/src/lib/components/copilot/chat/global/sessionToolset.test.ts b/frontend/src/lib/components/copilot/chat/global/sessionToolset.test.ts index 42136112c4..d3f5bfbb05 100644 --- a/frontend/src/lib/components/copilot/chat/global/sessionToolset.test.ts +++ b/frontend/src/lib/components/copilot/chat/global/sessionToolset.test.ts @@ -32,7 +32,7 @@ import type { SessionAccess, SessionCapability, SessionTool } from '../sessionCa const ASSEMBLY_OPTS = { previewTools: true, - pipelineContext: { folder: 'my_pipeline', mode: 'edit', nodes: [], assets: [] }, + pipelineFolders: ['my_pipeline'], mcpServers: [{ path: 'f/test/server' } as any] } @@ -54,9 +54,13 @@ function sessionReachableTools(): SessionTool<any>[] { } function withheldNames(access: SessionAccess): string[] { + // Shipped, not merely allowed: a kind-taking tool left with no kind is dropped too. + const shipped = new Set( + filterSessionTools(sessionReachableTools(), access).map((t) => t.def.function.name) + ) return sessionReachableTools() - .filter((t) => !sessionToolAllowed(t, access)) .map((t) => t.def.function.name) + .filter((n) => !shipped.has(n)) } /** The tools a session actually ships, through the same assembly production uses. */ @@ -75,10 +79,26 @@ const REACHABLE_PROFILES = [ [false, true].flatMap((isAdmin) => [false, true].flatMap((operator) => // `checkDeployRules` bypasses on admin, so an admin has only the one outcome. - (isAdmin ? [true] : [false, true]).map((deployRulesPass) => { - const access = capabilitiesForRole({ isAdmin, operator, deployRulesPass }) - return [[...access].sort().join(',') || 'none', access] as const - }) + (isAdmin ? [true] : [false, true]).flatMap((deployRulesPass) => + // The operator rights a workspace can set: none, either builder right or both, either lock, both locks. + [ + undefined, + { builder_flows: true }, + { builder_apps: true }, + { builder_flows: true, builder_apps: true }, + { manage_schedules: false }, + { manage_triggers: false }, + { manage_schedules: false, manage_triggers: false } + ].map((operatorSettings) => { + const access = capabilitiesForRole({ + isAdmin, + operator, + deployRulesPass, + operatorSettings + }) + return [[...access].sort().join(',') || 'none', access] as const + }) + ) ) ) ).entries() @@ -122,13 +142,26 @@ describe('session tool policies', () => { const kindsOf = (name: string, access: SessionAccess) => (shipped(name, access).def.function.parameters as any).properties.type.enum + const developerCaps: SessionCapability[] = [ + 'write_draft', + 'write_flow_draft', + 'write_app_draft', + 'run_preview', + 'run_flow_preview', + 'manage_code', + 'manage_flows', + 'manage_apps', + 'manage_schedules', + 'manage_triggers' + ] + // A developer a protection rule refuses keeps the two kinds no rule reaches. - const refused = accessWith(['write_draft', 'run_preview', 'manage_code']) + const refused = accessWith(developerCaps) expect(kindsOf('deploy_workspace_item', refused)).toEqual(['schedule', 'trigger']) expect(kindsOf('delete_workspace_item', refused)).toEqual(['schedule', 'trigger']) // An operator where no rule applies: only the code handlers refuse them. - const operator = accessWith(['deploy']) + const operator = accessWith(['deploy', 'manage_schedules', 'manage_triggers']) expect(kindsOf('deploy_workspace_item', operator)).toEqual([ 'schedule', 'trigger', @@ -136,8 +169,28 @@ describe('session tool policies', () => { 'variable' ]) + // A workspace that withdrew schedule writes from operators: `gate_operator_writes`. + const locked = accessWith(['deploy', 'manage_triggers']) + expect(kindsOf('delete_workspace_item', locked)).toEqual(['trigger', 'resource', 'variable']) + + // A builder operator deploys flows too, and still no script or app. + const builder = accessWith(['deploy', 'manage_flows', 'manage_schedules', 'manage_triggers']) + expect(kindsOf('deploy_workspace_item', builder)).toContain('flow') + expect(kindsOf('deploy_workspace_item', builder)).not.toContain('script') + expect(kindsOf('deploy_workspace_item', builder)).not.toContain('app') + + // An app builder gets the app kind alone, and rebases its own stale app drafts. + const appBuilder = accessWith(['deploy', 'manage_apps', 'write_app_draft']) + expect(kindsOf('deploy_workspace_item', appBuilder)).toContain('app') + expect(kindsOf('deploy_workspace_item', appBuilder)).not.toContain('flow') + expect(kindsOf('rebase_draft', appBuilder)).toEqual(['app']) + // A session left with no kind must not be offered an empty enum. + expect(shippedSessionTools(operator).map((t) => t.def.function.name)).not.toContain( + 'rebase_draft' + ) + // Deleting a script is admin-only, where deploying one is not. - const developer = accessWith(['write_draft', 'run_preview', 'manage_code', 'deploy']) + const developer = accessWith([...developerCaps, 'deploy']) expect(kindsOf('deploy_workspace_item', developer)).toContain('script') expect(kindsOf('delete_workspace_item', developer)).not.toContain('script') @@ -150,6 +203,15 @@ describe('session tool policies', () => { expect((original.def.function.parameters as any).properties.type.enum).toContain('script') }) + it('offers the workspace settings tools to admins only', () => { + const settingsTools = ['get_workspace_settings', 'set_workspace_settings'] + for (const [, access] of REACHABLE_PROFILES) { + const names = shippedSessionTools(access).map((t) => t.def.function.name) + const offered = settingsTools.filter((n) => names.includes(n)) + expect(offered).toEqual(access.has('admin') ? settingsTools : []) + } + }) + // Naming a tool the model was not given produces invented calls. Asserted over the // ASSEMBLED message: the session-state, pipeline and plan-mode sections are each // appended by a different caller, and each can name a withheld tool. @@ -168,7 +230,7 @@ describe('session tool policies', () => { user: { username: 'alex', folders: ['shared'], folders_read: ['shared'] }, access, sessionContext: ctx, - pipelineContext: { folder: 'my_pipeline', mode: 'edit', nodes: [], assets: [] } + pipelineFolders: ['my_pipeline'] }) // Both decoration variants: the escalation one adds its own tool mentions. for (const blocks of [0, 9]) { @@ -184,9 +246,9 @@ describe('session tool policies', () => { // ships to every profile with guidance written around the draft tools by name. it('does not hand authoring guidance naming withheld tools to a session that cannot draft', async () => { const tool = globalTools.find((t) => t.def.function.name === 'get_instructions')! - const call = (access: SessionAccess) => + const call = (access: SessionAccess, subject = 'script') => tool.fn({ - args: { subject: 'script', language: 'bun' }, + args: { subject, language: 'bun' }, workspace: 'ws', helpers: { access }, toolId: 't1', @@ -199,6 +261,30 @@ describe('session tool policies', () => { expect(withheld.filter((n) => restricted.includes(n))).toEqual([]) // The gate is the whole test, so pin that it is not simply refusing everyone. expect(await call(fullSessionAccess())).toContain('write_script') + + // A builder gets the guide for their kind, rewritten without the inline-code tools. + for (const [capability, subject, used] of [ + ['write_flow_draft', 'flow', 'patch_flow_json'], + ['write_app_draft', 'app', 'write_app_runnable'] + ] as const) { + const builder = accessWith(['deploy', capability]) + const guide = await call(builder, subject) + expect(guide).toContain(used) + // The shared reference below still teaches inline code, so the guide must say to skip it. + expect(guide).toContain('skip what it says') + expect(withheldNames(builder).filter((n) => guide.includes(n))).toEqual([]) + } + }) + + // A data setup needs SQL and inline runnables, neither of which a builder has. + it('offers a builder no init_app data setup', async () => { + const tool = globalTools.find((t) => t.def.function.name === 'init_app')! + const properties = async (access: SessionAccess) => + ((await tool.schemaFor!({ access })).function.parameters as any).properties + const builder = await properties(accessWith(['deploy', 'write_app_draft'])) + const full = await properties(fullSessionAccess()) + expect(builder.data).toBeUndefined() + expect(full.data).toBeDefined() }) // A full-access profile must gate nothing at all: the text has to match the ungated @@ -216,4 +302,27 @@ describe('session tool policies', () => { expect(full).toBe(ungated) } }) + + // The operator's own rights outrun the chat's tools: what they schedule in the UI must not + // be sent to an admin. + it("sends an operator to the UI for what their role allows and the chat's tools do not", () => { + const prompt = (operatorSettings: { manage_schedules?: boolean }): string => + prepareGlobalSystemMessage(undefined, { + user: { username: 'op' }, + access: capabilitiesForRole({ + isAdmin: false, + operator: true, + deployRulesPass: true, + operatorSettings + }) + }).content as string + + // None of these is sent to the UI: the chat drafts them itself. + expect(prompt({})).not.toContain('they can still edit themselves on their pages') + expect(prompt({})).toContain( + 'lets them create and edit resources, variables, schedules, and triggers' + ) + expect(prompt({})).toContain('schedule a deployed script or flow themselves') + expect(prompt({ manage_schedules: false })).not.toContain('schedule a deployed script') + }) }) diff --git a/frontend/src/lib/components/copilot/chat/global/sessionToolset.ts b/frontend/src/lib/components/copilot/chat/global/sessionToolset.ts index 4789967a6d..0d8f8753a2 100644 --- a/frontend/src/lib/components/copilot/chat/global/sessionToolset.ts +++ b/frontend/src/lib/components/copilot/chat/global/sessionToolset.ts @@ -24,13 +24,16 @@ export function filterSessionTools<T extends FilterableTool>( access: SessionAccess | undefined ): T[] { if (!access) return tools - return tools.filter((t) => sessionToolAllowed(t, access)).map((t) => narrowKinds(t, access)) + return tools + .filter((t) => sessionToolAllowed(t, access)) + .flatMap((t) => narrowKinds(t, access) ?? []) } /** Returns the tool itself when every kind is allowed, so full access ships the same bytes: * tool defs are part of every iteration's cached prefix. Builds new objects otherwise — the - * defs are module singletons shared by every session. */ -function narrowKinds<T extends FilterableTool>(tool: T, access: SessionAccess): T { + * defs are module singletons shared by every session. `undefined` when no kind is left: an + * empty enum would offer a tool no call can satisfy. */ +function narrowKinds<T extends FilterableTool>(tool: T, access: SessionAccess): T | undefined { const kindRequires = tool.kindRequires if (!kindRequires) return tool const parameters = tool.def.function.parameters as { @@ -40,6 +43,7 @@ function narrowKinds<T extends FilterableTool>(tool: T, access: SessionAccess): // A kind with no entry is withheld, as a tool with no `requires` is. const allowed = kinds.filter((k) => kindRequires[k] && satisfies(kindRequires[k], access)) if (allowed.length === kinds.length) return tool + if (allowed.length === 0) return undefined const def = structuredClone(tool.def) ;(def.function.parameters as typeof parameters).properties.type.enum = allowed return { ...tool, def } diff --git a/frontend/src/lib/components/copilot/chat/global/workspaceItems.ts b/frontend/src/lib/components/copilot/chat/global/workspaceItems.ts index 3d922a3b72..d08fe4fd58 100644 --- a/frontend/src/lib/components/copilot/chat/global/workspaceItems.ts +++ b/frontend/src/lib/components/copilot/chat/global/workspaceItems.ts @@ -151,6 +151,10 @@ export type WorkspaceItem = { * app, not in listings — a listing carrying it would make absence read as * proof of no exposure. */ executionMode?: string + /** Who a deployed item is shared with beyond its path owner, as `u/<user>` / + * `g/<group>` → true for write, false for read-only. A draft has no permissions of + * its own, so a draft read leaves it unset rather than reporting the item unshared. */ + extraPerms?: Record<string, boolean> isDraft: boolean isLiveDraft?: boolean } diff --git a/frontend/src/lib/components/copilot/chat/global/workspaceSettingsTools.ts b/frontend/src/lib/components/copilot/chat/global/workspaceSettingsTools.ts new file mode 100644 index 0000000000..d63b75343f --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/global/workspaceSettingsTools.ts @@ -0,0 +1,169 @@ +import { z } from 'zod' +import YAML from 'yaml' +import { ApiError, WorkspaceService, type ApplyWorkspaceSettingsDocumentResponse } from '$lib/gen' +import { createToolDef, type ToolCodeDiff } from '../shared' +import type { SessionTool, SessionToolPolicy } from '../sessionCapabilities' +import { toStableYaml } from './draftDiff' + +// Both endpoints call `require_admin`. +const ADMIN: SessionToolPolicy = ['admin'] + +const MAX_READ_CHARS = 20_000 + +type SettingsChange = ApplyWorkspaceSettingsDocumentResponse['changes'][number] + +const getWorkspaceSettingsSchema = z.object({ + keys: z + .array(z.string()) + .optional() + .describe('Only these top-level keys. Omit for the whole document.') +}) + +const setWorkspaceSettingsSchema = z.object({ + yaml: z + .string() + .describe( + 'A YAML mapping of only the top-level keys to change, each given whole (a nested object replaces the stored one). A key set to null clears it.' + ) +}) + +function apiErrorText(e: unknown): string { + if (e instanceof ApiError) { + return typeof e.body === 'string' ? e.body : JSON.stringify(e.body) + } + return e instanceof Error ? e.message : String(e) +} + +function parseSettingsYaml(text: string): Record<string, unknown> { + const doc = YAML.parse(text) + if (doc === null || typeof doc !== 'object' || Array.isArray(doc)) { + throw new Error('The yaml must be a mapping of setting keys to values.') + } + return doc +} + +// An unset value is left out rather than written as null, so a side with nothing set is empty. +function changesSide(changes: SettingsChange[], side: 'before' | 'after'): string { + const set = changes.filter((c) => c[side] != null) + return set.length ? toStableYaml(Object.fromEntries(set.map((c) => [c.key, c[side]]))) : '' +} + +function changesDiff(changes: SettingsChange[]): ToolCodeDiff { + return { + before: changesSide(changes, 'before'), + after: changesSide(changes, 'after'), + lang: 'yaml' + } +} + +// The dry run answers before the confirmation card, and the card shows its changes. Keyed by +// the call's parsed arguments, the one object both hooks are handed. +const dryRuns = new WeakMap<object, SettingsChange[]>() + +export const workspaceSettingsTools: SessionTool<{}>[] = [ + { + requires: ADMIN, + def: createToolDef( + getWorkspaceSettingsSchema, + 'get_workspace_settings', + 'Read the workspace settings as YAML, in the layout of the settings.yaml file the CLI syncs. Secrets read as `__SENSITIVE_AND_UNCHANGED__`.' + ), + planModeSafe: true, + showDetails: true, + fn: async ({ args, workspace, toolId, toolCallbacks }) => { + const parsed = getWorkspaceSettingsSchema.parse(args) + const doc = (await WorkspaceService.getWorkspaceSettingsDocument({ + workspace, + secrets: 'redacted' + })) as Record<string, unknown> + let picked = doc + let note = '' + if (parsed.keys?.length) { + picked = Object.fromEntries(parsed.keys.filter((k) => k in doc).map((k) => [k, doc[k]])) + const unset = parsed.keys.filter((k) => !(k in doc)) + if (unset.length) { + note = `\n# Not in the document (unset, or not a setting): ${unset.join(', ')}` + } + } + let text = YAML.stringify(picked, { aliasDuplicateObjects: false, lineWidth: 0 }) + note + if (text.length > MAX_READ_CHARS) { + text = `${text.slice(0, MAX_READ_CHARS)}\n… truncated at ${MAX_READ_CHARS} chars; read the keys you need with \`keys\`.` + } + toolCallbacks.setToolStatus(toolId, { + content: parsed.keys?.length + ? `Read workspace settings: ${parsed.keys.join(', ')}` + : 'Read workspace settings' + }) + return text + } + }, + { + requires: ADMIN, + def: createToolDef( + setWorkspaceSettingsSchema, + 'set_workspace_settings', + 'Change workspace settings. Keys the yaml omits are left as they are. The user reviews the changes before they apply. Read get_instructions subject "workspace_settings" before your first change.' + ), + requiresConfirmation: true, + confirmationMessage: 'Change workspace settings', + cancellationMessage: 'The user declined: no setting was changed.', + showDetails: true, + validateBeforeConfirmation: async ({ args, workspace }) => { + let changes: SettingsChange[] + let warnings: string[] | undefined + try { + const document = parseSettingsYaml(setWorkspaceSettingsSchema.parse(args).yaml) + ;({ changes, warnings } = await WorkspaceService.applyWorkspaceSettingsDocument({ + workspace, + requestBody: { document, replace: false, dry_run: true } + })) + } catch (e) { + const error = apiErrorText(e) + return { label: `Invalid settings: ${error}`, result: `Nothing was changed: ${error}` } + } + if (changes.length === 0) { + return { + label: 'No settings change', + result: `The settings already hold these values: nothing to change.${ + warnings?.length ? ` Warnings: ${warnings.join(' ')}` : '' + }` + } + } + dryRuns.set(args, changes) + return undefined + }, + onConfirmationRequested: ({ args, toolCallbacks, toolId }) => { + const changes = dryRuns.get(args) + if (changes) { + toolCallbacks.setToolStatus(toolId, { codeDiff: changesDiff(changes) }) + } + }, + fn: async ({ args, workspace, toolId, toolCallbacks }) => { + const document = parseSettingsYaml(setWorkspaceSettingsSchema.parse(args).yaml) + toolCallbacks.setToolStatus(toolId, { content: 'Changing workspace settings...' }) + try { + const { changes, warnings } = await WorkspaceService.applyWorkspaceSettingsDocument({ + workspace, + requestBody: { document, replace: false } + }) + const keys = changes.map((c) => c.key) + toolCallbacks.setToolStatus(toolId, { + content: `Changed workspace settings: ${keys.join(', ')}`, + codeDiff: changesDiff(changes) + }) + return JSON.stringify({ + success: true, + message: `The user approved and these settings are now applied: ${keys.join(', ')}.`, + ...(warnings?.length ? { warnings } : {}) + }) + } catch (e) { + const error = apiErrorText(e) + toolCallbacks.setToolStatus(toolId, { + content: 'Failed to change workspace settings', + error + }) + return JSON.stringify({ success: false, error }) + } + } + } +] diff --git a/frontend/src/lib/components/copilot/chat/openai-responses.ts b/frontend/src/lib/components/copilot/chat/openai-responses.ts index 3a839f4bad..13143f6bce 100644 --- a/frontend/src/lib/components/copilot/chat/openai-responses.ts +++ b/frontend/src/lib/components/copilot/chat/openai-responses.ts @@ -18,6 +18,7 @@ import { applyReasoningToConfig } from '../reasoningRegistry' import { appendPendingToolImages, processToolCall, + type LiveToolSet, queuedToolStatus, type Tool, type ToolCallbacks, @@ -413,7 +414,11 @@ export async function parseOpenAIResponsesCompletion( addedMessages: ChatCompletionMessageParam[], tools: Tool<any>[], helpers: any, - options?: { workspace?: string; onTokenUsage?: (usage: ChatTokenUsage) => void } + options?: { + workspace?: string + onTokenUsage?: (usage: ChatTokenUsage) => void + live?: LiveToolSet + } ): Promise<ParsedCompletionResult> { let toolCallsToProcess: ChatCompletionMessageFunctionToolCall[] = [] let error: OpenAIError | ResponseErrorEvent | null = null @@ -620,7 +625,8 @@ export async function parseOpenAIResponsesCompletion( helpers, toolCallbacks: callbacks, workspace: options?.workspace, - messages + messages, + live: options?.live }) messages.push(messageToAdd) addedMessages.push(messageToAdd) diff --git a/frontend/src/lib/components/copilot/chat/pipeline/core.test.ts b/frontend/src/lib/components/copilot/chat/pipeline/core.test.ts index c0d9b7ac8b..6c4539ef85 100644 --- a/frontend/src/lib/components/copilot/chat/pipeline/core.test.ts +++ b/frontend/src/lib/components/copilot/chat/pipeline/core.test.ts @@ -39,7 +39,7 @@ const sampleContext: PipelineContext = { } function makeHelpers(overrides: Partial<PipelineAIChatHelpers> = {}): { - helpers: { pipeline: PipelineAIChatHelpers } + helpers: { pipelines: () => PipelineAIChatHelpers[] } calls: Record<string, any[]> } { const calls: Record<string, any[]> = {} @@ -50,6 +50,8 @@ function makeHelpers(overrides: Partial<PipelineAIChatHelpers> = {}): { return ret } const pipeline: PipelineAIChatHelpers = { + getFolder: () => sampleContext.folder, + hasDrafts: () => false, getPipelineContext: () => sampleContext, getNodeBody: async (path: string) => { calls.getNodeBody = [...(calls.getNodeBody ?? []), [path]] @@ -59,15 +61,20 @@ function makeHelpers(overrides: Partial<PipelineAIChatHelpers> = {}): { calls.proposeNode = [...(calls.proposeNode ?? []), [input]] return { path: input.path, detectedReads: [], detectedWrites: [] } }, - editNode: async (path, content) => { - calls.editNode = [...(calls.editNode ?? []), [path, content]] - return { detectedReads: [], detectedWrites: [] } + editNode: async (path, content, summary) => { + calls.editNode = [...(calls.editNode ?? []), [path, content, summary]] + return { summary: summary ?? 'Existing summary', detectedReads: [], detectedWrites: [] } }, removeProposedNode: record('removeProposedNode'), + unconfiguredTriggers: async () => [], + setNodeTrigger: async (path, kind, config) => { + calls.setNodeTrigger = [...(calls.setNodeTrigger ?? []), [path, kind, config]] + return { path: `${path}_${kind}`, replaced: false } + }, testNode: async () => 'job-123', ...overrides } - return { helpers: { pipeline }, calls } + return { helpers: { pipelines: () => [pipeline] }, calls } } describe('pipeline tools', () => { @@ -78,6 +85,7 @@ describe('pipeline tools', () => { 'get_pipeline_graph', 'read_pipeline_node', 'remove_pipeline_node', + 'set_pipeline_trigger', 'test_pipeline_node' ]) }) @@ -96,18 +104,25 @@ describe('pipeline tools', () => { it('build_pipeline_node forwards to proposeNode and does not deploy', async () => { const { helpers, calls } = makeHelpers() + const modified: string[] = [] const out = await toolByName('build_pipeline_node').fn({ args: { path: 'f/analytics/clean', language: 'bun', + summary: 'Test node', content: '// pipeline\nexport async function main() {}', output_kind: 'ducklake' }, workspace: 'w', helpers, - toolCallbacks: noopCallbacks(), + toolCallbacks: { + ...noopCallbacks(), + onItemModified: (kind, path) => modified.push(`${kind}:${path}`) + }, toolId: 't' }) + // The session tracks the folder's draft bundle, the unit it deploys. + expect(modified).toEqual(['data_pipeline:f/analytics/data_pipeline']) expect(calls.proposeNode?.[0]?.[0]).toMatchObject({ path: 'f/analytics/clean', language: 'bun', @@ -116,6 +131,99 @@ describe('pipeline tools', () => { expect(out).toContain('not deployed') }) + it('build_pipeline_node attaches declared triggers, and flags one left unset', async () => { + const { helpers, calls } = makeHelpers({ unconfiguredTriggers: async () => ['kafka'] }) + const out = await toolByName('build_pipeline_node').fn({ + args: { + path: 'f/analytics/ingest', + language: 'python3', + summary: 'Test node', + content: '# pipeline\n# on schedule\n# on kafka\ndef main():\n return 1', + triggers: [{ kind: 'schedule', config: { schedule: '0 0 6 * * *', timezone: 'UTC' } }] + }, + workspace: 'w', + helpers, + toolCallbacks: noopCallbacks(), + toolId: 't' + }) + expect(calls.setNodeTrigger?.[0]).toEqual([ + 'f/analytics/ingest', + 'schedule', + { args: {}, enabled: true, schedule: '0 0 6 * * *', timezone: 'UTC' } + ]) + expect(out).toContain("schedule 'f/analytics/ingest_schedule'") + expect(out).toContain('ACTION REQUIRED') + expect(out).toContain('set_pipeline_trigger') + }) + + it('build_pipeline_node rejects an invalid trigger config before staging the node', async () => { + const { helpers, calls } = makeHelpers() + await expect( + toolByName('build_pipeline_node').fn({ + args: { + path: 'f/analytics/ingest', + language: 'python3', + summary: 'Test node', + content: '# pipeline\n# on schedule\ndef main():\n return 1', + triggers: [{ kind: 'schedule', config: { timezone: 'UTC' } }] + }, + workspace: 'w', + helpers, + toolCallbacks: noopCallbacks(), + toolId: 't' + }) + ).rejects.toThrow(/schedule/) + expect(calls.proposeNode).toBeUndefined() + }) + + it('build_pipeline_node keeps and records the node when a trigger fails to attach', async () => { + const { helpers, calls } = makeHelpers({ + setNodeTrigger: async () => { + throw new Error('path taken') + } + }) + const modified: string[] = [] + const out = await toolByName('build_pipeline_node').fn({ + args: { + path: 'f/analytics/ingest', + language: 'python3', + content: '# pipeline\n# on schedule\ndef main():\n return 1', + summary: 'Ingest', + triggers: [{ kind: 'schedule', config: { schedule: '0 0 6 * * *', timezone: 'UTC' } }] + }, + workspace: 'w', + helpers, + toolCallbacks: { + ...noopCallbacks(), + onItemModified: (kind, path) => modified.push(`${kind}:${path}`) + }, + toolId: 't' + }) + expect(calls.proposeNode).toHaveLength(1) + expect(modified).toEqual(['data_pipeline:f/analytics/data_pipeline']) + expect(out).toContain('path taken') + }) + + it('build_pipeline_node refuses a trigger the content does not declare, before staging', async () => { + const { helpers, calls } = makeHelpers() + await expect( + toolByName('build_pipeline_node').fn({ + args: { + path: 'f/analytics/ingest', + language: 'python3', + content: '# pipeline\ndef main():\n return 1', + summary: 'Ingest', + triggers: [{ kind: 'schedule', config: { schedule: '0 0 6 * * *', timezone: 'UTC' } }] + }, + workspace: 'w', + helpers, + toolCallbacks: noopCallbacks(), + toolId: 't' + }) + ).rejects.toThrow(/on schedule/) + expect(calls.proposeNode).toBeUndefined() + }) + it('build_pipeline_node reports the inferred asset lineage', async () => { const { helpers } = makeHelpers({ proposeNode: async (input) => ({ @@ -125,7 +233,12 @@ describe('pipeline tools', () => { }) }) const out = await toolByName('build_pipeline_node').fn({ - args: { path: 'f/analytics/clean', language: 'duckdb', content: '-- pipeline' }, + args: { + path: 'f/analytics/clean', + language: 'duckdb', + content: '-- pipeline', + summary: 'Test node' + }, workspace: 'w', helpers, toolCallbacks: noopCallbacks(), @@ -140,7 +253,12 @@ describe('pipeline tools', () => { proposeNode: async (input) => ({ path: input.path, detectedReads: [], detectedWrites: [] }) }) const out = await toolByName('build_pipeline_node').fn({ - args: { path: 'f/analytics/clean', language: 'duckdb', content: '-- pipeline' }, + args: { + path: 'f/analytics/clean', + language: 'duckdb', + content: '-- pipeline', + summary: 'Test node' + }, workspace: 'w', helpers, toolCallbacks: noopCallbacks(), @@ -164,6 +282,34 @@ describe('pipeline tools', () => { expect(calls.editNode?.[0]?.[1]).toContain('const x = 42') }) + it('edit_pipeline_node renames a node by summary alone, and asks for one when missing', async () => { + const body = { language: 'bun' as const, content: 'const x = 1\n' } + const { helpers, calls } = makeHelpers({ getNodeBody: async () => body }) + const run = (args: Record<string, unknown>) => + toolByName('edit_pipeline_node').fn({ + args: { path: 'f/analytics/orders', ...args }, + workspace: 'w', + helpers, + toolCallbacks: noopCallbacks(), + toolId: 't' + }) + await run({ summary: 'Clean orders' }) + expect(calls.editNode?.[0]).toEqual(['f/analytics/orders', body.content, 'Clean orders']) + + const bare = makeHelpers({ + getNodeBody: async () => body, + editNode: async () => ({ summary: '', detectedReads: [], detectedWrites: [] }) + }) + const out = await toolByName('edit_pipeline_node').fn({ + args: { path: 'f/analytics/orders', old_string: 'x = 1', new_string: 'x = 2' }, + workspace: 'w', + helpers: bare.helpers, + toolCallbacks: noopCallbacks(), + toolId: 't' + }) + expect(out).toContain('has no summary') + }) + it('edit_pipeline_node surfaces a clear error when old_string is absent', async () => { const { helpers } = makeHelpers({ getNodeBody: async () => ({ language: 'bun', content: 'const x = 1\n' }) @@ -182,7 +328,7 @@ describe('pipeline tools', () => { it('mutation tools fail clearly when no pipeline editor is registered', async () => { await expect( toolByName('build_pipeline_node').fn({ - args: { path: 'f/a/b', language: 'bun', content: 'x' }, + args: { path: 'f/a/b', language: 'bun', content: 'x', summary: 'Test node' }, workspace: 'w', helpers: {}, toolCallbacks: noopCallbacks(), @@ -191,14 +337,114 @@ describe('pipeline tools', () => { ).rejects.toThrow(/No pipeline editor is open/) }) + it('remove_pipeline_node drops the pipeline from the changes once its last draft goes', async () => { + const run = async (hasDrafts: boolean) => { + const { helpers } = makeHelpers({ hasDrafts: () => hasDrafts }) + const log: string[] = [] + await toolByName('remove_pipeline_node').fn({ + args: { path: 'f/analytics/clean' }, + workspace: 'w', + helpers, + toolCallbacks: { + ...noopCallbacks(), + onItemModified: (kind, path) => log.push(`modified ${kind}:${path}`), + onItemDiscarded: (kind, path) => log.push(`discarded ${kind}:${path}`) + }, + toolId: 't' + }) + return log + } + expect(await run(false)).toEqual(['discarded data_pipeline:f/analytics/data_pipeline']) + expect(await run(true)).toEqual(['modified data_pipeline:f/analytics/data_pipeline']) + }) + it('test_pipeline_node requires confirmation', () => { expect(toolByName('test_pipeline_node').requiresConfirmation).toBe(true) }) }) +describe('pipeline tools with several editors open', () => { + function editorFor(folder: string, built: string[]): PipelineAIChatHelpers { + return { + ...makeHelpers().helpers.pipelines()[0], + getFolder: () => folder, + getPipelineContext: () => ({ ...sampleContext, folder }), + proposeNode: async (input) => { + built.push(`${folder}:${input.path}`) + return { path: input.path, detectedReads: [], detectedWrites: [] } + } + } + } + const call = (name: string, args: any, editors: PipelineAIChatHelpers[]) => + toolByName(name).fn({ + args, + workspace: 'w', + helpers: { pipelines: () => editors }, + toolCallbacks: noopCallbacks(), + toolId: 't' + }) + + it('remounts an opened folder whose editor another tab replaced', async () => { + const built: string[] = [] + const mounted: PipelineAIChatHelpers[] = [] + const ensured: string[] = [] + await toolByName('build_pipeline_node').fn({ + args: { + path: 'f/sales/clean', + language: 'bun', + content: '// pipeline', + summary: 'Test node' + }, + workspace: 'w', + helpers: { + pipelines: () => mounted, + pipelineFolders: () => ['sales'], + ensurePipeline: async (folder: string) => { + ensured.push(folder) + mounted.push(editorFor(folder, built)) + return mounted[0] + } + }, + toolCallbacks: noopCallbacks(), + toolId: 't' + }) + expect(ensured).toEqual(['sales']) + expect(built).toEqual(['sales:f/sales/clean']) + }) + + it('routes a node to the editor of its folder', async () => { + const built: string[] = [] + const editors = [editorFor('crm', built), editorFor('sales', built)] + await call( + 'build_pipeline_node', + { path: 'f/sales/clean', language: 'bun', content: '// pipeline', summary: 'Test node' }, + editors + ) + expect(built).toEqual(['sales:f/sales/clean']) + await expect( + call( + 'build_pipeline_node', + { path: 'f/other/clean', language: 'bun', content: '// pipeline', summary: 'Test node' }, + editors + ) + ).rejects.toThrow(/open_preview\(kind="pipeline", path="other"\)/) + }) + + it('get_pipeline_graph needs the folder only when it is ambiguous', async () => { + const editors = [editorFor('crm', []), editorFor('sales', [])] + await expect(call('get_pipeline_graph', {}, editors)).rejects.toThrow(/pass the folder/) + expect( + JSON.parse(await call('get_pipeline_graph', { folder: 'f/sales' }, editors)) + ).toMatchObject({ folder: 'sales' }) + expect(JSON.parse(await call('get_pipeline_graph', {}, [editors[0]]))).toMatchObject({ + folder: 'crm' + }) + }) +}) + describe('getPipelinePromptSection', () => { it('names the active folder and the direct-draft workflow', () => { - const section = getPipelinePromptSection(sampleContext) + const section = getPipelinePromptSection([sampleContext.folder]) expect(section).toContain('/pipeline/analytics') expect(section).toContain('build_pipeline_node') expect(section).toContain('directly as unsaved drafts') diff --git a/frontend/src/lib/components/copilot/chat/pipeline/core.ts b/frontend/src/lib/components/copilot/chat/pipeline/core.ts index a1a8f1ad6b..8d71b00279 100644 --- a/frontend/src/lib/components/copilot/chat/pipeline/core.ts +++ b/frontend/src/lib/components/copilot/chat/pipeline/core.ts @@ -1,7 +1,8 @@ import { z } from 'zod' import { $ScriptLang } from '$lib/gen/schemas.gen' import type { ScriptLang } from '$lib/gen' -import { createToolDef, executeTestRun, findAndReplace } from '../shared' +import { createToolDef, executeTestRun, findAndReplace, type ToolCallbacks } from '../shared' +import { PIPELINE_DRAFT_KIND, pipelineBundlePath } from '$lib/pipelinePaths' import { NONE, RUN_PREVIEW, @@ -10,6 +11,11 @@ import { type SessionTool } from '../sessionCapabilities' import type { PipelineOutputKind } from '$lib/components/assets/AssetGraph/pipelineTemplates' +import type { PipelineTriggerDraftKind } from '$lib/components/assets/AssetGraph/types' +import { DRAFTABLE_TRIGGER_KINDS } from '$lib/components/assets/AssetGraph/pipelineTriggerDrafts' +import { scheduleRequestSchema, triggerRequestSchemas } from '../workspaceToolsZod.gen' +import { normalizePipelineFolder } from '$lib/utils/pipelineFolder' +import { parsePipelineAnnotations } from '$lib/components/assets/AssetGraph/parsePipelineAnnotations' // ============================================================================ // Pipeline AI chat tools. @@ -57,6 +63,10 @@ export type PipelineContext = { * small — the page owns the draft Map and canvas rendering. */ export interface PipelineAIChatHelpers { + /** Folder name (no `f/` prefix) of the pipeline this editor shows. */ + getFolder: () => string + /** Whether the folder has any script or trigger draft left. */ + hasDrafts: () => boolean getPipelineContext: () => PipelineContext /** Read a node's source (the in-flight draft body if one exists, else deployed). */ getNodeBody: (path: string) => Promise<{ language: ScriptLang; content: string } | undefined> @@ -68,29 +78,108 @@ export interface PipelineAIChatHelpers { language: ScriptLang content: string outputKind?: PipelineOutputKind + summary?: string }) => Promise<{ path: string; detectedReads: string[]; detectedWrites: string[] }> /** Replace an existing node's body, applied as an unsaved draft. Returns the * re-inferred asset lineage (URIs) so the caller sees the effect of the edit. */ editNode: ( path: string, - content: string - ) => Promise<{ detectedReads: string[]; detectedWrites: string[] }> + content: string, + summary?: string + ) => Promise<{ summary: string; detectedReads: string[]; detectedWrites: string[] }> /** Discard the unsaved draft at a path (undo a build_pipeline_node). */ removeProposedNode: (path: string) => Promise<void> + /** Trigger kinds the node declares (`on <kind>`) that no trigger row or draft fills. */ + unconfiguredTriggers: (path: string) => Promise<PipelineTriggerDraftKind[]> + /** Attach (or replace) the node's trigger draft of that kind, deployed with the + * pipeline. `config` is the kind's trigger config; path/script_path are filled in. */ + setNodeTrigger: ( + path: string, + kind: PipelineTriggerDraftKind, + config: Record<string, any> + ) => Promise<{ path: string; replaced: boolean }> /** Preview-run a node (draft body preferred). Returns the started job id. */ testNode: (path: string, args?: Record<string, any>) => Promise<string | undefined> } -/** Helper bag the pipeline tools receive from the manager in global mode. */ -export type PipelineToolHelpers = { pipeline?: PipelineAIChatHelpers } +/** Helper bag the pipeline tools receive from the manager in global mode: every + * pipeline editor currently open, one per folder. */ +export type PipelineToolHelpers = { + pipelines?: () => readonly PipelineAIChatHelpers[] + /** Folders the chat may work on, including ones whose editor is not mounted now. */ + pipelineFolders?: () => readonly string[] + /** Remounts the folder's editor (a session reopens its preview tab) and resolves + * to it, or `undefined` when it cannot be brought back. */ + ensurePipeline?: (folder: string) => Promise<PipelineAIChatHelpers | undefined> +} -function requirePipeline(helpers: PipelineToolHelpers): PipelineAIChatHelpers { - if (!helpers?.pipeline) { +/** The folder's editor, remounted when the chat opened it before and something else + * has taken its tab since. */ +async function remount( + helpers: PipelineToolHelpers, + folder: string | undefined +): Promise<PipelineAIChatHelpers | undefined> { + if (!folder || !helpers?.ensurePipeline) return undefined + if (!(helpers.pipelineFolders?.() ?? []).includes(folder)) return undefined + return helpers.ensurePipeline(folder) +} + +function openPipelines(helpers: PipelineToolHelpers): readonly PipelineAIChatHelpers[] { + const open = helpers?.pipelines?.() ?? [] + if (open.length === 0) { throw new Error( 'No pipeline editor is open. Pipeline tools only work on a /pipeline/<folder> page in edit mode.' ) } - return helpers.pipeline + return open +} + +function notOpenError(folder: string, open: readonly PipelineAIChatHelpers[]): Error { + const names = open.map((p) => `'${p.getFolder()}'`).join(', ') + return new Error( + `No pipeline editor is open for folder '${folder}' (open: ${names}). Open it with open_preview(kind="pipeline", path="${folder}") first.` + ) +} + +/** The editor of the pipeline a node path belongs to (`f/<folder>/<node>`). With a + * single editor open, a path outside it still goes to that editor, whose own check + * names the corrected path. */ +async function pipelineForPath( + helpers: PipelineToolHelpers, + path: string +): Promise<PipelineAIChatHelpers> { + const folder = path.match(/^f\/([^/]+)\//)?.[1] + const live = folder ? helpers?.pipelines?.().find((p) => p.getFolder() === folder) : undefined + const match = live ?? (await remount(helpers, folder)) + if (match) return match + const open = openPipelines(helpers) + if (open.length === 1) return open[0] + throw folder + ? notOpenError(folder, open) + : new Error( + `'${path}' is not a pipeline node path — nodes live at f/<folder>/<node_name>, with <folder> one of: ${open.map((p) => `'${p.getFolder()}'`).join(', ')}.` + ) +} + +async function pipelineForFolder( + helpers: PipelineToolHelpers, + folder: string | undefined +): Promise<PipelineAIChatHelpers> { + const known = helpers?.pipelineFolders?.() ?? [] + const name = folder ? normalizePipelineFolder(folder) : known.length === 1 ? known[0] : undefined + const live = name ? helpers?.pipelines?.().find((p) => p.getFolder() === name) : undefined + const remounted = live ?? (await remount(helpers, name)) + if (remounted) return remounted + const open = openPipelines(helpers) + if (folder) { + const match = open.find((p) => p.getFolder() === name) + if (!match) throw notOpenError(normalizePipelineFolder(folder), open) + return match + } + if (open.length === 1) return open[0] + throw new Error( + `Several pipeline editors are open (${open.map((p) => `'${p.getFolder()}'`).join(', ')}) — pass the folder to read.` + ) } const scriptLangSchema = z.enum($ScriptLang.enum) @@ -105,12 +194,20 @@ const outputKindSchema = z // Read tools // ---------------------------------------------------------------------------- -const getPipelineGraphSchema = z.object({}) +const getPipelineGraphSchema = z.object({ + folder: z + .string() + .optional() + .describe( + 'Folder of the pipeline to read (e.g. `analytics`). Required when several pipeline editors are open; may be omitted when only one is.' + ) +}) const getPipelineGraphToolDef = createToolDef( getPipelineGraphSchema, 'get_pipeline_graph', - "Read the live pipeline graph for the open /pipeline/<folder> editor: its nodes (scripts), each node's language, asset reads/writes, declared triggers, and whether it has an unsaved draft edit. Call this before building or editing nodes so you reuse existing assets/paths and understand the current DAG." + "Read the live pipeline graph of an open /pipeline/<folder> editor: its nodes (scripts), each node's language, asset reads/writes, declared triggers, and whether it has an unsaved draft edit. Call this before building or editing nodes so you reuse existing assets/paths and understand the current DAG.", + { strict: false } ) const readPipelineNodeSchema = z.object({ @@ -127,11 +224,75 @@ const readPipelineNodeToolDef = createToolDef( // Mutation tools (apply directly as unsaved drafts; never deploy) // ---------------------------------------------------------------------------- +const triggerKindEnum = z.enum(DRAFTABLE_TRIGGER_KINDS as [PipelineTriggerDraftKind, ...PipelineTriggerDraftKind[]]) + +const nodeTriggerSchema = z.object({ + kind: triggerKindEnum.describe('Trigger kind; the node must declare `on <kind>`.'), + config: z + .record(z.string(), z.any()) + .describe( + 'The trigger configuration. schedule: { schedule (6-field cron, e.g. "0 0 6 * * *"), timezone (IANA, e.g. "UTC"), args? (the node\'s inputs), summary? }. Any other kind: the fields get_trigger_schema returns for it. path, script_path and is_flow are filled in; pass path only to name the trigger yourself.' + ) +}) + +const setPipelineTriggerSchema = nodeTriggerSchema.extend({ + path: z.string().describe('Workspace path of the node the trigger runs.') +}) + +const setPipelineTriggerToolDef = createToolDef( + setPipelineTriggerSchema, + 'set_pipeline_trigger', + 'Attach the trigger a node declares with `on <schedule|email|kafka|mqtt|amqp|nats|postgres|sqs|gcp>` (its cron, topic, queue…) as an unsaved trigger draft, deployed together with the pipeline. Calling it again for the same node and kind replaces that draft. Webhook and data_upload need no trigger.', + { strict: false } +) + +/** Validates a node trigger's config against the kind's request schema, with the + * fields the pipeline fills in present so they are not reported missing. */ +function validateTriggerConfig( + kind: PipelineTriggerDraftKind, + config: Record<string, any>, + nodePath: string +): Record<string, any> { + const filled = { path: `${nodePath}_${kind}`, script_path: nodePath, is_flow: false, ...config } + if (kind === 'schedule') { + const parsed = scheduleRequestSchema.safeParse({ args: {}, enabled: true, ...filled }) + if (!parsed.success) { + throw new Error( + `Invalid schedule config: ${parsed.error.issues.map((i) => `${i.path.join('.') || '<root>'}: ${i.message}`).join('; ')}` + ) + } + return { args: {}, enabled: true, ...config } + } + const parsed = triggerRequestSchemas[kind].safeParse(filled) + if (!parsed.success) { + throw new Error( + `Invalid config for a "${kind}" trigger. Call get_trigger_schema with kind "${kind}" for its exact fields. Issues: ${parsed.error.issues.map((i) => `${i.path.join('.') || '<root>'}: ${i.message}`).join('; ')}` + ) + } + return config +} + +/** The note every node write ends with while a declared trigger is still unset: the + * node would deploy with nothing to start it. */ +function unconfiguredTriggersNote(path: string, kinds: readonly string[]): string { + if (kinds.length === 0) return '' + return ` ACTION REQUIRED: '${path}' declares \`on ${kinds.join('`, `on ')}\` but has no ${kinds.join('/')} trigger yet, so nothing would start it once deployed. Call set_pipeline_trigger for it now (a schedule needs its cron and timezone; ask the user only if the cadence cannot be inferred).` +} + +const summaryField = z + .string() + .trim() + .min(1) + .max(80) + .describe( + 'Succinct summary of what the node does, a few words in sentence case with no trailing period (e.g. "Ingest Stripe charges", "Daily revenue by region"). It is the title the node shows in the workspace.' + ) + const buildPipelineNodeSchema = z.object({ path: z .string() .describe( - "Workspace path for the new node, e.g. f/<folder>/<name>. Use the open pipeline's folder. Must not collide with an existing node." + 'Workspace path for the new node, e.g. f/<folder>/<name>, in the folder of an open pipeline editor. Must not collide with an existing node.' ), language: scriptLangSchema.describe( 'Script language. SQL-shaped data work uses duckdb (DuckLake/S3) or postgresql (data tables); bun/python3 for general transforms.' @@ -141,7 +302,14 @@ const buildPipelineNodeSchema = z.object({ .describe( "Full script source. Start it with the `pipeline` annotation as a top-of-file comment in the LANGUAGE'S comment syntax — `-- pipeline` for SQL (duckdb/postgresql), `# pipeline` for python3/bash, `// pipeline` for bun/TS — to mark it a pipeline member; declare inputs the same way (e.g. `-- on <asset-uri|schedule|webhook|...>`), and write outputs via the wmill SDK / SQL so the lineage edges are inferred. A `// pipeline` line in a SQL node is a syntax error. Read existing node bodies first to match conventions." ), - output_kind: outputKindSchema.optional() + summary: summaryField, + output_kind: outputKindSchema.optional(), + triggers: z + .array(nodeTriggerSchema) + .optional() + .describe( + 'Triggers for the `on <kind>` lines the content declares (schedule, email, kafka, …), attached as trigger drafts in the same step. Every such declaration needs one; webhook and data_upload need none.' + ) }) const buildPipelineNodeToolDef = createToolDef( @@ -153,8 +321,17 @@ const buildPipelineNodeToolDef = createToolDef( const editPipelineNodeSchema = z.object({ path: z.string().describe('Workspace path of the node to edit.'), - old_string: z.string().min(1).describe("Exact text to find in the node's current source."), - new_string: z.string().describe('Replacement text.'), + old_string: z + .string() + .min(1) + .optional() + .describe("Exact text to find in the node's current source. Omit to change only the summary."), + new_string: z.string().optional().describe('Replacement text.'), + summary: summaryField + .optional() + .describe( + 'New succinct summary (a few words, no trailing period). Pass it whenever the node has none or the edit changes what the node does.' + ), replace_all: z .boolean() .optional() @@ -197,6 +374,12 @@ const testPipelineNodeToolDef = createToolDef( { strict: false } ) +// A pipeline's drafts are one bundle for the whole folder, so that bundle is the +// item a node edit marks as modified — it is what the session deploys as a unit. +function recordPipelineModified(toolCallbacks: ToolCallbacks, pipeline: PipelineAIChatHelpers) { + toolCallbacks.onItemModified?.(PIPELINE_DRAFT_KIND, pipelineBundlePath(pipeline.getFolder())) +} + // Summarize the asset lineage the parser inferred from a just-applied node so the // model gets same-turn feedback on whether its intended edges formed. An empty // result is the useful signal: a write/read expressed via a variable or dynamic @@ -217,8 +400,9 @@ export const pipelineTools: SessionTool<PipelineToolHelpers>[] = [ requires: NONE, def: getPipelineGraphToolDef, planModeSafe: true, - fn: async ({ helpers, toolId, toolCallbacks }) => { - const pipeline = requirePipeline(helpers) + fn: async ({ args, helpers, toolId, toolCallbacks }) => { + const { folder } = getPipelineGraphSchema.parse(args ?? {}) + const pipeline = await pipelineForFolder(helpers, folder) toolCallbacks.setToolStatus(toolId, { content: 'Reading pipeline graph...' }) const ctx = pipeline.getPipelineContext() toolCallbacks.setToolStatus(toolId, { @@ -233,8 +417,8 @@ export const pipelineTools: SessionTool<PipelineToolHelpers>[] = [ def: readPipelineNodeToolDef, planModeSafe: true, fn: async ({ args, helpers, toolId, toolCallbacks }) => { - const pipeline = requirePipeline(helpers) const { path } = readPipelineNodeSchema.parse(args) + const pipeline = await pipelineForPath(helpers, path) toolCallbacks.setToolStatus(toolId, { content: `Reading node '${path}'...` }) const node = await pipeline.getNodeBody(path) if (!node) { @@ -251,20 +435,51 @@ export const pipelineTools: SessionTool<PipelineToolHelpers>[] = [ showDetails: true, showFade: true, fn: async ({ args, helpers, toolId, toolCallbacks }) => { - const pipeline = requirePipeline(helpers) - const { path, language, content, output_kind } = buildPipelineNodeSchema.parse(args) + const { path, language, content, summary, output_kind, triggers } = + buildPipelineNodeSchema.parse(args) + const pipeline = await pipelineForPath(helpers, path) + // Checked before the node is staged, so a bad trigger leaves nothing half-built. + const declared = new Set(parsePipelineAnnotations(content).nativeTriggers.map((n) => n.kind)) + const configs = (triggers ?? []).map((t) => { + if (!declared.has(t.kind)) { + throw new Error( + `The content declares no \`on ${t.kind}\`, so a ${t.kind} trigger has nothing to bind to. Add the annotation line or drop that trigger. Nothing was built.` + ) + } + return { kind: t.kind, config: validateTriggerConfig(t.kind, t.config, path) } + }) toolCallbacks.setToolStatus(toolId, { content: `Building node '${path}'...` }) const { detectedReads, detectedWrites } = await pipeline.proposeNode({ path, language: language as ScriptLang, content, + summary, outputKind: output_kind as PipelineOutputKind | undefined }) + // Recorded as soon as it is staged: a trigger that fails below leaves the node. + recordPipelineModified(toolCallbacks, pipeline) + const attached: string[] = [] + const failed: string[] = [] + for (const t of configs) { + try { + const { path: triggerPath } = await pipeline.setNodeTrigger(path, t.kind, t.config) + attached.push(`${t.kind} '${triggerPath}'`) + } catch (e) { + failed.push(`${t.kind}: ${e instanceof Error ? e.message : String(e)}`) + } + } toolCallbacks.setToolStatus(toolId, { content: `Added draft node '${path}'`, result: 'Success' }) - return `Pipeline node '${path}' added as an unsaved draft on the canvas. It is not deployed — the user deploys it.${inferredLineageNote(detectedReads, detectedWrites)}` + const attachedNote = + (attached.length + ? ` Attached trigger draft${attached.length > 1 ? 's' : ''}: ${attached.join(', ')}.` + : '') + + (failed.length + ? ` The node was built, but these triggers were not attached — fix them with set_pipeline_trigger: ${failed.join('; ')}.` + : '') + return `Pipeline node '${path}' added as an unsaved draft on the canvas. It is not deployed — the user deploys it.${attachedNote}${inferredLineageNote(detectedReads, detectedWrites)}${unconfiguredTriggersNote(path, await pipeline.unconfiguredTriggers(path))}` } }, { @@ -274,36 +489,74 @@ export const pipelineTools: SessionTool<PipelineToolHelpers>[] = [ showDetails: true, showFade: true, fn: async ({ args, helpers, toolId, toolCallbacks }) => { - const pipeline = requirePipeline(helpers) - const { path, old_string, new_string, replace_all } = editPipelineNodeSchema.parse(args) + const { path, old_string, new_string, replace_all, summary } = + editPipelineNodeSchema.parse(args) + if (old_string === undefined && summary === undefined) { + throw new Error('Pass old_string/new_string to change the source, summary to rename it, or both.') + } + const pipeline = await pipelineForPath(helpers, path) const node = await pipeline.getNodeBody(path) if (!node) { return `No pipeline node found at '${path}'. Call get_pipeline_graph to list the available nodes.` } toolCallbacks.setToolStatus(toolId, { content: `Editing node '${path}'...` }) - const updated = findAndReplace( - node.content, - old_string, - new_string, - replace_all ?? false, - 'node source' - ) - const { detectedReads, detectedWrites } = await pipeline.editNode(path, updated) + const updated = + old_string === undefined + ? node.content + : findAndReplace( + node.content, + old_string, + new_string ?? '', + replace_all ?? false, + 'node source' + ) + const edited = await pipeline.editNode(path, updated, summary) + const { detectedReads, detectedWrites } = edited + const summaryNote = edited.summary.trim() + ? '' + : ` '${path}' has no summary: call edit_pipeline_node with just \`summary\` (a few words saying what it does).` + recordPipelineModified(toolCallbacks, pipeline) toolCallbacks.setToolStatus(toolId, { content: `Edited draft '${path}'`, result: 'Success' }) - return `Pipeline node '${path}' updated as an unsaved draft on the canvas (not deployed).${inferredLineageNote(detectedReads, detectedWrites)}` + return `Pipeline node '${path}' updated as an unsaved draft on the canvas (not deployed).${inferredLineageNote(detectedReads, detectedWrites)}${summaryNote}${unconfiguredTriggersNote(path, await pipeline.unconfiguredTriggers(path))}` + } + }, + { + requires: WRITE_DRAFT, + def: setPipelineTriggerToolDef, + showDetails: true, + fn: async ({ args, helpers, toolId, toolCallbacks }) => { + const { path, kind, config } = setPipelineTriggerSchema.parse(args) + const pipeline = await pipelineForPath(helpers, path) + toolCallbacks.setToolStatus(toolId, { content: `Setting the ${kind} trigger of '${path}'...` }) + const valid = validateTriggerConfig(kind, config, path) + const { path: triggerPath, replaced } = await pipeline.setNodeTrigger(path, kind, valid) + recordPipelineModified(toolCallbacks, pipeline) + toolCallbacks.setToolStatus(toolId, { + content: `${replaced ? 'Updated' : 'Attached'} ${kind} trigger '${triggerPath}'`, + result: 'Success' + }) + return `${replaced ? 'Replaced' : 'Attached'} the ${kind} trigger draft '${triggerPath}' on '${path}'. It deploys with the pipeline.${unconfiguredTriggersNote(path, await pipeline.unconfiguredTriggers(path))}` } }, { requires: WRITE_DRAFT, def: removePipelineNodeToolDef, fn: async ({ args, helpers, toolId, toolCallbacks }) => { - const pipeline = requirePipeline(helpers) const { path } = removePipelineNodeSchema.parse(args) + const pipeline = await pipelineForPath(helpers, path) toolCallbacks.setToolStatus(toolId, { content: `Discarding draft '${path}'...` }) await pipeline.removeProposedNode(path) + // With the last draft gone there is nothing left to deploy: the pipeline + // is no longer this chat's change, and listing it would show it deployed. + if (pipeline.hasDrafts()) recordPipelineModified(toolCallbacks, pipeline) + else + toolCallbacks.onItemDiscarded?.( + PIPELINE_DRAFT_KIND, + pipelineBundlePath(pipeline.getFolder()) + ) toolCallbacks.setToolStatus(toolId, { content: `Discarded draft '${path}'`, result: 'Success' @@ -319,8 +572,8 @@ export const pipelineTools: SessionTool<PipelineToolHelpers>[] = [ showDetails: true, autoCollapseDetails: false, fn: async ({ args, workspace, helpers, toolId, toolCallbacks }) => { - const pipeline = requirePipeline(helpers) const { path, args: runArgs } = testPipelineNodeSchema.parse(args) + const pipeline = await pipelineForPath(helpers, path) return executeTestRun({ jobStarter: async () => { const jobId = await pipeline.testNode(path, runArgs ?? undefined) @@ -350,22 +603,35 @@ export const pipelineTools: SessionTool<PipelineToolHelpers>[] = [ * since the tools it names are withheld from that session; the annotation model stays, * as it is what lets the model read and explain an existing pipeline. */ -export function getPipelinePromptSection(ctx: PipelineContext, access?: SessionAccess): string { +export function getPipelinePromptSection( + folders: readonly string[], + access?: SessionAccess +): string { const canWriteDraft = !access || access.has('write_draft') + const [first] = folders + const openLine = + folders.length === 1 + ? `The user has the /pipeline/${first} editor open.` + : `The user has ${folders.length} pipeline editors open: ${folders.map((f) => `/pipeline/${f}`).join(', ')}. Each tool acts on the pipeline its node path's folder names; pass \`folder\` to get_pipeline_graph.` + const pathLine = + folders.length === 1 + ? `Every node of this pipeline lives at \`f/${first}/<node_name>\` — \`${first}\` is the folder name and \`f/\` is the owner prefix every workspace path carries, so write it exactly once (never \`f/f/…\`, and never a bare \`<node_name>\`).` + : `Every node of a pipeline lives at \`f/<folder>/<node_name>\` (e.g. \`f/${first}/<node_name>\`) — \`f/\` is the owner prefix every workspace path carries, so write it exactly once (never \`f/f/…\`, and never a bare \`<node_name>\`). A node can only be built in the folder of an open pipeline editor.` return ` Data Pipeline editor (ACTIVE): -- The user has the /pipeline/${ctx.folder} editor open. A pipeline is a DAG of scripts (nodes) connected by storage assets (DuckLake tables, data tables, S3 objects, volumes, resources) and execution triggers. +- ${openLine} A pipeline is a DAG of scripts (nodes) connected by storage assets (DuckLake tables, data tables, S3 objects, volumes, resources) and execution triggers. - Annotations are top-of-file comments in the NODE'S OWN comment syntax: \`--\` for SQL (duckdb/postgresql), \`#\` for python3/bash, \`//\` for bun/TS. The \`//\` shown below is the TS form — translate it (a \`// pipeline\` line in a SQL node is a syntax error that won't deploy). - A script becomes a pipeline node when its source starts with the \`// pipeline\` annotation. Declare execution-DAG inputs with \`// on <asset-uri | schedule | webhook | email | kafka | mqtt | amqp | nats | postgres | sqs | gcp | data_upload>\` (e.g. \`// on ducklake://main/orders\`). Outputs are inferred from what the body writes (wmill SDK calls / SQL CREATE TABLE / writeS3File); declare a managed output with \`// materialize <asset-uri>\`. Optional badges: \`// partitioned <daily|hourly|weekly|monthly|dynamic>\`, \`// freshness <duration>\`, \`// tag <name>\`, \`// retry <count> [delay]\`, \`// data_test <kind> ...\` (managed DuckLake targets only — deploy rejects it beside a \`dbt://\` target), \`// measure <name> = <agg> [where <pred>]\`, \`// dimension <name> = <expr>\`. -- \`materialize\` (the managed output): a managed \`// materialize ducklake://<name>/<table>\` means the runtime writes the node's output table FOR you — write the body as a single SELECT and the runtime wraps it in the create/replace, so do NOT also write your own CREATE TABLE / INSERT. The \`dbt://\` target below is the opposite: the node writes its own DDL and none of the write strategies apply to it. IMPORTANT: a MANAGED \`// materialize\` is **DuckDB-only** and its target MUST be a DuckLake table (\`ducklake://<name>/<table>\`) — deploy rejects a \`ducklake://\` target on any other language. For a \`python3\`/\`bun\`/\`postgresql\` node writing the lake, do NOT use \`// materialize\`; write the output via the SDK instead (e.g. \`wmill.writeS3File(...)\`, a \`CREATE TABLE\` in postgresql, or \`wmill.databaseUrlFromResource\`/ducklake helpers) and let the output be inferred. Reach for \`duckdb\` when a node should materialize a DuckLake table. The one target any language BUT DBT'S OWN may declare (a dbt project's writes come from its manifest, so \`// materialize\` on a dbt script is rejected at deploy) is a WAREHOUSE RELATION: \`// materialize manual dbt://<warehouse>/<schema>/<name>\`, with \`<warehouse>\` a warehouse the workspace configures under Settings → dbt. \`manual\` is its only mode — nothing generates warehouse DDL, so the node issues its own write and the annotation records the outcome. Use it on an ingestion node a dbt project reads as a \`source\`: the declared relation and the dbt model become ONE graph node, and a downstream \`// on dbt://<warehouse>/<schema>/<name>\` fires when that node completes. Write strategy: with no option it REPLACES the whole table each run (full refresh; the only mode whose output columns may change); \`// materialize <uri> append\` INSERT-appends rows (incremental); \`// materialize <uri> key=<col>\` merges/upserts on \`<col>\`. \`// materialize manual <uri>\` opts OUT of managed writes — the script writes its own DDL and the annotation only records the output asset for lineage. \`materialize\` is paired with partitioning for incremental pipelines: a \`// partitioned <daily|hourly|weekly|monthly|dynamic>\` node runs once per partition (append/merge into a fixed-schema table), and the \`{partition}\` token — usable in any asset URI AND in the body SQL — is substituted with the current partition's IDENTITY string at run time. To filter the source to the active slice on a time grain, use the runtime-injected macro: \`WHERE wm_partition(<ts_col>) = {partition}\`. \`wm_partition(ts)\` buckets a timestamp with the exact identity format the runtime used (daily/hourly/weekly/monthly), so it always matches and you never hand-write a \`strftime\` format. Do NOT write \`= TIMESTAMP {partition}\`: the identity string is not a valid timestamp literal for hourly/weekly/monthly and errors at runtime. For \`dynamic\` partitioning the identity is your caller-supplied key (not a timestamp, no macro), so filter on it directly: \`WHERE <your_key_col> = {partition}\`. \`materialize\` is an output DECLARATION on the node — it is not a command; there is no "materialize run". +- \`materialize\` (the managed output): a managed \`// materialize ducklake://<name>/<table>\` means the runtime writes the node's output table FOR you — write the body as a single SELECT and the runtime wraps it in the create/replace, so do NOT also write your own CREATE TABLE / INSERT. The \`dbt://\` target below is the opposite: the node writes its own DDL and none of the write strategies apply to it. IMPORTANT: a MANAGED \`// materialize\` is **DuckDB-only** and its target MUST be a DuckLake table (\`ducklake://<name>/<table>\`) — deploy rejects a \`ducklake://\` target on any other language. For a \`python3\`/\`bun\`/\`postgresql\` node writing the lake, do NOT use \`// materialize\`; write the table straight into DuckLake with \`wmill.ducklake()\` (or a data table with \`wmill.datatable()\`), or a \`CREATE TABLE\` in postgresql and let the output be inferred. Reach for \`duckdb\` when a node should materialize a DuckLake table. The one target any language BUT DBT'S OWN may declare (a dbt project's writes come from its manifest, so \`// materialize\` on a dbt script is rejected at deploy) is a WAREHOUSE RELATION: \`// materialize manual dbt://<warehouse>/<schema>/<name>\`, with \`<warehouse>\` a warehouse the workspace configures under Settings → dbt. \`manual\` is its only mode — nothing generates warehouse DDL, so the node issues its own write and the annotation records the outcome. Use it on an ingestion node a dbt project reads as a \`source\`: the declared relation and the dbt model become ONE graph node, and a downstream \`// on dbt://<warehouse>/<schema>/<name>\` fires when that node completes. Write strategy: with no option it REPLACES the whole table each run (full refresh; the only mode whose output columns may change); \`// materialize <uri> append\` INSERT-appends rows (incremental); \`// materialize <uri> key=<col>\` merges/upserts on \`<col>\`. \`// materialize manual <uri>\` opts OUT of managed writes — the script writes its own DDL and the annotation only records the output asset for lineage. \`materialize\` is paired with partitioning for incremental pipelines: a \`// partitioned <daily|hourly|weekly|monthly|dynamic>\` node runs once per partition (append/merge into a fixed-schema table), and the \`{partition}\` token — usable in any asset URI AND in the body SQL — is substituted with the current partition's IDENTITY string at run time. To filter the source to the active slice on a time grain, use the runtime-injected macro: \`WHERE wm_partition(<ts_col>) = {partition}\`. \`wm_partition(ts)\` buckets a timestamp with the exact identity format the runtime used (daily/hourly/weekly/monthly), so it always matches and you never hand-write a \`strftime\` format. Do NOT write \`= TIMESTAMP {partition}\`: the identity string is not a valid timestamp literal for hourly/weekly/monthly and errors at runtime. For \`dynamic\` partitioning the identity is your caller-supplied key (not a timestamp, no macro), so filter on it directly: \`WHERE <your_key_col> = {partition}\`. \`materialize\` is an output DECLARATION on the node — it is not a command; there is no "materialize run". - \`measure\` / \`dimension\` (declared metrics): on a node that materializes a DuckLake table, \`// measure <name> = <aggregate> [where <predicate>]\` names the canonical way to aggregate that table (e.g. \`// measure revenue = sum(amount) where not is_refund\`), and \`// dimension <name> = <expr>\` names a way to slice it (e.g. \`// dimension region = region\`, \`// dimension month = date_trunc('month', ordered_at)\`). They execute nothing: they are catalogued at deploy so the editor and other agents can reuse the definition instead of re-deriving it and silently disagreeing. Keep the predicate in the \`where\` clause rather than folding it into the aggregate: it is rendered as \`<agg> FILTER (WHERE <pred>)\`, which is what lets two measures with different predicates sit under one GROUP BY. DuckLake-only, and only meaningful next to \`// materialize\`. Declare one when a number carries a judgement call someone else would get wrong (refunds excluded, test rows dropped, which column is the amount); do NOT blanket every table with measures, an obvious \`count(*)\` earns nothing. To USE a metric another node declares, read that node with read_pipeline_node and reuse its exact expression rather than guessing it. - Use get_pipeline_graph to see the current nodes/assets/triggers, and read_pipeline_node before editing one. -- Every node of this pipeline lives at \`f/${ctx.folder}/<node_name>\` — \`${ctx.folder}\` is the folder name and \`f/\` is the owner prefix every workspace path carries, so write it exactly once (never \`f/f/…\`, and never a bare \`<node_name>\`).${ +- ${pathLine}${ canWriteDraft ? ` -- Build new nodes with build_pipeline_node and edit existing ones with edit_pipeline_node. These apply directly as unsaved drafts on the canvas (like the flow/script editor applies AI edits) — they DO NOT deploy. There is no separate Accept/Reject step. Prefer these over the generic write_script/edit_script draft tools while a pipeline is open. +- Build new nodes with build_pipeline_node and edit existing ones with edit_pipeline_node. Give every node a succinct \`summary\` (a few words saying what it does, e.g. "Ingest Stripe charges"), and update it when an edit changes what the node does. These apply directly as unsaved drafts on the canvas (like the flow/script editor applies AI edits) — they DO NOT deploy. There is no separate Accept/Reject step. Prefer these over the generic write_script/edit_script draft tools while a pipeline is open. - Reuse existing asset paths from the graph when wiring a downstream node to an upstream one (read the upstream's write asset, then \`// on\` that same URI). +- TRIGGERS: an ingestion node (one with no upstream asset to react to) must declare how it starts, e.g. \`// on schedule\`, and every \`on <schedule|email|kafka|mqtt|amqp|nats|postgres|sqs|gcp>\` line needs its trigger: pass it in build_pipeline_node's \`triggers\` (or call set_pipeline_trigger) in the same step you build the node. A schedule needs a 6-field cron and an IANA timezone — pick a sensible cadence from the request (e.g. daily at 06:00 UTC for a daily sync) rather than leaving it empty; for the other kinds call get_trigger_schema(kind) for the config fields and ask the user for any connection/resource you cannot find. Never leave a declared trigger without one: the node would deploy with nothing to start it. \`webhook\` and \`data_upload\` need no trigger. - Only deploy when the user explicitly asks; the user deploys drafts from the canvas.` : '' }` diff --git a/frontend/src/lib/components/copilot/chat/readOnlyChatViewHost.svelte.ts b/frontend/src/lib/components/copilot/chat/readOnlyChatViewHost.svelte.ts new file mode 100644 index 0000000000..1e22903e9b --- /dev/null +++ b/frontend/src/lib/components/copilot/chat/readOnlyChatViewHost.svelte.ts @@ -0,0 +1,85 @@ +import { AIAutonomyMode } from './AIChatManager.svelte' +import type { ChatViewHost } from './chatViewHost' +import type { DisplayMessage } from './shared' +import { AttachedFilesStore } from './files/attachedFiles.svelte' +import { SessionArtifactsStore } from './artifacts/artifactsState.svelte' +import type { PersistedArtifact } from './artifacts/artifactsDB' + +const noop = () => {} + +/** + * A host over a finished transcript nobody can continue: every affordance that would send, + * edit, retry or answer is off, so the chat components render it as a record. + */ +export function readOnlyChatViewHost(options: { + messages: DisplayMessage[] + workspace: string + artifacts: PersistedArtifact[] + openArtifact: (artifactId: string) => void +}): ChatViewHost { + const artifacts = new SessionArtifactsStore() + artifacts.artifacts = options.artifacts + return { + displayMessages: options.messages, + messages: [], + contextTokens: 0, + operatingWorkspace: options.workspace, + loading: false, + sendPending: false, + runHeldElsewhere: false, + loadingLabel: undefined, + compacting: false, + currentReply: '', + currentReasoning: '', + currentReasoningActive: false, + reasoningHiddenIndicatorLabel: undefined, + automaticScroll: false, + enableAutomaticScroll: noop, + disableAutomaticScroll: noop, + + instructions: '', + sendInFlight: false, + sendRequest: async () => false, + cancel: noop, + setAiChatInput: noop, + queuedMessage: '', + queuedContext: undefined, + queuedImages: [], + queuedFiles: [], + queuedBlobs: [], + queueMessage: noop, + dequeueMessage: noop, + setComposerStaged: noop, + setComposerHasDraft: noop, + clearComposerStaged: noop, + attachmentBytesExcluding: () => 0, + + storedImages: () => undefined, + retryRequest: noop, + restartGeneration: noop, + handleUserQuestionAnswer: () => false, + handleToolConfirmation: noop, + hasPendingRunForm: false, + isRunFormPending: () => false, + + isSessionChat: true, + untrustedTranscript: true, + supportsModelSettings: false, + supportsMessageEditing: false, + supportsMessageAttachments: false, + requiresMessageText: false, + supportsLinkedFolders: false, + attachmentAccept: '', + attachmentsAsBlobs: false, + tools: [], + autonomyMode: AIAutonomyMode.DEFAULT, + setAutonomyMode: noop, + autoAcceptEditsActive: false, + autoAcceptEditsAvailable: false, + autoAcceptToolConfirmationsAvailable: false, + planModeAvailable: false, + attachedFiles: new AttachedFilesStore(), + artifacts, + openArtifact: (artifactId) => options.openArtifact(artifactId) + } +} diff --git a/frontend/src/lib/components/copilot/chat/script/CodeDisplay.svelte b/frontend/src/lib/components/copilot/chat/script/CodeDisplay.svelte index 2be52a32d2..e83c163302 100644 --- a/frontend/src/lib/components/copilot/chat/script/CodeDisplay.svelte +++ b/frontend/src/lib/components/copilot/chat/script/CodeDisplay.svelte @@ -3,11 +3,13 @@ import MarkdownCodeBlock from '$lib/components/MarkdownCodeBlock.svelte' import { AIMode } from '../AIChatManager.svelte' import { getAiChatManager } from '../aiChatManagerContext' + import { getChatViewHost } from '../chatViewHost' import { Check, Play } from 'lucide-svelte' // Chat `pre` renderer: the shared MarkdownCodeBlock plus the chat-only Apply // button (wired to the script editor) and mermaid diagrams. const aiChatManager = getAiChatManager() + const chatHost = getChatViewHost() const astNode = getAstNode() let code = $derived(astNode.current.children?.[0]?.children?.[0]?.value) @@ -34,5 +36,5 @@ {showApplyButton} onApplyCode={handleApplyCode} applyButtonIcon={aiChatManager.pendingNewCode ? Check : Play} - renderMermaid + renderMermaid={!chatHost.untrustedTranscript} /> diff --git a/frontend/src/lib/components/copilot/chat/script/core.test.ts b/frontend/src/lib/components/copilot/chat/script/core.test.ts index f235ae3796..2a6c37ca71 100644 --- a/frontend/src/lib/components/copilot/chat/script/core.test.ts +++ b/frontend/src/lib/components/copilot/chat/script/core.test.ts @@ -14,7 +14,50 @@ vi.mock('@codingame/monaco-vscode-standalone-typescript-language-features', () = vi.mock('@codingame/monaco-vscode-languages-service-override', () => ({ default: () => ({}) })) vi.mock('$lib/components/vscode', () => ({})) -import { editCodeToolWithDiff } from './core' +import { ResourceService } from '$lib/gen' +import { + editCodeToolWithDiff, + resolveResourceTypeSync, + resourceTypeSyncBlock, + searchResourceTypes +} from './core' + +describe('searchResourceTypes', () => { + it.each([ + [['ai_skill', 'ai_instruction'], true], + [Array.from({ length: 30 }, (_, i) => `type_${i}`), false] + ])('notes only an instance that never synced with the hub (%#)', async (names, noted) => { + vi.spyOn(ResourceService, 'queryResourceTypes').mockResolvedValue([ + { name: 'ai_skill', score: 0.8 } + ]) + vi.spyOn(ResourceService, 'listResourceTypeNames').mockResolvedValue(names) + + const { note } = await searchResourceTypes('stripe', 'ws', 5) + + expect(note?.includes('never synced') ?? false).toBe(noted) + }) +}) + +// The transition is what keeps the note out of the system prompt: a conversation that was +// told "not synced" has to be told once when that stops being true, and nobody else is. +describe('resolveResourceTypeSync', () => { + const synced = Array.from({ length: 30 }, (_, i) => `type_${i}`) + const told = (state: 'unsynced' | 'now_synced') => ({ + role: 'user', + content: resourceTypeSyncBlock(state) + }) + + it.each([ + ['unsynced instance', ['ai_skill'], [], 'unsynced'], + ['always synced', synced, [], undefined], + ['synced after an unsynced note', synced, [told('unsynced')], 'now_synced'], + ['already told it synced', synced, [told('unsynced'), told('now_synced')], undefined] + ] as const)('%s', async (label, names, history, expected) => { + vi.spyOn(ResourceService, 'listResourceTypeNames').mockResolvedValue([...names]) + + expect(await resolveResourceTypeSync(`ws-${label}`, history)).toBe(expected) + }) +}) describe('editCodeToolWithDiff', () => { it('records the complete script diff after applying replacements', async () => { diff --git a/frontend/src/lib/components/copilot/chat/script/core.ts b/frontend/src/lib/components/copilot/chat/script/core.ts index 92cb889b24..b732e00c05 100644 --- a/frontend/src/lib/components/copilot/chat/script/core.ts +++ b/frontend/src/lib/components/copilot/chat/script/core.ts @@ -1,4 +1,4 @@ -import { ResourceService, JobService } from '$lib/gen/services.gen' +import { ResourceService, JobService } from '$lib/gen' import type { AIProvider, AIProviderModel, ResourceType, ScriptLang } from '$lib/gen/types.gen' import { capitalize, toCamel } from '$lib/utils' import { compile, phpCompile, pythonCompile } from '../../utils' @@ -19,7 +19,8 @@ import { type ScriptLintResult, formatScriptLintResult, createSearchWorkspaceTool, - createGetRunnableDetailsTool + createGetRunnableDetailsTool, + HUB_SYNC_INSTRUCTIONS } from '../shared' import { createWorkspaceMutationTools } from '../workspaceTools' import { setupTypeAcquisition, type DepsToGet } from '$lib/ata' @@ -41,7 +42,7 @@ const TYPES_CONTEXT_PERCENTAGE = 1 export const DIFF_BASED_EDIT_PROVIDERS: AIProvider[] = [] export function formatResourceTypes( - allResourceTypes: ResourceType[], + allResourceTypes: Pick<ResourceType, 'name' | 'schema'>[], lang: 'python3' | 'php' | 'bun' | 'deno' | 'nativets' | 'bunnative' ) { if (lang === 'python3') { @@ -67,14 +68,75 @@ export function formatResourceTypes( } } -async function getResourceTypes(prompt: string, workspace: string) { - const resourceTypes = await ResourceService.queryResourceTypes({ - workspace: workspace, - text: prompt, - limit: 5 - }) +// The hub publishes hundreds of resource types and an instance seeds only a few of its own, +// so fewer than this means the instance never synced with the hub. +const UNSYNCED_RESOURCE_TYPE_COUNT = 20 - return resourceTypes +/** + * The note on an unsynced instance cannot wait for an empty result: the similarity search + * still returns the nearest of the few types there are (the instance's own `ai_skill` scores + * about 0.8 for "confluence"). + */ +export async function searchResourceTypes( + query: string, + workspace: string, + limit: number +): Promise<{ resourceTypes: Pick<ResourceType, 'name' | 'schema'>[]; note?: string }> { + const [resourceTypes, names] = await Promise.all([ + ResourceService.queryResourceTypes({ workspace, text: query, limit }), + ResourceService.listResourceTypeNames({ workspace }).catch(() => []) + ]) + const count = new Set(names).size + return { + resourceTypes, + note: + count > 0 && count < UNSYNCED_RESOURCE_TYPE_COUNT + ? `Only ${count} resource types exist on this instance, so it has most likely never synced with the Windmill Hub, which has types for most services. ${HUB_SYNC_INSTRUCTIONS}` + : undefined + } +} + +export type ResourceTypeSync = 'unsynced' | 'now_synced' + +const NOT_SYNCED_HEADING = '## RESOURCE TYPES NOT SYNCED' +const SYNCED_HEADING = '## RESOURCE TYPES SYNCED' + +// An instance does not go back to unsynced, so one seen synced is never asked again. +const syncedWorkspaces = new Set<string>() + +/** + * Whether the next user message has to say the instance lacks the hub's types, or that an + * earlier such note no longer holds. It rides in the user message, not the system prompt, + * so a sync during a conversation leaves the cached prefix untouched; `history` is what + * tells a sync that happened mid-conversation from an instance that was always synced. + */ +export async function resolveResourceTypeSync( + workspace: string, + history: readonly { role: string; content?: unknown }[] +): Promise<ResourceTypeSync | undefined> { + if (!syncedWorkspaces.has(workspace)) { + const count = await ResourceService.listResourceTypeNames({ workspace }) + .then((names) => new Set(names).size) + .catch(() => 0) + if (count === 0) { + return undefined + } + if (count < UNSYNCED_RESOURCE_TYPE_COUNT) { + return 'unsynced' + } + syncedWorkspaces.add(workspace) + } + const lastNote = history + .filter((m) => m.role === 'user') + .map((m) => (typeof m.content === 'string' ? m.content : JSON.stringify(m.content ?? ''))) + .findLast((text) => text.includes(NOT_SYNCED_HEADING) || text.includes(SYNCED_HEADING)) + return lastNote?.includes(NOT_SYNCED_HEADING) ? 'now_synced' : undefined +} + +export function resourceTypeSyncBlock(state: ResourceTypeSync): string { + return state === 'unsynced' + ? `${NOT_SYNCED_HEADING}\nThis instance has not synced the Windmill Hub's resource types, so no hub type exists here yet (stripe, slack, postgresql, ...), including the one a hub script takes. ${HUB_SYNC_INSTRUCTIONS}\n\n` + : `${SYNCED_HEADING}\nThe instance now holds the Windmill Hub's resource types: the earlier "not synced" note no longer applies.\n\n` } export const SUPPORTED_CHAT_SCRIPT_LANGUAGES = [ @@ -149,13 +211,14 @@ export async function getFormattedResourceTypes( case 'bunnative': case 'python3': case 'php': { - const resourceTypes = await getResourceTypes(prompt, workspace) + const { resourceTypes, note } = await searchResourceTypes(prompt, workspace, 5) - const intro = `RESOURCE_TYPES:\n` + const found = + resourceTypes.length > 0 + ? `RESOURCE_TYPES:\n${formatResourceTypes(resourceTypes, lang)}` + : `No resource type found for "${prompt}".` - const resourceTypesText = formatResourceTypes(resourceTypes, lang) - - return intro + resourceTypesText + return note ? `${found}\n\n${note}` : found } default: return '' diff --git a/frontend/src/lib/components/copilot/chat/sessionCapabilities.ts b/frontend/src/lib/components/copilot/chat/sessionCapabilities.ts index fc77b3e1c4..b06c41850e 100644 --- a/frontend/src/lib/components/copilot/chat/sessionCapabilities.ts +++ b/frontend/src/lib/components/copilot/chat/sessionCapabilities.ts @@ -9,17 +9,44 @@ import type { Tool } from './shared' * what the model is offered and guarantees nothing. */ export type SessionCapability = - /** Passes drafts.rs `require_can_write_path` — for a draft of any kind, schedules and - * triggers included, though an operator may create those directly. */ + /** Passes drafts.rs `require_can_write_path` for a draft of any kind. A tool writing only + * schedule or trigger drafts requires the narrower capability below instead, which an + * operator can hold. */ | 'write_draft' + /** Passes `require_can_write_path` for a flow draft, which an operator also passes where the + * workspace grants `builder_flows`. The server then refuses a draft carrying inline code. */ + | 'write_flow_draft' + /** The same for a raw app draft, under `builder_apps`. */ + | 'write_app_draft' + /** Passes `require_can_write_path` for a schedule draft: everyone `write_draft` covers, and an + * operator unless the workspace set `manage_schedules` to false. */ + | 'write_schedule_draft' + /** The same for a trigger draft, read from `manage_triggers`. */ + | 'write_trigger_draft' + /** Passes `require_can_write_path` for a resource draft, which every operator does. */ + | 'write_resource_draft' + /** The same for a variable draft. */ + | 'write_variable_draft' /** Passes the operator refusal jobs.rs `run_preview_*` makes before starting a job. */ | 'run_preview' + /** Passes `run_preview_flow`'s `check_operator_can_build_flows`: composed flows only, for an + * operator with `builder_flows`. */ + | 'run_flow_preview' /** Passes `check_deploy_rules`. */ | 'deploy' - /** Passes the operator refusal the script, flow and app handlers make before creating or + /** Passes the operator refusal the script handlers make before creating or * deleting one. The same condition as `run_preview` today, but another handler family's * check, so each follows its own gate if the two ever diverge. */ | 'manage_code' + /** Passes the flow handlers' `check_operator_can_build_flows`. */ + | 'manage_flows' + /** Passes the raw app handlers' `check_operator_can_build`, read from `builder_apps`. */ + | 'manage_apps' + /** Passes `gate_operator_writes` on the schedule router: withheld only from an operator whose + * workspace set `operator_settings.manage_schedules` to false. */ + | 'manage_schedules' + /** The same gate on the trigger routers, read from `manage_triggers`. */ + | 'manage_triggers' /** Passes `require_admin`. */ | 'admin' @@ -36,9 +63,29 @@ export type SessionToolPolicy = readonly SessionCapability[] export const NONE: SessionToolPolicy = [] export const WRITE_DRAFT: SessionToolPolicy = ['write_draft'] +export const WRITE_FLOW_DRAFT: SessionToolPolicy = ['write_flow_draft'] +export const WRITE_APP_DRAFT: SessionToolPolicy = ['write_app_draft'] +export const WRITE_SCHEDULE_DRAFT: SessionToolPolicy = ['write_schedule_draft'] +export const WRITE_TRIGGER_DRAFT: SessionToolPolicy = ['write_trigger_draft'] +export const WRITE_RESOURCE_DRAFT: SessionToolPolicy = ['write_resource_draft'] +export const WRITE_VARIABLE_DRAFT: SessionToolPolicy = ['write_variable_draft'] export const RUN_PREVIEW: SessionToolPolicy = ['run_preview'] +export const RUN_FLOW_PREVIEW: SessionToolPolicy = ['run_flow_preview'] export const DEPLOY: SessionToolPolicy = ['deploy'] +/** Editors a session can open. Every editor autosaves a draft, so it needs the draft + * capability of its kind; a pipeline's nodes are script drafts. */ +export type EditorKind = 'script' | 'flow' | 'raw_app' | 'pipeline' + +/** Whether `access` can save what the `kind` editor writes. `undefined` access (not + * resolved yet, or not a session) answers true, as the toolset filter does. */ +export function canOpenEditor(access: SessionAccess | undefined, kind: EditorKind): boolean { + if (!access) return true + return access.has( + kind === 'flow' ? 'write_flow_draft' : kind === 'raw_app' ? 'write_app_draft' : 'write_draft' + ) +} + /** * A tool that can reach an AI session's toolset. `requires` is mandatory, and declared * beside the `fn` whose call is what proves it right. diff --git a/frontend/src/lib/components/copilot/chat/shared.test.ts b/frontend/src/lib/components/copilot/chat/shared.test.ts index ff7c59d6cb..5a3427006e 100644 --- a/frontend/src/lib/components/copilot/chat/shared.test.ts +++ b/frontend/src/lib/components/copilot/chat/shared.test.ts @@ -395,6 +395,30 @@ describe('processToolCall', () => { expect(result.content).toBe(`Error while calling tool: ${expectedError}`) }) + it('resolves a tool registered earlier in the same batch from the live set', async () => { + const { createToolDef, processToolCall } = await import('./shared') + const fn = vi.fn().mockResolvedValue('built') + const registered = { + def: createToolDef(z.object({}), 'build_pipeline_node', 'Build node'), + fn + } + const result = await processToolCall({ + tools: [], + live: () => ({ tools: [registered], helpers: { pipelines: true } }), + toolCall: { + id: 'call_live', + type: 'function', + function: { name: 'build_pipeline_node', arguments: '{}' } + }, + helpers: {}, + workspace: 'test-workspace', + toolCallbacks: { setToolStatus: vi.fn(), removeToolStatus: vi.fn() } + }) + + expect(result.content).toBe('built') + expect(fn).toHaveBeenCalledWith(expect.objectContaining({ helpers: { pipelines: true } })) + }) + it('continues to confirmation when pre-confirmation validation passes', async () => { const { createToolDef, processToolCall } = await import('./shared') const fn = vi.fn().mockResolvedValue('ok') diff --git a/frontend/src/lib/components/copilot/chat/shared.ts b/frontend/src/lib/components/copilot/chat/shared.ts index 6897a22444..a6ce735230 100644 --- a/frontend/src/lib/components/copilot/chat/shared.ts +++ b/frontend/src/lib/components/copilot/chat/shared.ts @@ -571,6 +571,10 @@ export type RunFormDisplay = { /** What is being run, for the noun the card says it in. * Absent on cards recorded before flows had a form, which were all scripts. */ runnableKind?: 'script' | 'flow' + /** The deployed page of this item is a conversation, not a run form — a chat-enabled + * flow. Its page can be opened to look at, but it has no form to confirm this call on, so + * the card keeps the run. */ + conversational?: boolean /** Of whatever version is about to run: the deployed script, or the draft a test * previews. Only the rendered form reads it, so it is dropped once one of the flags * below unmounts that form: kept, every settled card would carry a copy of the schema @@ -606,6 +610,16 @@ export type RunFormDisplay = { /** What a run form is being filled with while it waits. Held by the chat manager, not by * the form, so the chat card and the preview pane edit one draft rather than two copies. * The schema rides along because SchemaForm binds and reorders it. */ +/** How a parked run form is answered. `args` for a form the tool then runs itself; `job` for + * a run the reader already started on the item's own page, which the tool follows instead. */ +export type RunFormAnswer = + | { kind: 'args'; args: Record<string, any> } + /** A job another surface already started. Its `args` are what that surface sent, already + * coerced and minted by its own form, so they are reported rather than processed, and + * `schema` is the one it ran against — which redaction needs, since it only visits the + * leaves a schema declares. */ + | { kind: 'job'; jobId: string; args: Record<string, any>; schema: Record<string, any> } + export type RunFormDraft = { args: Record<string, any> schema: Record<string, any> @@ -834,6 +848,13 @@ async function callTool<T>({ }): Promise<string> { const tool = tools.find((t) => t.def.function.name === functionName) if (!tool) { + // The pipeline tools exist only while a pipeline editor is mounted, and change_mode + // cannot mount one, so the generic hint would send the model probing. + if (/_pipeline_node$|^get_pipeline_graph$/.test(functionName)) { + throw new Error( + `${functionName} is not available yet: no pipeline editor is open for this chat. Call open_preview(kind="pipeline", path="<folder>") first and wait for its result; once it reports the editor open, the pipeline tools are callable. Do not fall back to write_script.` + ) + } throw new Error( `Unknown tool call: ${functionName}. Probably not in the correct mode, use the change_mode tool to switch to the correct mode.` ) @@ -924,22 +945,33 @@ type ToolCallStatus = | 'blocked_plan_mode' | 'held_for_instructions' +/** Re-reads the chat loop's current tools and helpers. A call earlier in the same + * response can register tools (open_preview mounting the pipeline editor, change_mode), + * so a later call in that batch must resolve against the live set, not the snapshot the + * response was requested with. */ +export type LiveToolSet = () => { tools: Tool<any>[]; helpers: any } + export async function processToolCall<T>({ - tools, + tools: snapshotTools, toolCall, - helpers, + helpers: snapshotHelpers, toolCallbacks, workspace, - messages = [] + messages = [], + live }: { tools: Tool<T>[] toolCall: ChatCompletionMessageFunctionToolCall helpers: T + live?: LiveToolSet toolCallbacks: ToolCallbacks workspace?: string /** The conversation so far, for which folder instructions it already carries. */ messages?: readonly ChatCompletionMessageParam[] }): Promise<ChatCompletionMessageParam> { + const current = live?.() + const tools: Tool<T>[] = current?.tools ?? snapshotTools + const helpers: T = current ? current.helpers : snapshotHelpers const tool = tools.find((t) => t.def.function.name === toolCall.function.name) const workspaceId = workspace ?? get(workspaceStore) ?? '' @@ -1419,9 +1451,14 @@ export interface ToolCallbacks { toolId: string, form: RunFormDisplay, opts?: { autoAccepted?: boolean } - ) => Promise<Record<string, any> | undefined> + ) => Promise<RunFormAnswer | undefined> /** The submitted form's job is queued. Wired alongside requestRunArgs. */ markRunFormStarted?: (toolId: string) => void + /** The submitted form will never produce a job: the server refused it, a sensitive + * argument could not be stored, or plan mode blocked it after the arguments were handed + * over. The mirror of `markRunFormStarted`, and the only way a surface that confirmed the + * run can tell that it is over — the call settles with neither a job nor a cancellation. */ + markRunFormEnded?: (toolId: string) => void /** Records a workspace item the tool call created/edited/deleted, by its * canonical (itemKind, storagePath). Session chats wire this to accumulate the * chat's modified-items mask; the global side-panel chat omits it (no-op). */ @@ -1710,6 +1747,9 @@ function parseResourceTypeSchema(schema: unknown): unknown { } } +export const HUB_SYNC_INSTRUCTIONS = + 'Tell the user: no resource of a missing type can be created until a superadmin syncs resource types from the hub, with "Sync resource types with Hub" in the Add resource dialog of the Resources page.' + export const getHubIntegrationTool = { requires: NONE, def: getHubIntegrationToolDef, diff --git a/frontend/src/lib/components/copilot/chat/skills/skillResources.ts b/frontend/src/lib/components/copilot/chat/skills/skillResources.ts index 7a80705d4e..d28a4d32e8 100644 --- a/frontend/src/lib/components/copilot/chat/skills/skillResources.ts +++ b/frontend/src/lib/components/copilot/chat/skills/skillResources.ts @@ -1,6 +1,7 @@ import { ResourceService } from '$lib/gen' -import { canWrite } from '$lib/utils' -import type { UserExt } from '$lib/stores' +import { canEditItem } from '$lib/editRights' +import { userWorkspaces, type UserExt } from '$lib/stores' +import { get } from 'svelte/store' /** * Skills are resources of this type: a file resource (`format_extension = 'md'`) @@ -53,9 +54,10 @@ export type SkillListing = { skills: SkillResource[]; truncated: boolean } * `user` decides which rows the drawer offers to edit rather than only view; pass * the account the workspace is being browsed as. Ownership is mostly implicit in * the path (`u/<me>/…`, a folder the user owns), which is why this goes through - * the shared `canWrite` rather than reading `extra_perms` alone. */ + * the shared `canEditItem` rather than reading `extra_perms` alone. */ export async function listSkillResources(workspace: string, user?: UserExt): Promise<SkillListing> { if (!workspace) return { skills: [], truncated: false } + const operatorSettings = get(userWorkspaces).find((w) => w.id === workspace)?.operator_settings const rows: SkillResource[] = [] for (let page = 1; page <= MAX_SKILLS_PAGES; page++) { const resources = await ResourceService.listResource({ @@ -70,7 +72,7 @@ export async function listSkillResources(workspace: string, user?: UserExt): Pro name: skillNameFromPath(r.path), description: r.description ?? '', editedAt: r.edited_at, - canWrite: canWrite(r.path, r.extra_perms ?? {}, user) + canWrite: canEditItem('resource', r.path, r.extra_perms, user, operatorSettings) })) ) if (resources.length < SKILLS_PAGE_SIZE) return { skills: rows, truncated: false } diff --git a/frontend/src/lib/components/copilot/chat/skills/skillsMenu.svelte.ts b/frontend/src/lib/components/copilot/chat/skills/skillsMenu.svelte.ts index dd480c5e97..75d996ebef 100644 --- a/frontend/src/lib/components/copilot/chat/skills/skillsMenu.svelte.ts +++ b/frontend/src/lib/components/copilot/chat/skills/skillsMenu.svelte.ts @@ -1,4 +1,4 @@ -import { BookOpen, List, Plus } from 'lucide-svelte' +import { BookOpen, List, Loader2, Plus } from 'lucide-svelte' import { get } from 'svelte/store' import { userStore, workspaceStore } from '$lib/stores' import { sendUserToast } from '$lib/toast' @@ -14,6 +14,14 @@ type Row = SkillResource & { enabled: boolean } // scannable, so the rest are reached through the settings modal rather than dropped. const MAX_MENU_SKILLS = 8 +// Not `disabled`: melt stamps that on a row at mount and never clears it, and the +// unkeyed submenu reuses this row for the first skill once the load lands. +const loadingItem: Item = { + displayName: 'Loading…', + icon: Loader2, + iconProps: { class: 'animate-spin shrink-0' } +} + /** * The chat "+" menu's Skills submenu: one row per skill, checked when it is on, * then the way to manage them. Everything a skill is beyond turning it on and off @@ -25,7 +33,7 @@ export class SkillsMenu { #seq = 0 /** Rows for the workspace named by `#rowsWorkspace`, and meaningless for any other. */ #rows = $state<Row[]>([]) - #rowsWorkspace: string | undefined = undefined + #rowsWorkspace = $state<string | undefined>(undefined) constructor(manager: AIChatManager, onManage: () => void) { this.#manager = manager @@ -89,19 +97,21 @@ export class SkillsMenu { await this.#manager.refreshGlobalSkills(ws) } - /** Loaded on open so the checks are current. */ - async items(closeMenu?: () => void): Promise<Item[]> { + /** Called on open so the checks are current; never awaited, see `items`. */ + refresh() { + const ws = this.#ws + if (ws) void this.#load(ws) + } + + /** + * Built from the live rows, so call it from a getter: the submenu then fills in + * when a load lands instead of the whole "+" menu waiting on the fetch. Rows for + * another workspace are not shown — same path, different skill. + */ + items(closeMenu?: () => void): Item[] { const ws = this.#ws if (!ws) return [] - // The menu opens on what is already known and refreshes behind it: awaited - // inline it would stall the whole "+" menu, attachments included. Rows for - // another workspace are not "already known" — same path, different skill. - if (this.#rowsWorkspace !== ws) { - this.#rows = [] - await this.#load(ws) - } else { - void this.#load(ws) - } + if (this.#rowsWorkspace !== ws) return [loadingItem] const ambiguous = ambiguousSkillNames(this.#rows) // By path. Ordering the ones that are on first would put every row in the same // bucket now that skills start that way, and drop the one row it did move — a diff --git a/frontend/src/lib/components/copilot/chat/workspaceToolsZod.gen.ts b/frontend/src/lib/components/copilot/chat/workspaceToolsZod.gen.ts index 0b393e6969..c6b03cee68 100644 --- a/frontend/src/lib/components/copilot/chat/workspaceToolsZod.gen.ts +++ b/frontend/src/lib/components/copilot/chat/workspaceToolsZod.gen.ts @@ -501,7 +501,8 @@ export const resourceRequestSchema = z.object({ "description": z.string().describe("The description of the resource").optional(), "resource_type": z.string().describe("The resource_type associated with the resource"), "labels": z.array(z.string()).optional(), - "ws_specific": z.boolean().optional() + "ws_specific": z.boolean().optional(), + "preserve_on_behalf_of": z.boolean().describe("ai_agent only. Keep the identity `value.on_behalf_of` names (`u/<username>`, `g/<group>`) rather than the caller's own. Honoured for admins and members of wm_deployers; otherwise every write of an agent sets it to the caller.").optional() }) export const triggerRequestSchemas = { diff --git a/frontend/src/lib/components/copilot/lib.ts b/frontend/src/lib/components/copilot/lib.ts index 1d111a2f20..299765605e 100644 --- a/frontend/src/lib/components/copilot/lib.ts +++ b/frontend/src/lib/components/copilot/lib.ts @@ -26,12 +26,14 @@ import { explicitOffToken, requestsReasoning, stripLegacyThinkingSuffix, + usesOpenAIResponsesApi, type ReasoningEffort } from './reasoningRegistry' import { formatResourceTypes } from './utils' import { appendPendingToolImages, processToolCall, + type LiveToolSet, queuedToolStatus, type Tool, type ToolCallbacks @@ -1241,8 +1243,7 @@ export async function getCompletion( reasoningEffort: options?.reasoningEffort }) - // Use Responses API for OpenAI and Azure OpenAI - if ((provider === 'openai' || provider === 'azure_openai') && !options?.forceCompletions) { + if (usesOpenAIResponsesApi(provider, modelProvider.model) && !options?.forceCompletions) { try { const stream = getOpenAIResponsesCompletionStream(messages, abortController, tools, { forceModelProvider: options?.forceModelProvider, @@ -1326,8 +1327,8 @@ 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 } = getCurrentModel() - if (abortController.signal.aborted || (provider !== 'openai' && provider !== 'azure_openai')) { + const { provider, model } = getCurrentModel() + if (abortController.signal.aborted || !usesOpenAIResponsesApi(provider, model)) { throw error } console.error('Error using Responses API:', error) @@ -1372,6 +1373,7 @@ export async function parseOpenAICompletion( workspace?: string provider?: string onTokenUsage?: (usage: ChatTokenUsage) => void + live?: LiveToolSet } ): Promise<{ shouldContinue: boolean; tokenUsage: ChatTokenUsage }> { const finalToolCalls: Record<number, ChatCompletionChunk.Choice.Delta.ToolCall> = {} @@ -1583,7 +1585,8 @@ export async function parseOpenAICompletion( helpers, toolCallbacks: callbacks, workspace: options?.workspace, - messages + messages, + live: options?.live }) messages.push(messageToAdd) addedMessages.push(messageToAdd) diff --git a/frontend/src/lib/components/copilot/reasoningRegistry.test.ts b/frontend/src/lib/components/copilot/reasoningRegistry.test.ts index 30543e6c2f..176ab424d1 100644 --- a/frontend/src/lib/components/copilot/reasoningRegistry.test.ts +++ b/frontend/src/lib/components/copilot/reasoningRegistry.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest' import { applyReasoningToConfig, completionsRejectsToolsWithReasoning, + usesOpenAIResponsesApi, explicitOffToken, getReasoningCapability, REASONING_OFF, @@ -301,6 +302,12 @@ describe('supportsReasoning (static registry)', () => { expect(completionsRejectsToolsWithReasoning('azure_openai', model), model).toBe(false) } }) + it('sends Foundry gpt models that refuse tools on Chat Completions to the Responses API', () => { + expect(usesOpenAIResponsesApi('azure_foundry', 'gpt-6.1-sol')).toBe(true) + for (const model of ['gpt-4o', 'DeepSeek-V4-Pro', 'claude-sonnet-5']) { + expect(usesOpenAIResponsesApi('azure_foundry', model), model).toBe(false) + } + }) it('forwards an explicit off as effort none through OpenRouter', () => { expect( resolveRequestReasoning({ diff --git a/frontend/src/lib/components/copilot/reasoningRegistry.ts b/frontend/src/lib/components/copilot/reasoningRegistry.ts index 0cbf935832..1cce6e3b0d 100644 --- a/frontend/src/lib/components/copilot/reasoningRegistry.ts +++ b/frontend/src/lib/components/copilot/reasoningRegistry.ts @@ -263,6 +263,19 @@ export function completionsRejectsToolsWithReasoning(provider: AIProvider, model return findReasoningRule(provider, model).rule?.completionsToolsNeedOff ?? false } +/** + * Whether the chat sends this model to the Responses API, falling back to Chat Completions + * where a deployment does not serve it. On Foundry, only the models Chat Completions refuses + * function tools from while they reason: gpt-6.1-sol and gpt-6-astra cannot turn it off. + */ +export function usesOpenAIResponsesApi(provider: AIProvider, model: string): boolean { + return ( + provider === 'openai' || + provider === 'azure_openai' || + (provider === 'azure_foundry' && completionsRejectsToolsWithReasoning(provider, model)) + ) +} + export type ReasoningCapability = { supported: boolean /** Suggested levels for the UI control. Empty when unsupported. */ diff --git a/frontend/src/lib/components/datatableMigrationSchemas.test.ts b/frontend/src/lib/components/datatableMigrationSchemas.test.ts new file mode 100644 index 0000000000..306206358b --- /dev/null +++ b/frontend/src/lib/components/datatableMigrationSchemas.test.ts @@ -0,0 +1,90 @@ +import { describe, test, expect } from 'vitest' +import { + parseMigrationSchemas, + suggestMigrationSchemas, + withMigrationSchemas +} from './datatableMigrationSchemas' +import { withMigrationRole, parseMigrationRole } from './datatableMigrationRole' + +describe('parseMigrationSchemas', () => { + test('reads the spellings the server accepts, lowercased and deduplicated', () => { + expect(parseMigrationSchemas('-- role a\n-- Schemas: Sales, billing,sales;\nBEGIN;')).toEqual({ + kind: 'schemas', + schemas: ['sales', 'billing'] + }) + expect(parseMigrationSchemas('BEGIN;\n-- schemas sales')).toEqual({ kind: 'none' }) + expect(parseMigrationSchemas('-- schemas: changes to orders\nBEGIN;')).toEqual({ + kind: 'malformed', + line: '-- schemas: changes to orders' + }) + }) + + test('rewriting the scope keeps the role annotation readable', () => { + const sql = withMigrationSchemas(withMigrationRole('BEGIN;\nEND;', 'analyst'), ['sales']) + expect(sql).toBe('-- schemas sales\n-- role analyst\nBEGIN;\nEND;') + expect(parseMigrationRole(sql)).toEqual({ kind: 'role', role: 'analyst' }) + expect(withMigrationSchemas(sql, [])).toBe('-- role analyst\nBEGIN;\nEND;') + }) +}) + +describe('suggestMigrationSchemas', () => { + test('reads the scope of generated table DDL', () => { + const sql = `BEGIN; +CREATE SCHEMA IF NOT EXISTS billing; +CREATE TABLE IF NOT EXISTS "Sales"."orders" ( + "id" uuid DEFAULT gen_random_uuid() NOT NULL, + "amount" numeric(10, 2) CHECK (amount > 0), + "customer" int REFERENCES crm.customers(id) ON DELETE CASCADE, + PRIMARY KEY ("id") +); +CREATE UNIQUE INDEX orders_idx ON sales.orders USING btree (id); +ALTER TABLE sales.orders ALTER COLUMN amount TYPE numeric(12, 2); +COMMENT ON TABLE sales.orders IS 'one row per order'; +END;` + expect(suggestMigrationSchemas(sql)).toEqual(['billing', 'sales', 'crm']) + // As the database manager's query builders write it. + expect( + suggestMigrationSchemas( + 'BEGIN;\n\nALTER TABLE "myschema"."users" ADD COLUMN "age" INT;\nDROP TABLE "myschema"."old";\n\nEND;' + ) + ).toEqual(['myschema']) + expect(suggestMigrationSchemas('ALTER SCHEMA "sales" RENAME TO "billing";')).toEqual([ + 'sales', + 'billing' + ]) + }) + + test('falls back to the whole database for anything it cannot read in full', () => { + for (const sql of [ + // Unqualified objects resolve through the search path. + 'CREATE TABLE plain (id int);', + 'ALTER TABLE ONLY plain ADD COLUMN x int;', + 'CREATE INDEX ON plain (id);', + 'CREATE TABLE sales.t (id int REFERENCES plain(id));', + 'CREATE TABLE sales.t (status order_status);', + 'ALTER TABLE sales.t ADD COLUMN x int DEFAULT my_default();', + 'DROP INDEX plain_idx;', + // Qualified, but where the scope is not read. + 'CREATE TABLE sales.t (status billing.order_status);', + // Statements outside the reader. + 'CREATE TABLE sales.copy AS SELECT * FROM customers;', + 'TRUNCATE plain;', + 'GRANT USAGE ON SCHEMA sales, billing TO analyst;', + 'CREATE EXTENSION postgis WITH SCHEMA public;', + 'CREATE POLICY p ON sales.t FOR SELECT USING (true);', + 'CREATE VIEW sales.v AS SELECT o.id FROM sales.orders o;', + // A cascade drops dependents wherever they are. + 'DROP SCHEMA billing CASCADE;', + // Several targets, or a relation reached through another one. + 'DROP SCHEMA sales, billing;', + 'DROP TABLE sales.t, customers;', + 'ALTER TABLE sales.t ATTACH PARTITION plain FOR VALUES IN (1);', + 'ALTER TABLE sales.t INHERIT plain;', + 'CREATE TABLE sales.t OF plain_type;', + // `t.c` names a table and a column, not a schema. + 'COMMENT ON COLUMN t.c IS null;' + ]) { + expect(suggestMigrationSchemas(`CREATE TABLE sales.a (id int);\n${sql}`), sql).toEqual([]) + } + }) +}) diff --git a/frontend/src/lib/components/datatableMigrationSchemas.ts b/frontend/src/lib/components/datatableMigrationSchemas.ts new file mode 100644 index 0000000000..b2e8f4c255 --- /dev/null +++ b/frontend/src/lib/components/datatableMigrationSchemas.ts @@ -0,0 +1,311 @@ +/** + * A migration declares the schemas it touches in its own SQL, as a `-- schemas sales, billing` + * annotation, the same way it declares its role (see `datatableMigrationRole.ts`). A migration that + * declares none applies to the whole database: every later migration waits for it, so the editors + * suggest a scope from the SQL rather than leaving it out. + * + * Mirrors `parse_migration_schemas` in `datatable_migration_scope.rs`: read from the leading comment + * block only, names lowercased, and a leading comment whose first word is `schemas` is an + * annotation attempt, so a malformed one is an error. + */ + +export type MigrationSchemas = + | { kind: 'none' } + | { kind: 'schemas'; schemas: string[] } + | { kind: 'malformed'; line: string } + +const KEYWORD = 'schemas' + +export function isAnnotatableSchemaName(name: string): boolean { + return /^[A-Za-z0-9_$-]{1,63}$/.test(name) +} + +/** The rest of a leading comment line that attempts a scope annotation, or undefined. */ +function schemasAttempt(line: string): string | undefined { + if (!line.startsWith('--')) return undefined + const body = line.slice(2).trimStart() + if (body.slice(0, KEYWORD.length).toLowerCase() !== KEYWORD) return undefined + const after = body.slice(KEYWORD.length) + if (after !== '' && !/^[\s:=]/.test(after)) return undefined + return after +} + +function parseAttempt(after: string): string[] | undefined { + let rest = after.trimStart() + if (rest.startsWith(':') || rest.startsWith('=')) rest = rest.slice(1) + rest = rest.trim() + if (rest.endsWith(';')) rest = rest.slice(0, -1) + const schemas: string[] = [] + for (const piece of rest.split(',')) { + const name = piece.trim() + if (!isAnnotatableSchemaName(name)) return undefined + const lower = name.toLowerCase() + if (!schemas.includes(lower)) schemas.push(lower) + } + return schemas +} + +export function parseMigrationSchemas(sql: string): MigrationSchemas { + for (const raw of sql.split('\n')) { + const line = raw.trim() + if (line === '') continue + if (!line.startsWith('--')) break + const after = schemasAttempt(line) + if (after === undefined) continue + const schemas = parseAttempt(after) + return schemas === undefined ? { kind: 'malformed', line } : { kind: 'schemas', schemas } + } + return { kind: 'none' } +} + +/** + * `sql` declaring `schemas`: any scope annotation attempt in the leading comment block is removed, + * and `-- schemas <names>` is prepended above everything, or nothing when `schemas` is empty. + */ +export function withMigrationSchemas(sql: string, schemas: string[]): string { + for (const s of schemas) { + if (!isAnnotatableSchemaName(s)) throw new Error(`Invalid schema name '${s}'`) + } + const lines = sql.split('\n') + const kept: string[] = [] + let i = 0 + for (; i < lines.length; i++) { + const line = lines[i].trim() + if (line !== '' && !line.startsWith('--')) break + if (schemasAttempt(line) === undefined) kept.push(lines[i]) + } + const rest = [...kept, ...lines.slice(i)] + while (rest.length > 0 && rest[0].trim() === '') rest.shift() + return schemas.length === 0 + ? rest.join('\n') + : [`-- ${KEYWORD} ${schemas.join(', ')}`, ...rest].join('\n') +} + +/** Whether two scopes overlap; `undefined` is the whole database, which overlaps everything. */ +export function scopesOverlap(a: string[] | undefined, b: string[] | undefined): boolean { + if (a === undefined || b === undefined) return true + return a.some((s) => b.includes(s)) +} + +/** The scope a migration's SQL declares, `undefined` for the whole database. */ +export function migrationScope(sql: string): string[] | undefined { + const parsed = parseMigrationSchemas(sql) + return parsed.kind === 'schemas' ? parsed.schemas : undefined +} + +const IDENT = String.raw`(?:"(?:[^"]|"")+"|[A-Za-z_][A-Za-z0-9_$]*)` +const SYSTEM_SCHEMAS = ['pg_catalog', 'information_schema', 'pg_toast', 'pg_temp'] + +function unquote(ident: string): string { + return ident.startsWith('"') ? ident.slice(1, -1).replaceAll('""', '"') : ident +} + +// The statements a scope is suggested for: table, index, schema, sequence and type DDL. Anything +// else (a view, a function, a grant, data, an extension) is outside the reader, and suggests +// nothing. +const STATEMENT_SHAPE = + /^(?:CREATE\s+(?:UNIQUE\s+)?INDEX|DROP\s+INDEX|(?:CREATE|ALTER|DROP)\s+(?:TABLE|SCHEMA|SEQUENCE|TYPE)|COMMENT\s+ON\s+(?:TABLE|SCHEMA))\b/i +const TRANSACTION_CONTROL = /^(?:BEGIN|COMMIT|END|START\s+TRANSACTION)$/i +// Clauses that reach another object without naming it where the reader looks: a query, a copied +// or inherited definition, a sequence named in a string, and a cascade, which drops whatever +// depends on the target wherever it lives. `ON DELETE CASCADE` is a foreign key's action. +const OPAQUE_CLAUSE = + /\b(?:SELECT|FROM|LIKE|INHERITS?|OF|ATTACH|DETACH|EXECUTE|nextval)\b|::\s*regclass|(?<!\bON\s+(?:DELETE|UPDATE)\s+)\bCASCADE\b/i +// Words a definition puts before `(` that call nothing a search path resolves: clause keywords, +// built-in types with a modifier, index methods, and `pg_catalog` functions. +const PAREN_WORDS = new Set( + ( + 'key unique check references foreign primary exclude constraint as with where include in any ' + + 'and or not cast ' + + 'all array identity generated enum default values filter over partition by ' + + 'varchar char character varying numeric decimal timestamp timestamptz time timetz interval ' + + 'bit varbit float double btree hash gist gin brin spgist ' + + 'now gen_random_uuid uuidv4 uuidv7 clock_timestamp statement_timestamp transaction_timestamp ' + + 'lower upper length char_length coalesce nullif greatest least abs round trunc md5 random ' + + 'date_trunc to_char to_jsonb jsonb_build_object json_build_object array_length cardinality' + ).split(' ') +) +// Built-in types: an unqualified type outside this list may be a user type resolved through the +// search path. +const BUILTIN_TYPES = new Set( + ( + 'int int2 int4 int8 integer smallint bigint serial serial2 serial4 serial8 smallserial ' + + 'bigserial real float float4 float8 double numeric decimal money text varchar char character ' + + 'bpchar name bytea boolean bool date time timetz timestamp timestamptz interval uuid json ' + + 'jsonb xml inet cidr macaddr macaddr8 bit varbit tsvector tsquery point line lseg box path ' + + 'polygon circle int4range int8range numrange tsrange tstzrange daterange int4multirange ' + + 'int8multirange nummultirange tsmultirange tstzmultirange datemultirange oid' + ).split(' ') +) +const BUILTIN_COLLATIONS = new Set(['c', 'posix', 'default', 'ucs_basic', 'unicode']) +// Keywords that follow `ON`, `REFERENCES` or an object keyword where a name could: `ON DELETE`, +// `COMMENT ON TABLE`, `ON COMMIT`, and the optional `IF [NOT] EXISTS` / `ONLY` a match can land +// on when the name after them is qualified. +const NOT_A_NAME = new Set([ + 'if', + 'not', + 'exists', + 'only', + 'concurrently', + 'delete', + 'update', + 'commit', + 'table', + 'column', + 'schema', + 'index', + 'type', + 'sequence', + 'constraint' +]) +// Words a column list puts first that open a table constraint rather than a column. +const CONSTRAINT_WORDS = new Set([ + 'constraint', + 'primary', + 'foreign', + 'unique', + 'check', + 'exclude', + 'like' +]) + +/** + * A scope to suggest for `sql`, read conservatively: every statement must be one of the DDL shapes + * above and name every object it reaches with its schema; otherwise this returns `[]`. It is only + * ever offered for the author to accept, never written for them: PostgreSQL reaches objects the + * SQL does not name (a partition, an inheriting table), so only the author can vouch for a scope. + */ +export function suggestMigrationSchemas(sql: string): string[] { + const code = stripLiteralsAndComments(sql) + if (OPAQUE_CLAUSE.test(code)) return [] + const statements = code + .split(';') + .map((s) => s.trim()) + .filter((s) => s !== '' && !TRANSACTION_CONTROL.test(s)) + if (statements.length === 0) return [] + for (const s of statements) { + // `DROP TABLE a, b` and `DROP SCHEMA a, b` name several targets; the reader checks one. + if (/^DROP\b/i.test(s) && splitTopLevel(s).length > 1) return [] + if (!STATEMENT_SHAPE.test(s) || !namesAreQualified(s)) return [] + } + const found = qualifiedSchemas(code) + // Every qualifier has to be a schema the scope declares: one that is not (an alias, a schema the + // reader has no position for) cannot be told apart from a dependency. + for (const m of code.matchAll(new RegExp(String.raw`(${IDENT})\s*\.\s*${IDENT}`, 'g'))) { + const qualifier = unquote(m[1]).toLowerCase() + if (!found.includes(qualifier) && !isSystemSchema(qualifier)) return [] + } + return found +} + +/** Whether a statement of an accepted shape reaches nothing through the search path. */ +function namesAreQualified(s: string): boolean { + const lower = (ident: string) => unquote(ident).toLowerCase() + const unqualifiedAfter = (prefix: string) => + new RegExp(String.raw`${prefix}\s+(${IDENT})(?![A-Za-z0-9_$"]|\s*\.)`, 'gi') + // The object a statement creates, changes or drops, and the table an index or foreign key + // targets. `IF [NOT] EXISTS` and `ONLY` come before the name, not instead of it. + const relation = String.raw`(?:\s+IF\s+(?:NOT\s+)?EXISTS)?(?:\s+ONLY)?` + for (const re of [ + unqualifiedAfter( + String.raw`\b(?:CREATE|ALTER|DROP)\s+(?:UNLOGGED\s+)?(?:TABLE|SEQUENCE|TYPE)${relation}` + ), + unqualifiedAfter(String.raw`\bDROP\s+INDEX(?:\s+CONCURRENTLY)?${relation}`), + unqualifiedAfter(String.raw`\bON${relation}`), + unqualifiedAfter(String.raw`\bREFERENCES`), + unqualifiedAfter(String.raw`\bCOMMENT\s+ON\s+TABLE`) + ]) { + for (const m of s.matchAll(re)) { + if (!NOT_A_NAME.has(lower(m[1]))) return false + } + } + for (const m of s.matchAll(new RegExp(String.raw`::\s*(${IDENT})(?!\s*\.)`, 'g'))) { + if (!BUILTIN_TYPES.has(lower(m[1]))) return false + } + // Calls: a word right before `(` that is not part of a qualified name. + for (const m of s.matchAll(new RegExp(String.raw`(?<![.\w$"])(${IDENT})\s*\(`, 'g'))) { + if (!PAREN_WORDS.has(lower(m[1]))) return false + } + for (const m of s.matchAll(new RegExp(String.raw`\bCOLLATE\s+(${IDENT})(?!\s*\.)`, 'gi'))) { + if (!BUILTIN_COLLATIONS.has(lower(m[1]))) return false + } + // Column types: in a table's column list, after `ADD [COLUMN]`, and after `TYPE`. + const types: string[] = [] + const body = /^CREATE\s+(?:UNLOGGED\s+)?TABLE\b[^(]*\(([\s\S]*)\)/i.exec(s)?.[1] + if (body !== undefined) { + for (const element of splitTopLevel(body)) { + const m = new RegExp(String.raw`^(${IDENT})\s+(${IDENT})(?!\s*\.)`).exec(element.trim()) + if (m && !CONSTRAINT_WORDS.has(lower(m[1]))) types.push(m[2]) + } + } + for (const m of s.matchAll( + new RegExp( + String.raw`\bADD\s+(?:COLUMN\s+)?(?:IF\s+NOT\s+EXISTS\s+)?(${IDENT})\s+(${IDENT})(?!\s*\.)`, + 'gi' + ) + )) { + if (!CONSTRAINT_WORDS.has(lower(m[1]))) types.push(m[2]) + } + for (const m of s.matchAll(new RegExp(String.raw`\bTYPE\s+(${IDENT})(?!\s*\.)`, 'gi'))) { + types.push(m[1]) + } + return types.every((t) => BUILTIN_TYPES.has(lower(t))) +} + +/** `body` split on the commas outside parentheses. */ +function splitTopLevel(body: string): string[] { + const parts: string[] = [] + let depth = 0 + let start = 0 + for (let i = 0; i < body.length; i++) { + if (body[i] === '(') depth++ + else if (body[i] === ')') depth-- + else if (body[i] === ',' && depth === 0) { + parts.push(body.slice(start, i)) + start = i + 1 + } + } + parts.push(body.slice(start)) + return parts +} + +function isSystemSchema(name: string): boolean { + return SYSTEM_SCHEMAS.includes(name) || name.startsWith('pg_temp') +} + +function stripLiteralsAndComments(sql: string): string { + return sql + .replace(/\$([A-Za-z_]*)\$[\s\S]*?\$\1\$/g, ' ') + .replace(/'(?:[^']|'')*'/g, ' ') + .replace(/\/\*[\s\S]*?\*\//g, ' ') + .replace(/--[^\n]*/g, ' ') +} + +function qualifiedSchemas(code: string): string[] { + const found: string[] = [] + const add = (ident: string) => { + const name = unquote(ident).toLowerCase() + if (isAnnotatableSchemaName(name) && !isSystemSchema(name) && !found.includes(name)) { + found.push(name) + } + } + const patterns = [ + new RegExp(String.raw`\bSCHEMA\s+(?:IF\s+(?:NOT\s+)?EXISTS\s+)?(${IDENT})`, 'gi'), + // The schema a rename creates, and the one `SET SCHEMA` moves an object into. + new RegExp(String.raw`\bALTER\s+SCHEMA\s+${IDENT}\s+RENAME\s+TO\s+(${IDENT})`, 'gi'), + new RegExp( + String.raw`\b(?:TABLE|VIEW|SEQUENCE|TYPE|FUNCTION|PROCEDURE|DOMAIN|INDEX|TRIGGER|COLUMN|REFERENCES|INTO|UPDATE|FROM|JOIN|EXISTS|ONLY)\s+(${IDENT})\s*\.\s*${IDENT}`, + 'gi' + ), + // `ON` also opens a join condition (`ON a.id = b.id`), so only the forms that name a relation + // count: an index, trigger, policy, grant or comment target. + new RegExp( + String.raw`\bON\s+(?:ONLY\s+)?(${IDENT})\s*\.\s*${IDENT}(?=\s*(?:\(|USING\b|FOR\b|TO\b|AS\b|IS\b|;|$))`, + 'gim' + ) + ] + for (const re of patterns) { + for (const m of code.matchAll(re)) add(m[1]) + } + return found +} diff --git a/frontend/src/lib/components/dbOps.ts b/frontend/src/lib/components/dbOps.ts index 1ffab78ac4..a926788180 100644 --- a/frontend/src/lib/components/dbOps.ts +++ b/frontend/src/lib/components/dbOps.ts @@ -411,20 +411,20 @@ export function dbSchemaOpsWithPreviewScripts({ ) return } - // The new migration gets the highest timestamp, so any still-pending - // migration is earlier: running only this one applies it out of order. - // Warn like the row-level Run action does (skipped if no confirm hook). - if (confirmRunOutOfOrder) { - const pending = pendingMigrations(status.migrations).length - if (pending > 0 && !(await confirmRunOutOfOrder(pending))) { - throw new MigrationRunCancelled() - } - } // Wrapped before annotating: the annotation must lead, above `BEGIN;`. const codeUp = withMigrationRole( wrapMigration(await expandMarker(workspace, language, content)), migrationRole ) + // The new migration gets the highest timestamp, so any still-pending + // migration is earlier: running only this one applies it out of order. + // Warn like the row-level Run action does (skipped if no confirm hook). + if (confirmRunOutOfOrder) { + const pending = pendingMigrations(status.migrations, codeUp).length + if (pending > 0 && !(await confirmRunOutOfOrder(pending))) { + throw new MigrationRunCancelled() + } + } // Down migrations are only generated for Postgres for now. let codeDown: string | undefined if (downContent && dbType === 'postgresql') { diff --git a/frontend/src/lib/components/dbTableFilters.ts b/frontend/src/lib/components/dbTableFilters.ts index 9d9c83e6b0..c3266b3ac7 100644 --- a/frontend/src/lib/components/dbTableFilters.ts +++ b/frontend/src/lib/components/dbTableFilters.ts @@ -52,7 +52,7 @@ export function buildDbTableFilterSchema(columns: ColumnDef[]): DbTableFilterSch const columnOfKey: Record<string, string> = {} const keyOfColumn: Record<string, string> = {} for (const col of columns) { - if (!col.field) continue + if (!col.field || col.filterable === false) continue let base = col.field.replace(/\W+/g, '_') || 'column' if (base === FREE_TEXT_KEY) base = `${base}col` let key = base diff --git a/frontend/src/lib/components/dbTypes.ts b/frontend/src/lib/components/dbTypes.ts index e6d3af12e8..2bb2a92e14 100644 --- a/frontend/src/lib/components/dbTypes.ts +++ b/frontend/src/lib/components/dbTypes.ts @@ -32,6 +32,9 @@ export const isDbType = (str?: string): str is DbType => !!str && dbTypes.includ /** The role every data table has: the one it connects as when it is not under roles. */ export const ADMIN_DATATABLE_ROLE = 'admin' +/** What `default_role` holds for a data table with no default role. Mirrors the backend's + * `NO_DEFAULT_DATATABLE_ROLE`. */ +export const NO_DEFAULT_DATATABLE_ROLE = '$none' /** What the server accepts in `-- role <name>` and `?role=<name>`. */ export function isDatatableRoleName(name: string): boolean { @@ -52,7 +55,13 @@ export function defaultMigrationRole( permissioned: boolean | undefined, defaultRole: string | undefined ): string | undefined { - return permissioned && !datatableNameTakesRole(name) ? defaultRole : undefined + return permissioned && !datatableNameTakesRole(name) ? namedDefaultRole(defaultRole) : undefined +} + +/** A data table's default role, or `undefined` when it has none: the server reports that as + * `NO_DEFAULT_DATATABLE_ROLE`, which is not a role anything can connect as. */ +export function namedDefaultRole(defaultRole: string | undefined): string | undefined { + return defaultRole === NO_DEFAULT_DATATABLE_ROLE ? undefined : defaultRole } /** `datatable://<name>`, with `?role=<role>` when a role is named. Throws rather than build a diff --git a/frontend/src/lib/components/dbt/DbtModelGraph.svelte b/frontend/src/lib/components/dbt/DbtModelGraph.svelte index bd7f42a9e7..12b008812d 100644 --- a/frontend/src/lib/components/dbt/DbtModelGraph.svelte +++ b/frontend/src/lib/components/dbt/DbtModelGraph.svelte @@ -16,7 +16,6 @@ import { Button } from '$lib/components/common' import { Loader2, RefreshCw } from 'lucide-svelte' import { displayDate } from '$lib/utils' - import { base } from '$lib/base' import AssetGraphCanvas from '$lib/components/assets/AssetGraph/AssetGraphCanvas.svelte' import type { DbtPreviewBuffer } from './previewRows' import type { @@ -477,7 +476,7 @@ worker tag nothing serves waits here indefinitely. <a class="text-blue-500 hover:underline" - href="{base}/run/{refreshPending}?workspace={workspace}" + href="/run/{refreshPending}?workspace={workspace}" target="_blank" rel="noreferrer">Open the parse job</a > @@ -491,7 +490,7 @@ {#if refreshError.job} <a class="text-blue-500 hover:underline" - href="{base}/run/{refreshError.job}?workspace={workspace}" + href="/run/{refreshError.job}?workspace={workspace}" target="_blank" rel="noreferrer">Open the parse job</a > diff --git a/frontend/src/lib/components/details/DetailPageHeader.svelte b/frontend/src/lib/components/details/DetailPageHeader.svelte index 34a7fab355..30b0d5dab7 100644 --- a/frontend/src/lib/components/details/DetailPageHeader.svelte +++ b/frontend/src/lib/components/details/DetailPageHeader.svelte @@ -17,14 +17,16 @@ type MainButton = { label: string - /** Shown under the label once the button has collapsed into a menu. */ + /** Shown under the label once the button is a row of a menu. */ description?: string buttonProps: ButtonProps - /** Where the button lands below the `lg` breakpoint, where the bar cannot hold every - * button beside the summary: the ellipsis menu, or the dropdown of the enabled bar button - * labelled `dropdownOf` (the menu when there is none). Unset keeps it in the bar at every - * width. */ - narrow?: 'menu' | { dropdownOf: string } + /** A secondary action: a bar button while the bar has room for every one, then, from the + * first fold, in the ellipsis menu or in the dropdown of the enabled bar button labelled + * `dropdownOf` (the menu when there is none). Unset makes it a main button, which goes to + * the menu only on the folds after that. */ + placement?: 'menu' | { dropdownOf: string } + /** In its `placement` at every width, never a bar button of its own. */ + alwaysPlaced?: boolean } type ButtonProps = any @@ -70,6 +72,9 @@ wide?: boolean /** Controls ahead of the menu, such as the way an agent's page runs it. */ leading_actions?: import('svelte').Snippet + /** Marks that belong to the item's name, such as its favorite star: drawn right after the + * summary rather than among the badges and buttons at the far end. */ + name_marks?: import('svelte').Snippet } let { @@ -89,7 +94,8 @@ trigger_badges, ownsPageHeader = false, wide = true, - leading_actions + leading_actions, + name_marks }: Props = $props() const dispatch = createEventDispatcher() @@ -98,26 +104,50 @@ // no error handler and says so itself. const renameKind = $derived(itemKind ?? errorHandlerKind) - // Two reasons the row can be too tight, and either one collapses it. The host knows when its - // own box is narrow while the window is not — a session's preview panel — and says so through - // `wide`. The band knows its own width, which the host cannot see: these buttons share that row - // with the breadcrumb, and the trail and summary want ~580px against the set's ~530. Unmeasured - // (0) counts as wide, because the bar measures itself on mount and starting narrow would pop - // the buttons out of the menu a frame later. - // Measured on a flow's page: a 1192px bar leaves the last button 4px past the edge, so the row - // has to fold before that rather than at the ~1150 the two parts add up to on paper. - const COLLAPSE_BELOW = 1250 - const roomInBar = $derived(pageHeader.barWidth === 0 || pageHeader.barWidth >= COLLAPSE_BELOW) - const wideRow = $derived(wide && roomInBar) + // The band folds the buttons once its breadcrumb has given all it can (`actionFolds` below): + // first the secondary ones go to their `placement`, then every bar button but the last, which + // is what the page is for (Edit), then that one too. Outside the band — a session's preview + // panel — no bar measures the row, but the host knows when its own box is narrow while the + // window is not and says so through `wide`: the secondary buttons fold there, as at the first + // fold, and the error handler's toggle goes to the menu. + const fold = $derived(ownsPageHeader ? pageHeader.actionFold : wide ? 0 : 1) + const wideRow = $derived(wide && fold <= 1) - const barButtons = $derived(wideRow ? mainButtons : mainButtons.filter((b) => !b.narrow)) + const rowButtons = $derived(mainButtons.filter((b) => !b.placement)) + const barButtons = $derived( + fold === 0 + ? mainButtons.filter((b) => !b.alwaysPlaced) + : fold === 1 + ? rowButtons + : fold === 2 + ? rowButtons.slice(-1) + : [] + ) function dropdownHost(btn: MainButton): MainButton | undefined { - if (typeof btn.narrow !== 'object') return undefined - const label = btn.narrow.dropdownOf + if (typeof btn.placement !== 'object' || barButtons.includes(btn)) return undefined + const label = btn.placement.dropdownOf return barButtons.find((b) => b.label === label && !b.buttonProps.disabled) } + /** What the menu holds of the buttons: the folded bar buttons, each followed by what its + * dropdown would have held, then the secondary actions with no bar button to hang from. */ + const menuButtons = $derived.by(() => { + const folded = rowButtons.filter((b) => !barButtons.includes(b)) + const homeless = mainButtons.filter( + (b) => b.placement && !barButtons.includes(b) && !dropdownHost(b) + ) + const childOf = (host: MainButton) => + homeless.filter( + (b) => typeof b.placement === 'object' && b.placement.dropdownOf === host.label + ) + const placed = new Set(folded.flatMap(childOf)) + return [ + ...folded.flatMap((host) => [host, ...childOf(host)]), + ...homeless.filter((b) => !placed.has(b)) + ] + }) + async function toggleErrorHandler() { if (!errorHandlerKind || !scriptOrFlowPath) return const next = await toggleWorkspaceErrorHandler( @@ -130,7 +160,7 @@ } const allMenuItems: Item[] = $derived([ - ...(wideRow ? [] : mainButtons.filter((b) => b.narrow && !dropdownHost(b))).map((b) => ({ + ...menuButtons.map((b) => ({ displayName: b.label, description: b.description, icon: b.buttonProps.startIcon, @@ -155,12 +185,11 @@ action: item.onclick, disabled: item.disabled, type: item.color === 'red' ? ('delete' as const) : ('action' as const), - separatorTop: i === 0 && !wideRow + separatorTop: i === 0 && (menuButtons.length > 0 || (!wideRow && !!errorHandlerKind)) })) ]) function dropdownItemsOf(host: MainButton) { - if (wideRow) return undefined const items = mainButtons .filter((b) => dropdownHost(b) === host) .map((b) => ({ @@ -176,15 +205,18 @@ </script> {#snippet summaryContent()} - <SummaryPathDisplay - {summary} - {path} - bind:labels - {inheritedLabels} - {onSaved} - kind={renameKind} - compact - /> + <div class="flex items-center gap-1 min-w-0"> + <SummaryPathDisplay + {summary} + {path} + bind:labels + {inheritedLabels} + {onSaved} + kind={renameKind} + compact + /> + {#if name_marks}<span class="flex items-center shrink-0">{@render name_marks()}</span>{/if} + </div> {/snippet} <!-- The same editor as the summary's, hung off the band's path segment so it opens under the path. @@ -272,12 +304,17 @@ item={{ kind: errorHandlerKind, path, + // Read-only, the summary control falls back to the path when there is no summary, so the + // path is what names the item there and the trail's own copy can go. + summary: onSaved ? summary : summary || path, summaryContent, // Only where this page can save one: without `onSaved` the editor behind it has nothing // to write, and the band keeps its own segment, which copies the path. pathTrigger: onSaved ? pathTrigger : undefined }} {actions} + actionFolds={3} + earlyActionFolds={1} contexts={headerContexts} separator="always" /> @@ -301,6 +338,7 @@ kind={renameKind} /> </div> + {@render name_marks?.()} {@render badges('md')} </div> <div class="flex gap-1 items-center pr-4"> diff --git a/frontend/src/lib/components/details/FlowDetail.svelte b/frontend/src/lib/components/details/FlowDetail.svelte index ce7378ede4..a9648b183d 100644 --- a/frontend/src/lib/components/details/FlowDetail.svelte +++ b/frontend/src/lib/components/details/FlowDetail.svelte @@ -23,13 +23,16 @@ import DetailPageLayout from '$lib/components/details/DetailPageLayout.svelte' import OnBehalfOfBadge from '$lib/components/details/OnBehalfOfBadge.svelte' import { goto } from '$lib/navigation' - import { base } from '$lib/base' import { Badge as HeaderBadge, Alert } from '$lib/components/common' import MoveDrawer from '$lib/components/MoveDrawer.svelte' import RunForm from '$lib/components/RunForm.svelte' + import type { PendingRun } from '$lib/components/details/pendingRun' + import { processSecretArgs } from '$lib/components/secretArgUtils' + import type { Schema } from '$lib/common' import ShareModal from '$lib/components/ShareModal.svelte' import { enterpriseLicense, userStore, userWorkspaces, workspaceStore } from '$lib/stores' - import { useOperatorBuilderFlows } from '$lib/operatorWriteRights' + import { useEditRights } from '$lib/operatorWriteRights' + import { PLAN_MODE_MESSAGES } from '$lib/components/copilot/chat/planModeMessages' import { sendUserToast } from '$lib/toast' import DeployWorkspaceDrawer from '$lib/components/DeployWorkspaceDrawer.svelte' import SavedInputsV2 from '$lib/components/SavedInputsV2.svelte' @@ -101,6 +104,7 @@ onNavigate = goto, active = true, embedded = false, + pendingRun, onLoadState }: { /** The `[...path]` route segment: the flow's path. */ @@ -116,6 +120,8 @@ /** Rendered inside a page that is not the flow's own (an AI session preview tab), whose * URL this must leave alone and which a cross-workspace link must not navigate away. */ embedded?: boolean + /** A chat tool call confirmed here rather than on its card. See {@link PendingRun}. */ + pendingRun?: PendingRun /** How the load ended, for a host that renders its own state around this page. */ onLoadState?: (state: 'loaded' | 'not_found') => void } = $props() @@ -131,7 +137,7 @@ // A ⌘-click opens these in a new tab, which only the query names the workspace for. const operatingHref = useOperatingWorkspaceHref() const actingUser = $derived(operatingUser.current) - const operatorBuilderFlows = useOperatorBuilderFlows() + const editRights = useEditRights() let flow: Flow | undefined = $state() // Derived, not assigned during the load: in a fork the acting user is looked up @@ -290,6 +296,10 @@ invisibleToOwner: boolean | undefined, overrideTag: string | undefined ) { + // Taken before the round trip below: the call this press answers is the one it was + // pressed under, and a call settled meanwhile — declined, then another proposed for + // this same flow — must not be answered with a job it never asked for. + const call = pendingRun loading = true const scheduledFor = scheduledForStr ? new Date(scheduledForStr).toISOString() : undefined try { @@ -302,7 +312,11 @@ tag: overrideTag, skipPreprocessor: true }) - await onNavigate('/run/' + run + '?workspace=' + workspace) + // The call asked for this run; it follows the job rather than starting one, and + // shows it in place of this page — so navigating here as well would leave two + // surfaces open on the same job. + if (!call?.adopt(run, args, flow?.schema ?? {})) + await onNavigate('/run/' + run + '?workspace=' + workspace) } catch (e) { throw e } finally { @@ -315,11 +329,21 @@ conversationId: string, additionalInputs?: Record<string, any> ): Promise<string> { + // A chat flow's inputs reach the job straight from the composer, with no RunForm in + // between to mint a secret as it is typed — so this is the only place a value the + // schema marks `password` can become a reference. Without it the literal is stored in + // the job's arguments, where anyone who can read the run can read it. Idempotent, so a + // reference that was already minted costs a walk and no round trip. + const requestBody = await processSecretArgs( + { user_message: userMessage, ...(additionalInputs ?? {}) }, + flow?.schema as Schema | undefined, + workspace + ) const run = await JobService.runFlowByPath({ workspace: workspace!, path, memoryId: conversationId, - requestBody: { user_message: userMessage, ...(additionalInputs ?? {}) }, + requestBody, skipPreprocessor: true }) return run @@ -344,10 +368,12 @@ console.error('Was not able to transform hash as args', e) } } + // A chat call confirmed here opens its form on what the chat proposed. Read at init like + // the hash above, and for the same reason; the host remounts this page when the call + // changes, so a tab already open on this flow still builds its form from the new one. + if (pendingRun) args = { ...untrack(() => pendingRun.proposedArgs) } - // Operators with the builder right author flows out of deployed runnables; every other - // operator is read-only here. - let canAuthorFlow = $derived(!actingUser?.operator || $operatorBuilderFlows) + let canAuthorFlow = $derived(editRights.roleCanAuthor('flow')) let moveDrawer: MoveDrawer | undefined = $state() let deploymentDrawer: DeployWorkspaceDrawer | undefined = $state() @@ -372,9 +398,9 @@ buttons.push({ label: 'Fork', description: `Start a new flow from a copy of this one`, - narrow: { dropdownOf: 'Edit' }, + placement: { dropdownOf: 'Edit' }, buttonProps: { - href: operatingHref(`${base}/flows/add?template=${flow.path}`), + href: operatingHref(`/flows/add?template=${flow.path}`), onClick: interceptNav(onNavigate, `/flows/add?template=${flow.path}`), variant: 'subtle', unifiedSize: 'md', @@ -393,7 +419,7 @@ buttons.push({ label: editInForkLabel(workspace, $userWorkspaces), description: editInForkDescription('flow', workspace, $userWorkspaces), - narrow: { dropdownOf: 'Edit' }, + placement: { dropdownOf: 'Edit' }, buttonProps: { href: buildForkEditUrl('flow', flow.path, workspace), onClick: (e: Event | undefined) => editInFork(e, flow.path), @@ -411,7 +437,7 @@ buttons.push({ label: `Runs`, buttonProps: { - href: operatingHref(`${base}/runs/${flow.path}`), + href: operatingHref(`/runs/${flow.path}`), onClick: interceptNav(onNavigate, `/runs/${flow.path}`), unifiedSize: 'md', variant: 'subtle', @@ -421,7 +447,7 @@ buttons.push({ label: `History`, - narrow: 'menu', + placement: 'menu', buttonProps: { onClick: () => flowHistory?.open(), unifiedSize: 'md', @@ -434,11 +460,12 @@ return buttons } - // The builder right covers flows only; building an app is still refused to operators. + // Build app makes a low-code app, which no builder right covers. if (!actingUser?.operator) { buttons.push({ label: 'Build app', - narrow: 'menu', + placement: 'menu', + alwaysPlaced: true, buttonProps: { onClick: async () => { const app = createRawAppFromFlow(flow.path, flow.summary, flow.schema) @@ -457,7 +484,7 @@ buttons.push({ label: 'Edit', buttonProps: { - href: operatingHref(`${base}/flows/edit/${path}`), + href: operatingHref(`/flows/edit/${path}`), onClick: interceptNav(onNavigate, `/flows/edit/${path}`), variant: 'accent', unifiedSize: 'md', @@ -685,6 +712,12 @@ } : undefined} > + {#snippet name_marks()} + <!-- Favorites are the sidebar's, which lists the navigation workspace only. --> + {#if workspace && flow && workspace === $workspaceStore} + <Star kind="flow" path={flow.path} summary={flow.summary} /> + {/if} + {/snippet} {#snippet trigger_badges()} <TriggersBadge showOnlyWithCount={true} @@ -701,12 +734,6 @@ small={false} /> {/snippet} - {#if workspace && flow} - <!-- Favorites are the sidebar's, which lists the navigation workspace only. --> - {#if workspace === $workspaceStore} - <Star kind="flow" path={flow.path} summary={flow.summary} /> - {/if} - {/if} <OnBehalfOfBadge onBehalfOf={flow?.on_behalf_of} onBehalfOfEmail={flow?.on_behalf_of_email} @@ -828,19 +855,31 @@ flow.schema && Object.keys(flow.schema.properties ?? {}).length > 0} <!-- Normal Mode: Form Layout --> <div class="flex flex-col align-left"> - {#if hasSchema || inputSelected} + {#if hasSchema || inputSelected || pendingRun} <div class="flex flex-row justify-between min-h-12" transition:slide={{ duration: 150 }} > - <InputSelectedBadge - onReject={() => { - savedInputsV2?.resetSelected() - }} - {inputSelected} - /> + <div class="flex flex-row items-start gap-2"> + {#if pendingRun} + <InputSelectedBadge + inputSelected="pending_run" + onReject={() => pendingRun.decline()} + /> + {/if} + <InputSelectedBadge + onReject={() => { + savedInputsV2?.resetSelected() + }} + {inputSelected} + /> + </div> - {#if hasSchema} + <!-- Not offered while the form refuses writes: each side of this + toggle mounts what the other unmounts, and a `password` field + mints a variable from the literal it opens on. The form stays on + whichever side it is already showing, read-only. --> + {#if hasSchema && !pendingRun?.planModeActive} <Toggle bind:checked={jsonView} size="xs" @@ -883,7 +922,11 @@ bind:isValid runnable={flow} runAction={runFlow} + runRefusal={pendingRun?.planModeActive + ? PLAN_MODE_MESSAGES.runFormRefused + : undefined} bind:args + schedulable={!pendingRun} bind:this={runForm} {jsonView} actions={promptForAi ? undefined : aiAssistant} diff --git a/frontend/src/lib/components/details/OnBehalfOfBadge.svelte b/frontend/src/lib/components/details/OnBehalfOfBadge.svelte index 13bd94b122..3b098555f1 100644 --- a/frontend/src/lib/components/details/OnBehalfOfBadge.svelte +++ b/frontend/src/lib/components/details/OnBehalfOfBadge.svelte @@ -8,7 +8,7 @@ onBehalfOf: string | undefined /** Address of the account `onBehalfOf` names, derived from it on the read paths. */ onBehalfOfEmail: string | undefined - kind: 'script' | 'flow' + kind: 'script' | 'flow' | 'agent' } let { onBehalfOf, onBehalfOfEmail, kind }: Props = $props() @@ -25,7 +25,12 @@ {#if onBehalfOf} <Tooltip> {#snippet text()} - Every run of this {kind} is permissioned as {detailed}, whoever starts it. + {#if kind === 'agent'} + Runs of this agent from its page and the API are permissioned as {detailed}, whoever + starts them. + {:else} + Every run of this {kind} is permissioned as {detailed}, whoever starts it. + {/if} {/snippet} <Badge color="violet" icon={{ icon: UserCog, position: 'left' }}> <span class="truncate max-w-40">On behalf of {onBehalfOf}</span> diff --git a/frontend/src/lib/components/details/ScriptDetail.svelte b/frontend/src/lib/components/details/ScriptDetail.svelte index f33f00fb8f..1d6bde0c82 100644 --- a/frontend/src/lib/components/details/ScriptDetail.svelte +++ b/frontend/src/lib/components/details/ScriptDetail.svelte @@ -1,5 +1,4 @@ <script lang="ts"> - import { base } from '$lib/base' import { JobService, ScriptService, @@ -46,10 +45,12 @@ } from '$lib/components/common' import Skeleton from '$lib/components/common/skeleton/Skeleton.svelte' import RunForm from '$lib/components/RunForm.svelte' + import type { PendingRun } from '$lib/components/details/pendingRun' import DbtRunGraph from '$lib/components/dbt/DbtRunGraph.svelte' import { goto } from '$lib/navigation' import MoveDrawer from '$lib/components/MoveDrawer.svelte' + import { PLAN_MODE_MESSAGES } from '$lib/components/copilot/chat/planModeMessages' import { sendUserToast } from '$lib/toast' import NoDirectDeployAlert from '$lib/components/NoDirectDeployAlert.svelte' import DeployWorkspaceDrawer from '$lib/components/DeployWorkspaceDrawer.svelte' @@ -104,6 +105,7 @@ useOperatingUser, useOperatingWorkspaceHref } from '$lib/components/operatingWorkspace.svelte' + import { useEditRights } from '$lib/operatorWriteRights' import { buildForkEditUrl, editInForkAllowed, @@ -126,6 +128,7 @@ onNavigate = goto, active = true, embedded = false, + pendingRun, onLoadState }: { /** The `[...hash]` route segment: either a script hash or a script path. */ @@ -141,6 +144,8 @@ /** Rendered inside a page that is not the script's own (an AI session preview tab), whose * URL this must leave alone and which a cross-workspace link must not navigate away. */ embedded?: boolean + /** A chat tool call confirmed here rather than on its card. See {@link PendingRun}. */ + pendingRun?: PendingRun /** How the load ended, for a host that renders its own state around this page. * Providing it also suppresses the "could not load" toast: a 404 here is the normal * state of a not-yet-deployed path, which the host explains in place instead. */ @@ -173,6 +178,9 @@ script.workspace_id == workspace && canWrite(script.path, script.extra_perms!, actingUser) ) + const editRights = useEditRights() + // The edit actions also need a role that authors scripts, which no operator has. + const canEdit = $derived(can_write && editRights.roleCanAuthor('script')) let deploymentInProgress = $state(false) let expandedModuleLocks: Record<string, boolean> = $state({}) let expandedModuleCode: Record<string, boolean> = $state({}) @@ -377,6 +385,10 @@ invisibleToOwner: boolean | undefined, overrideTag: string | undefined ) { + // Taken before the round trip below: the call this press answers is the one it was + // pressed under, and a call settled meanwhile — declined, then another proposed for + // this same script — must not be answered with a job it never asked for. + const call = pendingRun try { runLoading = true const scheduledFor = scheduledForStr ? new Date(scheduledForStr).toISOString() : undefined @@ -402,7 +414,11 @@ skipPreprocessor: true }) } - await onNavigate('/run/' + run + '?workspace=' + workspace) + // The call asked for this run; it follows the job rather than starting one, and + // shows it in place of this page — so navigating here as well would leave two + // surfaces open on the same job. + if (!call?.adopt(run, args, script?.schema ?? {})) + await onNavigate('/run/' + run + '?workspace=' + workspace) } catch (err) { sendUserToast(`Could not create job: ${err.body}`, true) } finally { @@ -431,6 +447,10 @@ console.error('Was not able to transform hash as args', e) } } + // A chat call confirmed here opens its form on what the chat proposed. Read at init like + // the hash above, and for the same reason; the host remounts this page when the call + // changes, so a tab already open on this script still builds its form from the new one. + if (pendingRun) args = { ...untrack(() => pendingRun.proposedArgs) } // A dbt retry must name the run it resumes, and a job id is not something to // type from memory: picking `retry` fills the field with the run this caller's @@ -529,9 +549,9 @@ buttons.push({ label: 'Fork', description: `Start a new script from a copy of this one`, - narrow: { dropdownOf: 'Edit' }, + placement: { dropdownOf: 'Edit' }, buttonProps: { - href: operatingHref(`${base}/scripts/add?template=${script.path}`), + href: operatingHref(`/scripts/add?template=${script.path}`), onClick: interceptNav(onNavigate, `/scripts/add?template=${script.path}`), unifiedSize: 'md', variant: 'subtle', @@ -550,7 +570,7 @@ buttons.push({ label: editInForkLabel(workspace, $userWorkspaces), description: editInForkDescription('script', workspace, $userWorkspaces), - narrow: { dropdownOf: 'Edit' }, + placement: { dropdownOf: 'Edit' }, buttonProps: { href: buildForkEditUrl('script', script.path, workspace), onClick: (e: Event | undefined) => editInFork(e, script.path), @@ -568,7 +588,7 @@ buttons.push({ label: `Runs`, buttonProps: { - href: operatingHref(`${base}/runs/${script.path}`), + href: operatingHref(`/runs/${script.path}`), onClick: interceptNav(onNavigate, `/runs/${script.path}`), unifiedSize: 'md', variant: 'subtle', @@ -576,14 +596,14 @@ } }) - if (!script || actingUser?.operator || !can_write) { + if (!script || !canEdit) { return buttons } if (Array.isArray(script.parent_hashes) && script.parent_hashes.length > 0) { buttons.push({ label: `History`, - narrow: 'menu', + placement: 'menu', buttonProps: { onClick: () => { versionsDrawerOpen = !versionsDrawerOpen @@ -599,7 +619,8 @@ if (!actingUser?.operator) { buttons.push({ label: 'Build app', - narrow: 'menu', + placement: 'menu', + alwaysPlaced: true, buttonProps: { onClick: async () => { const app = createRawAppFromScript(script.path, script.summary, script.schema) @@ -637,7 +658,7 @@ buttons.push({ label: 'Edit', buttonProps: { - href: operatingHref(`${base}${editUrl}`), + href: operatingHref(editUrl), onClick: interceptNav(onNavigate, editUrl), unifiedSize: 'md', startIcon: Pen, @@ -867,6 +888,12 @@ } : undefined} > + {#snippet name_marks()} + <!-- Favorites are the sidebar's, which lists the navigation workspace only. --> + {#if workspace && script && workspace === $workspaceStore} + <Star kind="script" path={script.path} summary={script.summary} /> + {/if} + {/snippet} {#snippet trigger_badges()} <TriggersBadge showOnlyWithCount={true} @@ -884,12 +911,6 @@ }} /> {/snippet} - {#if workspace && script} - <!-- Favorites are the sidebar's, which lists the navigation workspace only. --> - {#if workspace === $workspaceStore} - <Star kind="script" path={script.path} summary={script.summary} /> - {/if} - {/if} {#if script?.auto_kind === 'wac'} <Popover notClickable> {#snippet text()} @@ -982,7 +1003,7 @@ <Alert type="warning" title="Not HEAD"> This hash is not HEAD (latest non-archived version at this path) : <a - href="{base}/scripts/get/{topHash}?workspace={workspace}" + href="/scripts/get/{topHash}?workspace={workspace}" onclick={interceptNav(onNavigate, `/scripts/get/${topHash}`)} >Go to the HEAD of this path</a > @@ -1027,20 +1048,32 @@ {/if} <div class="flex flex-col align-left"> - {#if (script.schema && Object.keys(script.schema.properties ?? {}).length > 0) || inputSelected} + {#if (script.schema && Object.keys(script.schema.properties ?? {}).length > 0) || inputSelected || pendingRun} {@const hasSchema = script.schema && Object.keys(script.schema.properties ?? {}).length > 0} <div class="flex flex-row justify-between min-h-12" transition:slide={{ duration: 150 }} > - <InputSelectedBadge - onReject={() => { - savedInputsV2?.resetSelected() - }} - {inputSelected} - /> - {#if hasSchema} + <div class="flex flex-row items-start gap-2"> + {#if pendingRun} + <InputSelectedBadge + inputSelected="pending_run" + onReject={() => pendingRun.decline()} + /> + {/if} + <InputSelectedBadge + onReject={() => { + savedInputsV2?.resetSelected() + }} + {inputSelected} + /> + </div> + <!-- Not offered while the form refuses writes: each side of this toggle + mounts what the other unmounts, and a `password` field mints a + variable from the literal it opens on. The form stays on whichever + side it is already showing, read-only. --> + {#if hasSchema && !pendingRun?.planModeActive} <Toggle bind:checked={jsonView} size="xs" @@ -1079,7 +1112,7 @@ {#if Object.keys(script?.schema?.properties ?? {}).length > 0} <AIFormAssistant instructions={promptForAi} - onEditInstructions={can_write && !actingUser?.operator + onEditInstructions={canEdit ? () => onNavigate(`/scripts/edit/${script?.path}?metadata_open=true`) : undefined} runnableType="script" @@ -1104,8 +1137,11 @@ bind:isValid runnable={script} runAction={runScript} + runRefusal={pendingRun?.planModeActive + ? PLAN_MODE_MESSAGES.runFormRefused + : undefined} bind:args - schedulable={true} + schedulable={!pendingRun} bind:this={runForm} {jsonView} actions={promptForAi ? undefined : aiAssistant} diff --git a/frontend/src/lib/components/details/pendingRun.ts b/frontend/src/lib/components/details/pendingRun.ts new file mode 100644 index 0000000000..00e75622fc --- /dev/null +++ b/frontend/src/lib/components/details/pendingRun.ts @@ -0,0 +1,27 @@ +/** + * A chat tool call waiting for a run of this item, shown on the item's deployed page. + * + * The page runs it the way it runs anything — its own form, its own version, its own + * arguments — and tells the call which job that was. The tool then follows that job instead + * of starting one, so the chat reports on the run the reader actually started. + */ +export type PendingRun = { + toolCallId: string + /** The chat promised no runs and no writes. A form standing in for its card owes that + * too: a `password` mints as it is typed and the dynamic-select helper runs on mount, + * both before Run is ever pressed. */ + planModeActive: boolean + /** What the chat proposed, for the form to open on. Read when the form is built, so this + * is the live draft of the card's own form rather than a copy to keep in step. */ + readonly proposedArgs: Record<string, any> + /** The job the reader started here answers the call, with the arguments it was started + * with — the card has no other way to show what ran — and the schema it ran against, which + * a deploy can have moved on from the one the call fetched. Both are needed: redaction + * only visits the leaves a schema declares, so a file argument this page has and that one + * does not would reach the transcript as bytes. True when the call took the job: the chat + * then shows that run in place of this page, so the page must not navigate to it as well. + * False when the call settled while the job was starting, and the run is the reader's + * alone. */ + adopt: (jobId: string, args: Record<string, any>, schema: Record<string, any>) => boolean + decline: () => void +} diff --git a/frontend/src/lib/components/flows/AgentHistory.svelte b/frontend/src/lib/components/flows/AgentHistory.svelte new file mode 100644 index 0000000000..c6deff1e59 --- /dev/null +++ b/frontend/src/lib/components/flows/AgentHistory.svelte @@ -0,0 +1,34 @@ +<script lang="ts"> + import { Drawer, DrawerContent } from '$lib/components/common' + import ResourceVersionHistory from '$lib/components/ResourceVersionHistory.svelte' + import { workspaceStore } from '$lib/stores' + import { markAgentWritten } from './agentEditorStore.svelte' + + interface Props { + path: string + canRestore: boolean + onRestored?: () => void + } + + let { path, canRestore, onRestored }: Props = $props() + let drawer: Drawer | undefined = $state() + + export function open() { + drawer?.openDrawer() + } +</script> + +<Drawer bind:this={drawer} size="1200px"> + <DrawerContent title="Version history" on:close={() => drawer?.closeDrawer()} noPadding> + <ResourceVersionHistory + {path} + {canRestore} + onRestore={() => { + drawer?.closeDrawer() + // A restore writes the resource as a deploy does, so whatever shows this agent re-reads it. + markAgentWritten($workspaceStore ?? undefined, path) + onRestored?.() + }} + /> + </DrawerContent> +</Drawer> diff --git a/frontend/src/lib/components/flows/CreateActionsApp.svelte b/frontend/src/lib/components/flows/CreateActionsApp.svelte index d75d1b33d3..9ab0ea407f 100644 --- a/frontend/src/lib/components/flows/CreateActionsApp.svelte +++ b/frontend/src/lib/components/flows/CreateActionsApp.svelte @@ -1,6 +1,5 @@ <script lang="ts"> import { goto } from '$lib/navigation' - import { base } from '$lib/base' import { Button } from '$lib/components/common' import Drawer from '$lib/components/common/drawer/Drawer.svelte' @@ -39,12 +38,12 @@ function selectLowCode() { appTypeModalOpen = false - goto(`${base}/apps/add`) + goto('/apps/add') } function selectFullCode() { appTypeModalOpen = false - goto(`${base}/apps_raw/add`) + goto('/apps_raw/add') } </script> diff --git a/frontend/src/lib/components/flows/CreateActionsFlow.svelte b/frontend/src/lib/components/flows/CreateActionsFlow.svelte index ae848156f5..9f78585cc0 100644 --- a/frontend/src/lib/components/flows/CreateActionsFlow.svelte +++ b/frontend/src/lib/components/flows/CreateActionsFlow.svelte @@ -1,6 +1,5 @@ <script lang="ts"> import { goto } from '$lib/navigation' - import { base } from '$lib/base' import BarsStaggered from '$lib/components/icons/BarsStaggered.svelte' import { Button } from '$lib/components/common' @@ -35,7 +34,7 @@ const parsed = wacImportType === 'yaml' ? YAML.parse(pendingWacRaw ?? '') : JSON.parse(pendingWacRaw ?? '') $importScriptStore = parsed - await goto(`${base}/scripts/add?import=true`) + await goto('/scripts/add?import=true') wacDrawer?.closeDrawer?.() } @@ -45,22 +44,22 @@ function selectFlowEditor() { flowModalOpen = false - goto(`${base}/flows/add`) + goto('/flows/add') } function selectWacPython() { flowModalOpen = false - goto(`${base}/scripts/add?wac=python`) + goto('/scripts/add?wac=python') } function selectWacTypescript() { flowModalOpen = false - goto(`${base}/scripts/add?wac=typescript`) + goto('/scripts/add?wac=typescript') } function selectPipeline() { flowModalOpen = false - goto(`${base}/pipeline`) + goto('/pipeline') } </script> diff --git a/frontend/src/lib/components/flows/agentActions.ts b/frontend/src/lib/components/flows/agentActions.ts index daaec527df..da31a3665f 100644 --- a/frontend/src/lib/components/flows/agentActions.ts +++ b/frontend/src/lib/components/flows/agentActions.ts @@ -1,8 +1,9 @@ -import { FileUp, Shield, Trash } from 'lucide-svelte' +import { Copy, Eye, FileUp, History, List, Shield, Trash } from 'lucide-svelte' import { ResourceService } from '$lib/gen' import { sendUserToast } from '$lib/toast' -import type { Item } from '$lib/utils' +import { copyToClipboard, type Item } from '$lib/utils' import { isDeployable } from '$lib/utils_deployable' +import { goto } from '$lib/navigation' import type { WorkspaceDeployUISettings } from '$lib/gen' /** Deletes a saved agent, saying how it went. Resolves whether it was deleted. */ @@ -24,10 +25,13 @@ export function agentMenuItems(agent: { /** Never deployed: no resource yet to hold permissions or to deploy onward. */ draftOnly?: boolean wsSpecific?: boolean + /** Hides what an operator has no page for, as on a flow's menu. */ + operator?: boolean /** Undefined until loaded, when nothing is offered for deploy. */ deployUiSettings: WorkspaceDeployUISettings | undefined onPermissions: () => void onDeploy: () => void + onHistory: () => void onDelete: (event?: MouseEvent) => void }): Item[] { const deployable = @@ -35,6 +39,28 @@ export function agentMenuItems(agent: { !agent.draftOnly && isDeployable('resource', agent.path, agent.deployUiSettings) return [ + // A draft-only agent has no runs, no audit trail, and only a placeholder path yet. + ...(agent.draftOnly + ? [] + : [ + { + // An agent run is a flow preview, which the runs page hides by default. Chat turns + // are filed under `<path>.chat` (agent_runs.rs) and listed by the agent's own chat. + displayName: 'View runs', + icon: List, + action: () => goto(`/runs/${agent.path}?job_kinds=previews`) + }, + ...(agent.operator + ? [] + : [ + { + displayName: 'Audit logs', + icon: Eye, + action: () => goto(`/audit_logs?resource=${agent.path}`) + } + ]), + { displayName: 'Copy path', icon: Copy, action: () => copyToClipboard(agent.path) } + ]), { displayName: 'Permissions', icon: Shield, @@ -44,6 +70,9 @@ export function agentMenuItems(agent: { ...(deployable ? [{ displayName: 'Deploy to prod/staging', icon: FileUp, action: agent.onDeploy }] : []), + ...(agent.draftOnly || agent.operator + ? [] + : [{ displayName: 'Version history', icon: History, action: agent.onHistory }]), { displayName: 'Delete', icon: Trash, diff --git a/frontend/src/lib/components/flows/agentDraft.svelte.ts b/frontend/src/lib/components/flows/agentDraft.svelte.ts index b76f9bb471..c0b2ba8bc4 100644 --- a/frontend/src/lib/components/flows/agentDraft.svelte.ts +++ b/frontend/src/lib/components/flows/agentDraft.svelte.ts @@ -3,8 +3,8 @@ import { get } from 'svelte/store' import { deepEqual } from 'fast-equals' import { ResourceService } from '$lib/gen' import { sendUserToast } from '$lib/toast' -import { canWrite } from '$lib/utils' -import { userStore } from '$lib/stores' +import { canEditItem, roleCanAuthor } from '$lib/editRights' +import { userStore, userWorkspaces } from '$lib/stores' import { getUserExt } from '$lib/user' import { UserDraftDbSyncer } from '$lib/userDraftDbSyncer.svelte' import { UserDraft } from '$lib/userDraft.svelte' @@ -144,18 +144,29 @@ export function agentDraftDeployRefusal( */ type AgentWriteResult = { ok: true } | { ok: false; error: string; notAnAgent?: true } +/** Who a deploy makes the agent run as. The server resolves it as it does a flow's: without + * `preserve`, or from someone not allowed to keep another identity, it is the deployer. */ +export interface AgentRunAs { + permissionedAs: string | undefined + preserve: boolean +} + async function writeAgentResource( workspace: string, fromPath: string, state: AgentResourceState, - noDeployed: boolean + noDeployed: boolean, + runAs?: AgentRunAs ): Promise<AgentWriteResult> { const body = { path: state.path, - value: state.args, + value: runAs?.permissionedAs + ? { ...state.args, on_behalf_of: runAs.permissionedAs } + : state.args, description: state.description, labels: state.labels, - ws_specific: state.wsSpecific + ws_specific: state.wsSpecific, + preserve_on_behalf_of: runAs?.preserve || undefined } try { if (noDeployed) { @@ -221,9 +232,12 @@ export interface AgentDraftHandle { /** Why this path cannot be edited here, if it cannot. Render it instead of the form. */ readonly refusal: string | undefined readonly sync: TriggerDraftSync + /** Who the deployed agent runs as when run from its page; undefined when nothing is deployed + * or it runs as whoever runs it. */ + readonly onBehalfOf: string | undefined /** Write the current state to the resource and drop the draft. Resolves to the path written, * which differs from the one loaded when the draft renames the agent, or undefined on failure. */ - deploy: () => Promise<string | undefined> + deploy: (runAs?: AgentRunAs) => Promise<string | undefined> } /** @@ -237,6 +251,7 @@ export function useAgentDraft(opts: AgentDraftOptions): AgentDraftHandle { let loading = $state(true) let noDeployed = $state(false) let canWriteResource = $state(true) + let onBehalfOf = $state<string | undefined>(undefined) /** Guards the load against a path that changed under a slow response. */ let loadedFor = $state<string | undefined>(undefined) /** Why the loaded path cannot be edited here, if it cannot. Gates the sync for as long as that @@ -324,10 +339,15 @@ export function useAgentDraft(opts: AgentDraftOptions): AgentDraftHandle { return } noDeployed = Boolean((r as any).no_deployed) + // Who it runs as is the deploy's to decide, not a setting the form or a draft holds. + const { on_behalf_of, ...args } = (r.value ?? {}) as AIAgentConfig & { + on_behalf_of?: string + } + onBehalfOf = noDeployed ? undefined : on_behalf_of const deployedState: AgentResourceState = { path: r.path, description: r.description ?? '', - args: (r.value ?? {}) as AIAgentConfig, + args, // Only where nothing else answers for the type: with a deployed row both the // create below and the review page's `deployDraft` read it from there, and // carrying it would make every draft the generic resource editor writes — which @@ -339,10 +359,12 @@ export function useAgentDraft(opts: AgentDraftOptions): AgentDraftHandle { // Same rule the generic resource editor applies. The backend refuses the write // either way, but without this the editor would invite edits it cannot save and // autosave a draft on every keystroke against a resource the reader cannot deploy. - canWriteResource = canWrite( + canWriteResource = canEditItem( + 'agent', r.path, - r.extra_perms ?? {}, - user ?? get(userStore) ?? undefined + r.extra_perms, + user ?? get(userStore) ?? undefined, + get(userWorkspaces).find((w) => w.id === ws)?.operator_settings ) // An agent that exists only as a draft has no deployed value to compare against or // fall back to, and the response's is a synthetic echo of the draft. Leaving the @@ -382,7 +404,11 @@ export function useAgentDraft(opts: AgentDraftOptions): AgentDraftHandle { if (loadedFor !== key) return noDeployed = true deployed = undefined - canWriteResource = true + canWriteResource = roleCanAuthor( + 'agent', + get(userStore) ?? undefined, + get(userWorkspaces).find((w) => w.id === ws)?.operator_settings + ) state = { path: name, description: '', @@ -408,7 +434,7 @@ export function useAgentDraft(opts: AgentDraftOptions): AgentDraftHandle { }) }) - async function deploy(): Promise<string | undefined> { + async function deploy(runAs?: AgentRunAs): Promise<string | undefined> { const ws = opts.workspace() const fromPath = opts.path() const s = state @@ -424,7 +450,7 @@ export function useAgentDraft(opts: AgentDraftOptions): AgentDraftHandle { // made during the request as saved, and the banner would clear on a value the server never // received; against the snapshot it stays a draft, which is what it is. const submitted = structuredClone($state.snapshot(s)) as AgentResourceState - const written = await writeAgentResource(ws, fromPath, submitted, noDeployed) + const written = await writeAgentResource(ws, fromPath, submitted, noDeployed, runAs) if (!written.ok) { // A path that is no longer an agent tears this editor down; anything else is a plain error // the user can retry from the form as it stands. @@ -438,8 +464,15 @@ export function useAgentDraft(opts: AgentDraftOptions): AgentDraftHandle { // The counter the step card's write-back used to report, from the surface that now owns the // write: a deploy here reaches every flow linking this agent. logReusableAgentUsage(noDeployed ? 'saved' : 'updated') + // A new agent's editor opens on its draft's storage path, so its first save always lands + // elsewhere: that is naming it, not a rename. + const firstSave = noDeployed deployed = submitted noDeployed = false + // What the server resolved, which a request to keep an identity does not decide alone. + void ResourceService.getResource({ workspace: ws, path: submitted.path }) + .then((r) => (onBehalfOf = (r.value as { on_behalf_of?: string } | undefined)?.on_behalf_of)) + .catch(() => {}) const renamed = submitted.path !== fromPath // Only when the form still holds exactly what was sent. `discard` resets the handle's cell to // what it is given, and the apply-effect copies that back over the form: against an edit made @@ -456,7 +489,9 @@ export function useAgentDraft(opts: AgentDraftOptions): AgentDraftHandle { sync.discard(fromPath, submitted) // A rename moves the row, so the next load must not reuse the old key. loadedFor = `${ws}:${submitted.path}` - sendUserToast(renamed ? `Renamed agent to ${submitted.path}` : `Saved agent ${submitted.path}`) + sendUserToast( + renamed && !firstSave ? `Renamed agent to ${submitted.path}` : `Saved agent ${submitted.path}` + ) return submitted.path } @@ -479,6 +514,9 @@ export function useAgentDraft(opts: AgentDraftOptions): AgentDraftHandle { get refusal() { return refusal }, + get onBehalfOf() { + return onBehalfOf + }, sync, deploy } diff --git a/frontend/src/lib/components/flows/agentFormFields.ts b/frontend/src/lib/components/flows/agentFormFields.ts index e8c5584407..4a9c16f53a 100644 --- a/frontend/src/lib/components/flows/agentFormFields.ts +++ b/frontend/src/lib/components/flows/agentFormFields.ts @@ -10,15 +10,21 @@ import type { InputTransform, MemoryConfig } from '$lib/gen' * the two cannot cycle. */ -export type AgentFieldGroup = 'model' | 'messages' | 'tools' | 'output' +export type AgentFieldGroup = 'model' | 'messages' | 'tools' | 'output' | 'overrides' /** Groups in the order a run assembles the request: pick a model, build the messages, let it call - * tools, shape what comes back. */ -export const AGENT_FIELD_GROUPS: { id: AgentFieldGroup; label: string }[] = [ + * tools, shape what comes back. Overrides come last: only a step linked to a saved agent has + * them, and they replace what the agent saved rather than add to the request. */ +export const AGENT_FIELD_GROUPS: { id: AgentFieldGroup; label: string; caption?: string }[] = [ { id: 'model', label: 'Model' }, { id: 'messages', label: 'Messages' }, { id: 'tools', label: 'Tools' }, - { id: 'output', label: 'Output' } + { id: 'output', label: 'Output' }, + { + id: 'overrides', + label: 'Agent overrides', + caption: "Replace what is saved on the agent, for this step's runs only." + } ] /** The tool roster, which reads `flowModule.value.tools` rather than an `input_transforms` key. @@ -30,6 +36,17 @@ export const AGENT_TOOLS_ROW = 'tools' export const AGENT_HISTORY_KEYS = ['memory_id', 'previous_messages'] as const export type AgentHistoryKey = (typeof AGENT_HISTORY_KEYS)[number] +/** A linked step's overrides of its saved agent. Never seeded either: a step with no override + * holds no key for one. */ +export const AGENT_OVERRIDE_KEYS = ['model', 'reasoning_effort'] as const +export type AgentOverrideKey = (typeof AGENT_OVERRIDE_KEYS)[number] + +/** The inputs whose row exists exactly while the step holds the key. */ +export const AGENT_UNSEEDED_KEYS: readonly string[] = [ + ...AGENT_HISTORY_KEYS, + ...AGENT_OVERRIDE_KEYS +] + /** The input transforms a one-off test of an agent step runs with: each form key is fed from * `flow_input`, over the step's own transforms. A blank history input is unset, as on the step: * an expression evaluating to nothing reads as an empty memory id, and the step's transform is @@ -256,6 +273,24 @@ export const AGENT_FIELDS: AgentFieldSpec[] = [ implicit: true, defaultHint: 'Default: on', textOnly: true + }, + { + key: 'model', + group: 'overrides', + label: 'Model', + tooltip: + "Runs this step on another model than the one saved on the agent, through the agent's own provider resource. Set it to an expression to choose the model per run: an empty value keeps the saved model.", + implicit: '', + defaultHint: 'Default: the model saved on the agent' + }, + { + key: 'reasoning_effort', + group: 'overrides', + label: 'Reasoning effort', + tooltip: + 'Runs this step at another reasoning effort than the one saved on the agent. Set it to an expression to choose the effort per run. An empty value sends no effort, so the model runs at its default. Overriding the model without it does the same.', + implicit: '', + defaultHint: 'Default: the effort saved on the agent' } ] diff --git a/frontend/src/lib/components/flows/agentResourceUtils.test.ts b/frontend/src/lib/components/flows/agentResourceUtils.test.ts index 96b9cf83ff..0799e4357c 100644 --- a/frontend/src/lib/components/flows/agentResourceUtils.test.ts +++ b/frontend/src/lib/components/flows/agentResourceUtils.test.ts @@ -6,6 +6,7 @@ import { flowLocalInputs, inputTransformsToAgentConfig, nonStaticBrainKeys, + providerWithOverrides, summarizeAgentBrain, toolInputOverrides, transformValuedBrainKeys @@ -193,3 +194,54 @@ describe('toolInputOverrides', () => { }) }) }) + +describe('providerWithOverrides', () => { + const saved = { + kind: 'openai', + resource: '$res:u/a/openai', + model: 'gpt-5', + reasoning_effort: 'high' + } + + it('folds static overrides into a static provider, as the worker reads them', () => { + expect( + providerWithOverrides(saved, { reasoning_effort: { type: 'static', value: 'low' } }) + ).toEqual({ type: 'static', value: { ...saved, reasoning_effort: 'low' } }) + // The saved effort names a level of the saved model, so it does not follow to another one. + expect( + providerWithOverrides(saved, { model: { type: 'static', value: 'gpt-5-mini' } }) + ).toEqual({ + type: 'static', + value: { kind: 'openai', resource: '$res:u/a/openai', model: 'gpt-5-mini' } + }) + expect(providerWithOverrides(saved, { model: { type: 'static', value: '' } })).toEqual({ + type: 'static', + value: saved + }) + }) + + it('keeps an expression, resolving as the linked step did', () => { + const run = (overrides: Record<string, string>, flow_input: Record<string, unknown>) => { + const folded = providerWithOverrides( + saved, + Object.fromEntries( + Object.entries(overrides).map(([key, expr]) => [key, { type: 'javascript', expr }]) + ) + ) as { type: 'javascript'; expr: string } + expect(folded.type).toBe('javascript') + return JSON.parse( + JSON.stringify(new Function('flow_input', `return ${folded.expr}`)(flow_input)) + ) + } + const other = { kind: 'openai', resource: '$res:u/a/openai', model: 'gpt-5-mini' } + const effort = { reasoning_effort: 'flow_input.effort' } + const model = { model: 'flow_input.model' } + + expect(run(effort, { effort: 'low' })).toEqual({ ...saved, reasoning_effort: 'low' }) + // An effort the step sets to nothing is no effort, not the saved one. + expect(run(effort, { effort: '' })).toEqual({ ...other, model: 'gpt-5' }) + expect(run(model, { model: '' })).toEqual(saved) + expect(run(model, { model: 'gpt-5-mini' })).toEqual(other) + expect(run({ ...model, ...effort }, { model: 'gpt-5-mini', effort: '' })).toEqual(other) + }) +}) diff --git a/frontend/src/lib/components/flows/agentResourceUtils.ts b/frontend/src/lib/components/flows/agentResourceUtils.ts index 3ee0eaa77e..bf6668a4f1 100644 --- a/frontend/src/lib/components/flows/agentResourceUtils.ts +++ b/frontend/src/lib/components/flows/agentResourceUtils.ts @@ -1,6 +1,11 @@ import { deepEqual } from 'fast-equals' import type { InputTransform } from '$lib/gen' -import { AGENT_FIELDS, describeMemoryPolicy } from './agentFormFields' +import { + AGENT_FIELDS, + AGENT_OVERRIDE_KEYS, + describeMemoryPolicy, + type AgentOverrideKey +} from './agentFormFields' // The brain fields stored flat in an `ai_agent` resource value. The flow-local inputs below are // intentionally excluded — they are supplied per-flow. @@ -31,6 +36,13 @@ export const AGENT_FLOW_LOCAL_KEYS = [ 'previous_messages' ] as const +/** Every input a linked step holds itself: the flow-local ones, and its overrides of what the + * agent saved inside `provider`. */ +export const AGENT_LINKED_STEP_KEYS: readonly string[] = [ + ...AGENT_FLOW_LOCAL_KEYS, + ...AGENT_OVERRIDE_KEYS +] + export type AgentTool = Record<string, any> /** @@ -59,7 +71,7 @@ export function nonStaticBrainKeys( } /** - * Keep only the flow-local inputs on a step's input_transforms. Used when linking: the brain comes + * Keep only the inputs a linked step holds on a step's input_transforms. Used when linking: the brain comes * from the resource, so the step must not carry stale `provider`/`system_prompt`/… transforms — at * runtime they'd still be resolved (an unnecessary, possibly failing provider `$res:` fetch) yet * never used, since the linked branch takes the brain from the resource. @@ -68,7 +80,7 @@ export function flowLocalInputs( inputTransforms: Record<string, InputTransform> | undefined ): Record<string, InputTransform> { const out: Record<string, InputTransform> = {} - for (const key of AGENT_FLOW_LOCAL_KEYS) { + for (const key of AGENT_LINKED_STEP_KEYS) { if (inputTransforms?.[key]) { out[key] = inputTransforms[key] } @@ -106,6 +118,8 @@ export interface AIAgentConfig { temperature?: number max_iterations?: number tools?: AgentTool[] + /** Runs from the agent's page take its `on_behalf_of` rather than the caller's identity. */ + run_on_behalf_of?: boolean } /** Extract the static brain values from a step's input_transforms into a flat agent config. */ @@ -149,6 +163,74 @@ export function flowLocalAgentSchema(schema: any): any { } } +/** + * The schema of a step linked to a saved agent, in a flow: its flow-local inputs, plus the saved + * settings it may override. + */ +export function linkedAgentStepSchema(schema: any): any { + const local = flowLocalAgentSchema(schema) + if (!local?.properties) { + return local + } + return { + ...local, + properties: { + ...local.properties, + model: { + type: 'string', + description: "Replaces the model saved on the agent for this step's runs." + }, + reasoning_effort: { + type: 'string', + description: "Replaces the reasoning effort saved on the agent for this step's runs." + } + }, + order: [...local.order, ...AGENT_OVERRIDE_KEYS] + } +} + +/** + * The `provider` of a step unlinked from its agent: the saved one with the step's overrides folded + * in, since an unlinked step sets model and effort nowhere else. Follows the worker's + * `override_provider_model`, so the step runs on what it ran on while linked. + */ +export function providerWithOverrides( + provider: any, + overrides: Partial<Record<AgentOverrideKey, InputTransform>> | undefined +): InputTransform | undefined { + if (!provider || typeof provider !== 'object') return undefined + const authored = (key: AgentOverrideKey): any => { + const t = overrides?.[key] as any + return t?.type === 'static' || (t?.type === 'javascript' && t.expr) ? t : undefined + } + const text = (t: any): string => (typeof t.value === 'string' ? t.value.trim() : '') + const model = authored('model') + const effort = authored('reasoning_effort') + const { model: savedModel, reasoning_effort: savedEffort, ...rest } = provider + + if (model?.type !== 'javascript' && effort?.type !== 'javascript') { + const runModel = (model && text(model)) || savedModel + const runEffort = effort ? text(effort) : runModel === savedModel ? savedEffort : undefined + return { + type: 'static', + value: { ...rest, model: runModel, ...(runEffort ? { reasoning_effort: runEffort } : {}) } + } + } + const literal = (value: unknown) => (value === undefined ? 'undefined' : JSON.stringify(value)) + const source = (t: any) => (t.type === 'javascript' ? `(${t.expr})` : literal(text(t))) + // One object literal, the shape the flow's expression evaluator and the chat composer both read. + const runModel = model ? `(${source(model)} || ${literal(savedModel)})` : literal(savedModel) + const runEffort = effort + ? `${source(effort)} || undefined` + : `${runModel} === ${literal(savedModel)} ? ${literal(savedEffort)} : undefined` + const fields = [ + ...Object.entries(rest).map(([key, value]) => `${JSON.stringify(key)}: ${literal(value)}`), + `model: ${runModel}`, + `reasoning_effort: ${runEffort}` + ] + return { type: 'javascript', expr: `({ ${fields.join(', ')} })` } +} + /** Read off the form's own registry, so a linked agent's summary cannot name a field differently * from the form that edits it. */ export const AGENT_BRAIN_LABELS: Record<string, string> = Object.fromEntries( @@ -182,7 +264,7 @@ export function summarizeAgentBrain( if (v === undefined || v === null || v === '') continue let value: string if (key === 'provider') { - value = [v.kind, v.model].filter(Boolean).join(' · ') || 'configured' + value = [v.kind, v.model, v.reasoning_effort].filter(Boolean).join(' · ') || 'configured' } else if (key === 'memory') { value = typeof v === 'object' ? describeMemoryPolicy(v) : String(v) } else if (key === 'output_schema') { diff --git a/frontend/src/lib/components/flows/content/AgentEditorHost.svelte b/frontend/src/lib/components/flows/content/AgentEditorHost.svelte index 9c2a57b43f..b902b69bfa 100644 --- a/frontend/src/lib/components/flows/content/AgentEditorHost.svelte +++ b/frontend/src/lib/components/flows/content/AgentEditorHost.svelte @@ -9,7 +9,8 @@ AGENT_CHAT_SCHEMA, agentChatFlow, agentChatGap, - agentChatPath + agentChatPath, + AGENT_STEP_ID } from '../conversations/agentEditorChat' import { runFlowPreview } from '../utils.svelte' import { goto } from '$lib/navigation' @@ -49,7 +50,7 @@ keepsManagedMemory } from '../agentFormFields' import { toolDisplayName, type AgentTool } from '../agentToolUtils' - import { useAgentDraft } from '../agentDraft.svelte' + import { useAgentDraft, type AgentRunAs } from '../agentDraft.svelte' import { sendUserToast } from '$lib/toast' interface Props { @@ -100,7 +101,7 @@ * schema per tool — the linked branch deliberately loads none. Reserved in `forbiddenIds`: * the root shares a flow-state map with the tools, so a tool of this id would lose its * schema to the root's. */ - const AGENT_ID = '__wm_agent_root' + const AGENT_ID = AGENT_STEP_ID const draft = useAgentDraft({ path: () => path, @@ -358,8 +359,8 @@ inputs?: Record<string, any> ): Promise<string | undefined> { if (!agentModule) return undefined - // A view runs the deployed agent, which anyone who can read it may do; the editor previews - // the draft. Both run as the caller. + // A view runs the deployed agent, which anyone who can read it may do, as the server picks + // the identity; the editor previews the draft as the one editing it. if (view && workspace) { return await JobService.runAgent({ workspace, @@ -455,12 +456,21 @@ pathErrorValue = error ?? '' } + /** Who the next deploy makes the agent run as, as the "Permissioned as" line picked it. Unset + * while the line was never shown, which keeps the current identity as the line would have + * preselected it: an admin deploying without looking must not take the agent over. */ + let runAs = $state<AgentRunAs | undefined>(undefined) + export function setRunAs(next: AgentRunAs) { + runAs = next + } + export function deploy(): Promise<boolean> { if (pathErrorValue) { sendUserToast(`Cannot deploy the agent: ${pathErrorValue}`, true) return Promise.resolve(false) } - return draft.deploy().then(async (written) => { + const keep = draft.onBehalfOf ? { permissionedAs: draft.onBehalfOf, preserve: true } : undefined + return draft.deploy(runAs ?? keep).then(async (written) => { // The path the write landed on, which a rename moves off the one this editor opened. if (written) await onSaved?.(written) return written !== undefined diff --git a/frontend/src/lib/components/flows/content/AgentEditorModal.svelte b/frontend/src/lib/components/flows/content/AgentEditorModal.svelte index 0280455e77..58c47bbb20 100644 --- a/frontend/src/lib/components/flows/content/AgentEditorModal.svelte +++ b/frontend/src/lib/components/flows/content/AgentEditorModal.svelte @@ -318,6 +318,7 @@ <PageHeaderContent item={{ path: pathSnapshot ?? shownPath, + summary: draft?.state?.description, summaryContent: agentSummary, // Only where the rename behind it can be saved: a reader who cannot write this agent // keeps the segment that copies the path, rather than an editor with nothing to edit. @@ -581,6 +582,7 @@ path={target?.path ?? ''} workspace={ws} bind:error={() => host?.pathError(), (error) => host?.setPathError(error)} + onRunAsChange={(runAs) => host?.setRunAs(runAs)} /> {/if} {/snippet} diff --git a/frontend/src/lib/components/flows/content/AgentResourceBar.svelte b/frontend/src/lib/components/flows/content/AgentResourceBar.svelte index dc7c0948eb..6aa5a902e8 100644 --- a/frontend/src/lib/components/flows/content/AgentResourceBar.svelte +++ b/frontend/src/lib/components/flows/content/AgentResourceBar.svelte @@ -8,8 +8,8 @@ import ResourcePathHint from '$lib/components/ResourcePathHint.svelte' import { ResourceService, type InputTransform, type Resource } from '$lib/gen' import { sendUserToast } from '$lib/toast' - import { userStore } from '$lib/stores' - import { canWrite } from '$lib/utils' + import { userStore, userWorkspaces } from '$lib/stores' + import { canEditItem } from '$lib/editRights' import { Bot, ChevronDown, ChevronUp, Save, Unlink, Pencil } from 'lucide-svelte' import { AGENT_BRAIN_KEYS, @@ -18,6 +18,7 @@ flowLocalInputs, inputTransformsToAgentConfig, nonStaticBrainKeys, + providerWithOverrides, summarizeAgentBrain, type AIAgentConfig, type AgentTool @@ -61,7 +62,7 @@ flowPath = '', fromAgentEditor = false, chatInputEnabled = false, - linkedMemory = $bindable() + linkedAgent = $bindable() }: { agent: string | undefined inputTransforms: Record<string, InputTransform> @@ -80,8 +81,9 @@ // is the wrong way in. fromAgentEditor?: boolean chatInputEnabled?: boolean - // The linked agent's memory once its config has loaded, for the step's history inputs. - linkedMemory?: { memory: unknown } | undefined + // The linked agent's memory and provider once its config has loaded, for the step's history + // inputs and its overrides. + linkedAgent?: { memory: unknown; provider?: unknown } | undefined } = $props() let ws = $derived(opWorkspace ?? $operatingWorkspace) @@ -226,7 +228,9 @@ loadedInfo?.ws === ws && loadedInfo?.path === agent ? loadedInfo : undefined ) $effect(() => { - linkedMemory = linkedInfo ? { memory: linkedInfo.config?.memory } : undefined + linkedAgent = linkedInfo + ? { memory: linkedInfo.config?.memory, provider: linkedInfo.config?.provider } + : undefined }) let inheritedTools = $derived(linkedInfo?.tools ?? []) let brainParams = $derived(summarizeAgentBrain(linkedInfo?.config)) @@ -235,8 +239,13 @@ let unavailable = $derived(linkedInfo?.unavailable ?? false) let canEditAgent = $derived( !!agent && - !$userStore?.operator && - canWrite(agent, linkedInfo?.extraPerms ?? {}, $userStore ?? undefined) + canEditItem( + 'agent', + agent, + linkedInfo?.extraPerms, + $userStore ?? undefined, + $userWorkspaces.find((w) => w.id === ws)?.operator_settings + ) ) // The hint flips on the first keystroke in the agent editor, so the badge does not wait for the // debounced autosave and the refetch behind it; the fetched answer covers a draft written @@ -507,7 +516,13 @@ local[key] = inputTransforms[key] } } - const forkedInputs = { ...agentConfigToInputTransforms(cfg), ...local } + // An unlinked step sets model and effort inside `provider`, so its overrides move there. + const provider = providerWithOverrides(cfg.provider, inputTransforms) + const forkedInputs = { + ...agentConfigToInputTransforms(cfg), + ...(provider ? { provider } : {}), + ...local + } const forkedTools = cfg.tools ?? [] inputTransforms = forkedInputs for (const tool of forkedTools) { diff --git a/frontend/src/lib/components/flows/content/AgentSettings.svelte b/frontend/src/lib/components/flows/content/AgentSettings.svelte index 449edfccff..ec7d0edb7c 100644 --- a/frontend/src/lib/components/flows/content/AgentSettings.svelte +++ b/frontend/src/lib/components/flows/content/AgentSettings.svelte @@ -7,8 +7,9 @@ import ResourceDescriptionField from '$lib/components/ResourceDescriptionField.svelte' import ResourcePathHint from '$lib/components/ResourcePathHint.svelte' import Toggle from '$lib/components/Toggle.svelte' + import PermissionedAsLine from '$lib/components/triggers/PermissionedAsLine.svelte' import { WorkspaceService } from '$lib/gen' - import type { AgentDraftHandle } from '../agentDraft.svelte' + import type { AgentDraftHandle, AgentRunAs } from '../agentDraft.svelte' /** An agent's own settings, laid out as the top of the resource editor: what it is saved as * rather than what it does. */ @@ -19,9 +20,11 @@ workspace: string | undefined /** Why the path cannot be deployed to, if it cannot. */ error?: string + /** Who the next deploy makes the agent run as, as picked here. */ + onRunAsChange?: (runAs: AgentRunAs) => void } - let { draft, path, workspace, error = $bindable() }: Props = $props() + let { draft, path, workspace, error = $bindable(), onRunAsChange = undefined }: Props = $props() let readOnly = $derived(!draft.canWrite) // Only a workspace that deploys somewhere has anything to keep an agent out of. @@ -64,6 +67,33 @@ {:else} <LabelsInput bind:labels={draft.state.labels} {workspace} class="-mt-4" /> {/if} + <!-- The identity exists only while the toggle is on, resolved on deploy as a flow's + on-behalf-of identity is. --> + <div class="flex flex-col gap-2"> + <Label + label="Run on behalf of" + tooltip="Runs from the agent's page and the API take the permissions of whoever deploys it, or of the user an admin picks. Otherwise they take the caller's." + > + <Toggle + bind:checked={ + () => draft.state?.args.run_on_behalf_of ?? false, + (v) => { + if (draft.state) draft.state.args.run_on_behalf_of = v || undefined + } + } + disabled={readOnly} + /> + </Label> + {#if draft.state.args.run_on_behalf_of} + <PermissionedAsLine + permissionedAs={draft.onBehalfOf} + path={draft.state.path} + disabled={readOnly} + onPermissionedAsChange={(permissionedAs, preserve) => + onRunAsChange?.({ permissionedAs, preserve })} + /> + {/if} + </div> {#if deployTo.current} <Label label="Workspace specific" tooltip="Keeps this agent out of deploys to prod/staging."> <Toggle bind:checked={draft.state.wsSpecific} disabled={readOnly} /> diff --git a/frontend/src/lib/components/flows/content/AiAgentStepInputs.svelte b/frontend/src/lib/components/flows/content/AiAgentStepInputs.svelte index 4e7c7692a5..a123ce9185 100644 --- a/frontend/src/lib/components/flows/content/AiAgentStepInputs.svelte +++ b/frontend/src/lib/components/flows/content/AiAgentStepInputs.svelte @@ -29,7 +29,7 @@ <script lang="ts"> import type { Schema } from '$lib/common' import { deepEqual } from 'fast-equals' - import { type InputTransform } from '$lib/gen' + import { type AIProvider, type InputTransform } from '$lib/gen' import { allTrue, type DynamicInput as DynamicInputTypes } from '$lib/utils' import { getContext, untrack, type Snippet } from 'svelte' import { SvelteSet } from 'svelte/reactivity' @@ -46,6 +46,12 @@ import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte' import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte' import { AlertTriangle, Plus, X } from 'lucide-svelte' + import { resource } from 'runed' + import { aiProviderDetails, fetchAvailableModels } from '$lib/components/copilot/lib' + import { + explicitOffToken, + getReasoningCapability + } from '$lib/components/copilot/reasoningRegistry' import type { PickableProperties } from '../previousResults' import type { FlowCopilotContext } from '$lib/components/copilot/flow' import { enabledToolNames, type AgentTool } from '../agentToolUtils' @@ -53,6 +59,7 @@ AGENT_FIELDS, AGENT_FIELD_BY_KEY, AGENT_HISTORY_KEYS, + AGENT_UNSEEDED_KEYS, AGENT_MEMORY_DOCS_URL, AGENT_TOOLS_ROW, AGENT_FIELD_GROUPS, @@ -114,9 +121,10 @@ onDeleteTool?: (toolId: string) => void /** Where the tool picker's popover belongs, for a surface that is not the flow editor. */ toolPickerPortal?: string - /** A linked agent's memory, once its config has loaded: whether it keeps managed memory decides - * which history inputs the step offers. */ - linkedMemory?: { memory: unknown } | undefined + /** A linked agent's saved config, once it has loaded: whether it keeps managed memory decides + * which history inputs the step offers, and its provider is what the step's overrides + * replace. */ + linkedAgent?: { memory: unknown; provider?: unknown } | undefined /** Set when this agent's config lives in a resource, so `tools` arrives with it rather than * with the step. */ agentLinked?: boolean @@ -150,7 +158,7 @@ onAddTool = undefined, onDeleteTool = undefined, toolPickerPortal = undefined, - linkedMemory = undefined, + linkedAgent = undefined, agentLinked = false }: Props = $props() @@ -195,7 +203,7 @@ ? agentMemoryMode(transform?.value) : undefined } - return linkedMemory ? agentMemoryMode(linkedMemory.memory) : undefined + return linkedAgent ? agentMemoryMode(linkedAgent.memory) : undefined }) // The one-of field rewrites a value that matches none of its options, so a legacy kind the step @@ -212,6 +220,92 @@ return (AGENT_HISTORY_KEYS as readonly string[]).includes(key) } + let savedProvider = $derived( + linkedAgent?.provider as + | { kind?: AIProvider; resource?: string; model?: string; reasoning_effort?: string } + | undefined + ) + + // The models the agent's own provider resource serves, since an override keeps that resource. + const savedProviderModels = resource( + () => ({ + ws, + kind: savedProvider?.kind, + path: savedProvider?.resource?.replace(/^\$res:/, ''), + shown: args?.model != undefined + }), + async ({ ws, kind, path, shown }, _prev, { onCleanup }) => { + if (!shown || !ws || !kind || !path) return [] + const controller = new AbortController() + onCleanup(() => controller.abort()) + try { + return await fetchAvailableModels(path, ws, kind, controller.signal) + } catch { + return aiProviderDetails(kind).defaultModels + } + } + ) + + // The model the effort is placed on: the step's own where it names one, else the agent's. An + // expression is only known once the run is under way, so the agent's model stands in for it: + // its levels are suggestions, and any other value stays typeable. + let modelIsExpression = $derived(args?.model?.type === 'javascript') + let effortModel = $derived.by(() => { + const transform = args?.model + const own = transform?.type === 'static' ? transform.value : undefined + return (typeof own === 'string' && own.trim()) || savedProvider?.model + }) + let effortCapability = $derived( + savedProvider?.kind && effortModel + ? getReasoningCapability(savedProvider.kind, effortModel) + : undefined + ) + let effortChoices = $derived.by(() => { + if (!savedProvider?.kind || !effortModel || !effortCapability?.supported) return undefined + const off = explicitOffToken(savedProvider.kind, effortModel) + return [...(effortCapability.canDisable && off ? [off] : []), ...effortCapability.levels] + }) + + // The override rows offer what the agent's provider has, where that is known. Custom values stay + // typeable: a resource may serve a model its listing omits. Always an enum, even an empty one, so + // the row keeps one shape whatever is known. Held in state of their own, since the field binds + // into the property it renders. + let overrideProperties: Record<string, any> = $state({ model: {}, reasoning_effort: {} }) + $effect(() => { + const model = { + ...schemaProperties.model, + enum: savedProviderModels.current ?? [] + } + const effort = { ...schemaProperties.reasoning_effort, enum: effortChoices ?? [] } + untrack(() => { + if (!deepEqual($state.snapshot(overrideProperties.model), model)) { + overrideProperties.model = model + } + if (!deepEqual($state.snapshot(overrideProperties.reasoning_effort), effort)) { + overrideProperties.reasoning_effort = effort + } + }) + }) + let overrideFieldSchema = $derived({ + ...schema, + properties: { ...schemaProperties, ...overrideProperties } + }) + + function overrideHint(spec: AgentFieldSpec): string | undefined { + if (spec.group !== 'overrides' || !savedProvider) return undefined + if (spec.key !== 'reasoning_effort') + return `Saved on the agent: ${savedProvider.model || 'none'}` + if (!modelIsExpression && effortCapability?.known && !effortCapability.supported) { + return `${effortModel} does not take a reasoning effort` + } + return `Saved on the agent: ${savedProvider.reasoning_effort || 'none'}` + } + + function fieldSchema(key: string) { + if (key === 'memory') return memoryFieldSchema + return key === 'model' || key === 'reasoning_effort' ? overrideFieldSchema : schema + } + // Offer the agent's own tools as the choices for `enabled_tools`, rather than asking for names // to be typed. Written into the schema because that is where `InputTransformForm` reads a // field's shape from; `flowInfers` hands every step its own copy, so this stays this step's. @@ -260,7 +354,7 @@ ? args?.memory?.type === 'static' ? args.memory.value : undefined - : linkedMemory?.memory + : linkedAgent?.memory ) return onThisForm ? `Ignored while memory is set to ${label}.` @@ -272,10 +366,11 @@ scopedFields.some((spec) => spec.key === 'memory_id') ) - // A history input's row follows its key: the remembered `visible` set can outlive a key that a - // save, an undo or the AI chat removed, and a row with no value renders no field. + // A history input's or an override's row follows its key: the remembered `visible` set can + // outlive a key that a save, an undo or the AI chat removed, and a row with no value renders no + // field. function isShown(key: string): boolean { - if (isHistoryKey(key)) { + if (AGENT_UNSEEDED_KEYS.includes(key)) { return args?.[key] != undefined || (key === 'memory_id' && memoryIdOffered) } return visible.has(key) @@ -330,12 +425,13 @@ }) }) - // A history input's row follows its key rather than `visible`, so the run form is told about one - // only while the step holds the key: an inherited memory id has nothing a test run could inherit. + // A history input's or an override's row follows its key rather than `visible`, so the run form + // is told about one only while the step holds the key: an inherited memory id has nothing a test + // run could inherit. $effect(() => { const keys = [ - ...[...visible].filter((key) => !isHistoryKey(key)), - ...AGENT_HISTORY_KEYS.filter((key) => args?.[key] != undefined) + ...[...visible].filter((key) => !AGENT_UNSEEDED_KEYS.includes(key)), + ...AGENT_UNSEEDED_KEYS.filter((key) => args?.[key] != undefined) ] untrack(() => rememberOpenFields(visibilityKey, keys)) }) @@ -372,7 +468,7 @@ function removeField(spec: AgentFieldSpec) { visible.delete(spec.key) if (args) { - if (isHistoryKey(spec.key)) { + if (AGENT_UNSEEDED_KEYS.includes(spec.key)) { delete args[spec.key] } else { // Back to exactly what `flowInfers` seeds, so removing a field leaves no diff behind. @@ -449,27 +545,29 @@ tooltip: string | undefined, removable: AgentFieldSpec | undefined, header: Snippet | undefined = undefined, - collapsed: boolean = false + collapsed: boolean = false, + hint: string | undefined = undefined )} <InputTransformForm {previousModuleId} bind:arg={args[key]} bind:schema={ - () => (key === 'memory' ? memoryFieldSchema : schema), + () => fieldSchema(key), (value) => { - if (key !== 'memory') schema = value + if (fieldSchema(key) === schema) schema = value } } argName={key} {label} headerTooltip={tooltip} + {hint} hideDescription subtleControls {header} indentUnderHeader={false} {collapsed} animateAppear={header != undefined} - argExtra={schemaProperties[key] ?? {}} + argExtra={fieldSchema(key)?.properties?.[key] ?? {}} bind:inputCheck={() => inputCheck[key] ?? false, (value) => (inputCheck[key] = value)} bind:extraLib={() => extraLib ?? 'missing extraLib', (v) => (extraLib = v)} {variableEditor} @@ -558,6 +656,9 @@ {#if rows.length > 0} <div class="w-full flex flex-col"> <h2 class="mb-1 text-2xs font-normal uppercase text-secondary">{group.label}</h2> + {#if group.caption} + <p class="mb-2 text-xs text-secondary">{group.caption}</p> + {/if} <div class="flex flex-col gap-6"> {#each rows as spec (spec.key)} <ResizeTransitionWrapper innerClass="w-full" vertical> @@ -604,7 +705,15 @@ </p> {/if} {:else} - {@render transformField(spec.key, spec.label, spec.tooltip, spec)} + {@render transformField( + spec.key, + spec.label, + spec.tooltip, + spec, + undefined, + false, + overrideHint(spec) + )} {#if isHistoryKey(spec.key) && !historyInputApplies(spec.key, memoryMode)} <p class="mt-1 text-2xs text-hint"> {memoryMode === 'legacy' diff --git a/frontend/src/lib/components/flows/content/DynamicInputHelpBox.svelte b/frontend/src/lib/components/flows/content/DynamicInputHelpBox.svelte index 8ed18d73bf..0a225e1106 100644 --- a/frontend/src/lib/components/flows/content/DynamicInputHelpBox.svelte +++ b/frontend/src/lib/components/flows/content/DynamicInputHelpBox.svelte @@ -3,12 +3,14 @@ import Button from '$lib/components/common/button/Button.svelte' import { ChevronDown } from 'lucide-svelte' + let { hint = undefined }: { hint?: string } = $props() + let opened = $state(false) </script> <!-- Pulled up against the input above: it reads as a footnote on that field rather than as the next thing in the form. --> -<div class="text-2xs flex flex-row-reverse -mt-2"> +<div class="text-2xs flex flex-row-reverse items-start justify-between gap-2 -mt-2"> <Button on:click={() => { opened = !opened @@ -21,6 +23,10 @@ > Help </Button> + {#if hint} + <!-- The 4px a hint keeps from its input; the toggle stays flush against it. --> + <span class="mt-1 text-hint">{hint}</span> + {/if} </div> {#if opened} diff --git a/frontend/src/lib/components/flows/content/ExpandedSubflowStep.svelte b/frontend/src/lib/components/flows/content/ExpandedSubflowStep.svelte index 979717dae1..9002e88adf 100644 --- a/frontend/src/lib/components/flows/content/ExpandedSubflowStep.svelte +++ b/frontend/src/lib/components/flows/content/ExpandedSubflowStep.svelte @@ -13,7 +13,6 @@ type ResolvedExpandedSubflowStep } from '../expandedSubflowStep' import { parseExpandedSubflowId } from '$lib/components/restartFromStepPath' - import { base } from '$app/paths' import FlowPanelChrome from '../common/FlowPanelChrome.svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' @@ -122,7 +121,7 @@ title="Open the subflow in a new tab" startIcon={{ icon: ExternalLink }} iconOnly - href={`${base}/flows/edit/${containingFlowPath}?workspace=${encodeURIComponent( + href={`/flows/edit/${containingFlowPath}?workspace=${encodeURIComponent( opWs ?? '' )}${module ? `&selected=${encodeURIComponent(leafId)}` : ''}`} target="_blank" diff --git a/frontend/src/lib/components/flows/content/FlowEditorDrawer.svelte b/frontend/src/lib/components/flows/content/FlowEditorDrawer.svelte index 6b4d73c6a0..c6c1d13b2a 100644 --- a/frontend/src/lib/components/flows/content/FlowEditorDrawer.svelte +++ b/frontend/src/lib/components/flows/content/FlowEditorDrawer.svelte @@ -11,7 +11,6 @@ import { initFlow } from '$lib/components/flows/flowStore.svelte' import type { FlowState } from '$lib/components/flows/flowState' import type { FlowEditorContext } from '../types' - import { base } from '$app/paths' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' const operatingWorkspace = useOperatingWorkspace() @@ -127,7 +126,7 @@ // Follow the drawer's own selection, which the user may have moved since it opened. const stepId = flowBuilder?.getSelectedId() ?? selectedStepId const selected = stepId ? `?selected=${encodeURIComponent(stepId)}` : '' - window.open(`${base}/flows/edit/${flowPath}${selected}`, '_blank', 'noopener,noreferrer') + window.open(`/flows/edit/${flowPath}${selected}`, '_blank', 'noopener,noreferrer') flowEditorDrawer?.closeDrawer() }} startIcon={{ icon: ExternalLink }} diff --git a/frontend/src/lib/components/flows/content/FlowInputs.svelte b/frontend/src/lib/components/flows/content/FlowInputs.svelte index f86d870a1a..41d860530a 100644 --- a/frontend/src/lib/components/flows/content/FlowInputs.svelte +++ b/frontend/src/lib/components/flows/content/FlowInputs.svelte @@ -291,6 +291,18 @@ }) }} /> + <FlowScriptPicker + label="Pi" + lang="pisandbox" + on:click={() => { + dispatch('new', { + language: 'bun', + kind, + subkind: 'pisandbox', + summary + }) + }} + /> </div> {/if} diff --git a/frontend/src/lib/components/flows/content/FlowInputsQuick.svelte b/frontend/src/lib/components/flows/content/FlowInputsQuick.svelte index 0b78193c6a..ecb3187c5c 100644 --- a/frontend/src/lib/components/flows/content/FlowInputsQuick.svelte +++ b/frontend/src/lib/components/flows/content/FlowInputsQuick.svelte @@ -267,28 +267,33 @@ ) let aiLength = $derived(showAiRows ? 2 : 0) - // Must match the heading and label rendered for the AI Sandbox section const aiSandboxHeading = 'AI Sandbox' - const aiSandboxLabel = 'Claude Code' - let matchesAiSandbox = $derived.by(() => { + const aiSandboxes = [ + { label: 'Claude Code', subkind: 'claudesandbox' }, + { label: 'Pi', subkind: 'pisandbox' } + ] as const + // A query matching the heading keeps every sandbox, otherwise only the ones it names. + let matchingAiSandboxes = $derived.by(() => { const query = funcDesc?.trim().toLowerCase() ?? '' - if (query.length == 0) { - return true - } - return [aiSandboxHeading, aiSandboxLabel].some((term) => { + const matches = (term: string) => { const lowered = term.toLowerCase() return lowered.startsWith(query) || lowered.split(' ').some((w) => w.startsWith(query)) - }) + } + if (query.length == 0 || matches(aiSandboxHeading)) { + return aiSandboxes + } + return aiSandboxes.filter((s) => matches(s.label)) }) - // Gates the AI Sandbox row and its slot in the index space; both must agree or arrow keys land - // on an index that renders nothing. - let showAiSandbox = $derived( + // Gates the AI Sandbox rows and their slots in the index space; both must agree or arrow keys + // land on an index that renders nothing. + let aiSandboxRows = $derived( selectedKind === 'script' && preFilter === 'all' && !selected && customUi?.aiSandbox != false && - !$operatorBuilderFlows && - matchesAiSandbox + !$operatorBuilderFlows + ? matchingAiSandboxes + : [] ) // Hub runnables carry code the workspace never reviewed, and the backend refuses them in a @@ -301,7 +306,7 @@ let aiOffset = $derived(inlineOffset + (inlineScripts?.length ?? 0)) let workspaceOffset = $derived(aiOffset + aiLength) let aiSandboxOffset = $derived(workspaceOffset + (filteredWorkspaceItems?.length ?? 0)) - let hubOffset = $derived(aiSandboxOffset + (showAiSandbox ? 1 : 0)) + let hubOffset = $derived(aiSandboxOffset + aiSandboxRows.length) </script> <svelte:window onkeydown={onKeyDown} /> @@ -530,27 +535,29 @@ {/await} <div class="pb-1"></div> {/if} - {#if showAiSandbox} + {#if aiSandboxRows.length > 0} <div class="pb-0 text-2xs font-normal text-secondary ml-2">{aiSandboxHeading}</div> - <FlowScriptPickerQuick - eeRestricted={false} - selected={selectedByKeyboard === aiSandboxOffset} - onHover={() => hover(aiSandboxOffset)} - enterpriseLangs={[]} - label={aiSandboxLabel} - lang="claudesandbox" - on:click={() => { - dispatch('new', { - kind: selectedKind, - inlineScript: { - language: 'bun', + {#each aiSandboxRows as sandbox, i (sandbox.subkind)} + <FlowScriptPickerQuick + eeRestricted={false} + selected={selectedByKeyboard === aiSandboxOffset + i} + onHover={() => hover(aiSandboxOffset + i)} + enterpriseLangs={[]} + label={sandbox.label} + lang={sandbox.subkind} + on:click={() => { + dispatch('new', { kind: selectedKind, - subkind: 'claudesandbox', - summary - } - }) - }} - /> + inlineScript: { + language: 'bun', + kind: selectedKind, + subkind: sandbox.subkind, + summary + } + }) + }} + /> + {/each} {/if} {#if showHub && selectedKind != 'preprocessor' && selectedKind != 'flow'} {#if (!selected || selected?.kind === 'integrations') && (preFilter === 'hub' || preFilter === 'all')} diff --git a/frontend/src/lib/components/flows/content/FlowModuleComponent.svelte b/frontend/src/lib/components/flows/content/FlowModuleComponent.svelte index 1ca2ed94fc..5694965663 100644 --- a/frontend/src/lib/components/flows/content/FlowModuleComponent.svelte +++ b/frontend/src/lib/components/flows/content/FlowModuleComponent.svelte @@ -33,7 +33,7 @@ import AiAgentStepInputs from './AiAgentStepInputs.svelte' import AgentToolBindings from './AgentToolBindings.svelte' import { getLinkedAgentTools, linkedToolsScope } from '../linkedAgentToolsStore.svelte' - import { flowLocalAgentSchema } from '../agentResourceUtils' + import { linkedAgentStepSchema } from '../agentResourceUtils' import { AI_AGENT_TOOL_AI_KEYS, AI_DECISION_TOOL_AI_KEYS } from '../agentToolUtils' import { setAiDecisionStep } from '../aiDecisionBranching' import DiffEditor from '$lib/components/DiffEditor.svelte' @@ -309,7 +309,7 @@ let inputTransformSchemaForm: { setArgs: (nargs: Record<string, any>) => void } | undefined = $state(undefined) // The linked agent's memory, which decides which history inputs the step offers. - let linkedAgentMemory: { memory: unknown } | undefined = $state(undefined) + let linkedAgentConfig: { memory: unknown; provider?: unknown } | undefined = $state(undefined) let reloadError: string | undefined = $state(undefined) async function reload(flowModule: FlowModule) { @@ -1180,7 +1180,7 @@ opWorkspace={opWs} flowPath={$pathStore} fromAgentEditor={agentEditorHost?.() != undefined} - bind:linkedMemory={linkedAgentMemory} + bind:linkedAgent={linkedAgentConfig} chatInputEnabled={flowStore.val.value?.chat_input_enabled ?? false} bind:agent={ () => @@ -1233,7 +1233,7 @@ bind:this={inputTransformSchemaForm} pickableProperties={stepPropPicker.pickableProperties} schema={agentLinked - ? flowLocalAgentSchema( + ? linkedAgentStepSchema( flowStateStore.val[flowModule.id]?.schema ?? {} ) : (flowStateStore.val[flowModule.id]?.schema ?? {})} @@ -1263,7 +1263,7 @@ chatInputEnabled={flowStore.val.value?.chat_input_enabled ?? false} workspace={opWs} visibilityKey={agentFieldsKey} - linkedMemory={agentLinked ? linkedAgentMemory : undefined} + linkedAgent={agentLinked ? linkedAgentConfig : undefined} {agentLinked} tools={agentLinked ? getLinkedAgentTools( @@ -1367,7 +1367,7 @@ mod={flowModule} {noEditor} schema={agentLinked - ? flowLocalAgentSchema(flowStateStore.val[flowModule.id]?.schema ?? {}) + ? linkedAgentStepSchema(flowStateStore.val[flowModule.id]?.schema ?? {}) : (flowStateStore.val[flowModule.id]?.schema ?? {})} bind:testJob bind:testIsLoading diff --git a/frontend/src/lib/components/flows/content/FlowSettings.svelte b/frontend/src/lib/components/flows/content/FlowSettings.svelte index 0ae94b208e..dacb9efd4d 100644 --- a/frontend/src/lib/components/flows/content/FlowSettings.svelte +++ b/frontend/src/lib/components/flows/content/FlowSettings.svelte @@ -32,6 +32,8 @@ type OnBehalfOfChoice } from '$lib/components/OnBehalfOfSelector.svelte' import { modulesWithRetryOrSleep, SAME_WORKER_INCOMPATIBLE_MSG } from '../utils.svelte' + import { earlyReturnCandidates } from '../earlyReturnCandidates' + import Select from '$lib/components/select/Select.svelte' import { useOperatingUser, useOperatingWorkspace @@ -388,23 +390,26 @@ }} /> {#if flowStore.val.value.early_return} - <div - class="max-w-[120px] flex flex-col mt-2 {flowStore.val.value.early_return - ? '' - : 'bg-surface-secondary'}" - transition:slide={{ duration: 120 }} - > - <select - name="oauth_name" - id="oauth_name" + {@const candidates = earlyReturnCandidates(flowStore.val.value.modules ?? [])} + {@const selected = candidates.find((c) => c.id === flowStore.val.value.early_return)} + <div class="mt-2 flex flex-col gap-1 max-w-sm" transition:slide={{ duration: 120 }}> + <Select + items={candidates.map((c) => ({ value: c.id, label: c.id }))} bind:value={flowStore.val.value.early_return} - class="text-xs" - > - <option value={undefined}>Node's id</option> - {#each flowStore.val.value?.modules?.map((x) => x.id) as name} - <option value={name}>{name}</option> - {/each} - </select> + placeholder="Node's id" + size="sm" + /> + {#if !selected} + <span class="text-2xs text-red-600 dark:text-red-400"> + Step {flowStore.val.value.early_return} is not one of the steps above. Pick another + step. + </span> + {:else if !selected.deterministic} + <span class="text-2xs text-secondary"> + This step only runs if its branch is taken. Otherwise, sync calls return the + flow's final result. + </span> + {/if} </div> {/if} </div> diff --git a/frontend/src/lib/components/flows/conversations/FlowChatInterface.svelte b/frontend/src/lib/components/flows/conversations/FlowChatInterface.svelte index f6cc9af6f5..9d7f39ed2c 100644 --- a/frontend/src/lib/components/flows/conversations/FlowChatInterface.svelte +++ b/frontend/src/lib/components/flows/conversations/FlowChatInterface.svelte @@ -12,7 +12,8 @@ import { tick, untrack } from 'svelte' import type { Chat } from 'windmill-chat' import { saveFlowChatInputs } from './flowChatProps' - import type { FlowModule } from '$lib/gen' + import { ResourceService, type FlowModule } from '$lib/gen' + import { resource } from 'runed' import { useWorkspaceStorageConfigured } from '$lib/components/inputTransformEnv.svelte' import { attachmentsTargetFor, @@ -23,10 +24,12 @@ import FlowChatModelSettings from './FlowChatModelSettings.svelte' import { agentModelGap, + chatLinkedAgentPaths, composerOwnedInputs, resolveAgentModelWiring, showsModelButton, - withoutRejectedEffort + withoutRejectedEffort, + type SavedAgentProviders } from './agentChatInputs' interface Props { @@ -107,7 +110,26 @@ // The model gets its own button, shaped like the copilot's model settings, driven by // whichever provider fields the flow exposes. Attachments are the paperclip's; every other // flow input is asked for in the Configure-inputs modal. - const modelWiring = $derived(resolveAgentModelWiring(flowModules)) + // A step linked to a saved agent takes its provider from the agent, so that is read here. One + // the reader cannot load leaves the wiring unreadable, and the model button away. + const savedProviders = resource( + () => ({ workspace, paths: chatLinkedAgentPaths(flowModules) }), + async ({ workspace, paths }): Promise<SavedAgentProviders> => { + if (!workspace || paths.length === 0) return {} + const entries = await Promise.all( + paths.map(async (path) => { + try { + const value: any = await ResourceService.getResourceValue({ workspace, path }) + return [path, value?.provider] as const + } catch { + return [path, undefined] as const + } + }) + ) + return Object.fromEntries(entries) + } + ) + const modelWiring = $derived(resolveAgentModelWiring(flowModules, savedProviders.current)) // An agent with nothing to call cannot answer, and the composer cannot fix it, so the // chat says what to go and do instead of offering controls that write nowhere. const modelGap = $derived(agentModelGap(modelWiring, subject)) diff --git a/frontend/src/lib/components/flows/conversations/FlowChatModelSettings.svelte b/frontend/src/lib/components/flows/conversations/FlowChatModelSettings.svelte index f27e14749e..f777a4cf49 100644 --- a/frontend/src/lib/components/flows/conversations/FlowChatModelSettings.svelte +++ b/frontend/src/lib/components/flows/conversations/FlowChatModelSettings.svelte @@ -25,6 +25,7 @@ import { resource } from 'runed' import { composerDrivenFields, + wiredFieldValue, type AgentModelWiring, type ProviderField } from './agentChatInputs' @@ -40,9 +41,7 @@ let { wiring, values, setValue, workspace }: Props = $props() function fieldValue(field: ProviderField): any { - if (wiring.whole) return values[wiring.whole]?.[field] - const name = wiring.fields[field] - return name ? values[name] : wiring.fixed[field] + return wiredFieldValue(wiring, values, field) } const driven = $derived(composerDrivenFields(wiring)) diff --git a/frontend/src/lib/components/flows/conversations/agentChatInputs.test.ts b/frontend/src/lib/components/flows/conversations/agentChatInputs.test.ts index 00561330d0..6855f8bbf7 100644 --- a/frontend/src/lib/components/flows/conversations/agentChatInputs.test.ts +++ b/frontend/src/lib/components/flows/conversations/agentChatInputs.test.ts @@ -6,6 +6,7 @@ import { parseProviderTransform, resolveAgentModelWiring, showsModelButton, + wiredFieldValue, withoutRejectedEffort } from './agentChatInputs' import type { FlowModule } from '$lib/gen' @@ -499,3 +500,84 @@ describe('parseProviderTransform with comments', () => { ).toBeUndefined() }) }) + +describe('a step linked to a saved agent', () => { + const saved = { + 'u/a/agent': { + kind: 'anthropic', + resource: '$res:u/a/claude', + model: 'claude-sonnet-4-5', + reasoning_effort: 'high' + } + } + function linked(input_transforms: Record<string, unknown>): FlowModule { + return { + id: 'a', + value: { type: 'aiagent', agent: '$res:u/a/agent', tools: [], input_transforms } + } as unknown as FlowModule + } + const wired = linked({ + model: { type: 'javascript', expr: 'flow_input.model' }, + reasoning_effort: { type: 'javascript', expr: 'flow_input.effort' } + }) + + it('drives the overrides it wires, on the provider the agent saved', () => { + const wiring = resolveAgentModelWiring([wired], saved) + expect(wiring?.fields).toEqual({ model: 'model', reasoning_effort: 'effort' }) + expect(wiring?.fixed).toEqual({ kind: 'anthropic', resource: '$res:u/a/claude' }) + expect(agentModelWiringInputs(wiring).sort()).toEqual(['effort', 'model']) + }) + + it('shows the saved model for a model input left empty, and no effort for an empty effort', () => { + const wiring = resolveAgentModelWiring([wired], saved)! + expect(wiredFieldValue(wiring, {}, 'model')).toBe('claude-sonnet-4-5') + // Empty is how a model that reasons only on request is turned off. + expect(wiredFieldValue(wiring, { effort: '' }, 'reasoning_effort')).toBe('') + }) + + it('shows the saved effort where the step sets none, only on the saved model', () => { + const wiring = resolveAgentModelWiring( + [linked({ model: { type: 'javascript', expr: 'flow_input.model' } })], + saved + )! + expect(wiredFieldValue(wiring, {}, 'reasoning_effort')).toBe('high') + const none = resolveAgentModelWiring( + [linked({ reasoning_effort: { type: 'static', value: '' } })], + saved + )! + expect(wiredFieldValue(none, {}, 'reasoning_effort')).toBe('') + expect( + wiredFieldValue(wiring, { model: 'claude-haiku-4-5' }, 'reasoning_effort') + ).toBeUndefined() + }) + + it('does not show the saved effort for steps that fix different ones', () => { + const effort = (value: string) => + linked({ + model: { type: 'javascript', expr: 'flow_input.model' }, + reasoning_effort: { type: 'static', value } + }) + const wiring = resolveAgentModelWiring([effort('low'), effort('medium')], saved)! + expect(wiredFieldValue(wiring, {}, 'reasoning_effort')).toBeUndefined() + expect(wiredFieldValue(wiring, {}, 'model')).toBe('claude-sonnet-4-5') + + // Two agents that share a model and saved different efforts are in the same position. + const other = { ...wired, value: { ...wired.value, agent: '$res:u/a/other' } } as FlowModule + const two = resolveAgentModelWiring([wired, other], { + ...saved, + 'u/a/other': { ...saved['u/a/agent'], reasoning_effort: 'low' } + })! + expect(wiredFieldValue(two, {}, 'model')).toBe('claude-sonnet-4-5') + expect(two.saved?.reasoning_effort).toBeUndefined() + }) + + it('cannot be read until the agent has loaded, or with an expression it cannot place', () => { + expect(resolveAgentModelWiring([wired], {})).toBeUndefined() + expect( + resolveAgentModelWiring( + [linked({ model: { type: 'javascript', expr: 'pick(flow_input.model)' } })], + saved + ) + ).toBeUndefined() + }) +}) diff --git a/frontend/src/lib/components/flows/conversations/agentChatInputs.ts b/frontend/src/lib/components/flows/conversations/agentChatInputs.ts index 1c178bde26..6cfe730572 100644 --- a/frontend/src/lib/components/flows/conversations/agentChatInputs.ts +++ b/frontend/src/lib/components/flows/conversations/agentChatInputs.ts @@ -4,6 +4,12 @@ import { carriedReasoning } from '$lib/components/copilot/chatModelSettings' import { parseExpressionAt } from 'acorn' import { agentSteps, flowInputReads } from './agentAttachmentInput' +/** A step names its agent bare or as `$res:<path>`/`res://<path>`, as `linkedAgentDrafts` reads it; + * kept apart from that module, which loads the editor's draft stores. */ +function normalizeAgentRef(agentRef: string): string { + return agentRef.replace(/^\$res:/, '').replace(/^res:\/\//, '') +} + /** Block and line comments removed, so what is left is only what affects the value. */ function withoutComments(source: string): string { return source.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/[^\n]*/g, '') @@ -78,6 +84,82 @@ export type AgentModelWiring = { * which describe what the composer may offer. */ someAgentCannotRun?: boolean + /** + * What a step linked to a saved agent runs on where it overrides nothing: an empty model + * input keeps the saved model, and the saved effort applies only on that model, to a step + * that sets no effort of its own. + */ + saved?: { model?: string; reasoning_effort?: string } +} + +/** The provider saved on each linked agent, by resource path. */ +export type SavedAgentProviders = Record<string, Record<string, any> | undefined> + +/** The saved agents whose provider the wiring needs, as bare resource paths. */ +export function chatLinkedAgentPaths(modules: FlowModule[] | undefined): string[] { + const paths = chatFacingAgents(modules) + .map((module) => (module.value as any).agent as string | undefined) + .filter((agent): agent is string => !!agent) + .map(normalizeAgentRef) + return [...new Set(paths)].sort() +} + +/** + * Read a step linked to a saved agent: the provider is the agent's, except for the model and + * effort the step overrides, each a literal or one flow input. + */ +function parseLinkedStep( + provider: Record<string, any> | undefined, + transforms: Record<string, InputTransform> | undefined +): AgentModelWiring | undefined { + if (!provider || typeof provider !== 'object') return undefined + const fixed: AgentModelWiring['fixed'] = {} + for (const field of PROVIDER_FIELDS) { + if (provider[field] !== undefined) fixed[field] = provider[field] + } + const saved = { model: fixed.model, reasoning_effort: fixed.reasoning_effort } + // Read off `saved` by whoever shows it, since it holds only on the saved model. + delete fixed.reasoning_effort + const fields: AgentModelWiring['fields'] = {} + for (const field of ['model', 'reasoning_effort'] as const) { + const transform = transforms?.[field] as any + if (!transform) continue + if (transform.type === 'static') { + const value = typeof transform.value === 'string' ? transform.value.trim() : '' + // An empty model keeps the saved one; an empty effort is the step's choice of none. + if (value || field === 'reasoning_effort') fixed[field] = value + continue + } + if (transform.type !== 'javascript') return undefined + const name = flowInputName(parseExpression(transform.expr)) + if (!name) return undefined + fields[field] = name + delete fixed[field] + } + return { fields, fixed, saved } +} + +/** + * The value a provider field runs on, given what the composer holds, as the worker's + * `override_provider_model` resolves a linked agent's. + */ +export function wiredFieldValue( + wiring: AgentModelWiring, + values: Record<string, any>, + field: ProviderField +): any { + if (wiring.whole) return values[wiring.whole]?.[field] + const name = wiring.fields[field] + const own = name ? values[name] : wiring.fixed[field] + if (!wiring.saved) return own + if (field === 'model') return own || wiring.saved.model + // An effort the step overrides is the run's whatever it holds: empty there is no effort. + if (field === 'reasoning_effort' && !name && own === undefined) { + return wiredFieldValue(wiring, values, 'model') === wiring.saved.model + ? wiring.saved.reasoning_effort + : own + } + return own } /** The flow input behind `flow_input.x`, `flow_input?.x` or `flow_input['x']`. */ @@ -121,23 +203,8 @@ export function parseProviderTransform( } if (transform?.type !== 'javascript') return undefined - // The author's own text may already be wrapped, so any balanced surround is fine — what - // the span check rejects is an expression with something else beside it. - const source = parenthesised(transform.expr) - let node: any - try { - node = parseExpressionAt(source, 0, { ecmaVersion: 'latest' }) - } catch { - return undefined - } - // A comment beside the expression is not another expression: the author annotating their - // own provider must not cost them the model control. Dropped before the check so what - // remains is only what would change the value — and so a paren inside a comment is not - // counted as one of the wrapping pair. - const before = withoutComments(source.slice(0, node.start)) - const after = withoutComments(source.slice(node.end)) - if (!/^[\s(]*$/.test(before) || !/^[\s)]*$/.test(after)) return undefined - if ((before.match(/\(/g)?.length ?? 0) !== (after.match(/\)/g)?.length ?? 0)) return undefined + const node = parseExpression(transform.expr) + if (!node) return undefined const whole = flowInputName(node) if (whole) return { whole, fields: {}, fixed: {} } @@ -162,6 +229,28 @@ export function parseProviderTransform( return { fields, fixed } } +/** The one expression a transform holds, or undefined where it is anything more than that. */ +function parseExpression(expr: string): any { + // The author's own text may already be wrapped, so any balanced surround is fine — what + // the span check rejects is an expression with something else beside it. + const source = parenthesised(expr) + let node: any + try { + node = parseExpressionAt(source, 0, { ecmaVersion: 'latest' }) + } catch { + return undefined + } + // A comment beside the expression is not another expression: the author annotating their + // own provider must not cost them the model control. Dropped before the check so what + // remains is only what would change the value — and so a paren inside a comment is not + // counted as one of the wrapping pair. + const before = withoutComments(source.slice(0, node.start)) + const after = withoutComments(source.slice(node.end)) + if (!/^[\s(]*$/.test(before) || !/^[\s)]*$/.test(after)) return undefined + if ((before.match(/\(/g)?.length ?? 0) !== (after.match(/\)/g)?.length ?? 0)) return undefined + return node +} + /** How one agent supplies a provider field: from an input, as a literal, or not at all. */ type FieldSupply = | { kind: 'wired'; name: string } @@ -192,12 +281,16 @@ function fieldSupply(wiring: AgentModelWiring, field: ProviderField): FieldSuppl * and field-by-field wiring is ambiguous throughout and yields nothing. */ export function resolveAgentModelWiring( - modules: FlowModule[] | undefined + modules: FlowModule[] | undefined, + savedProviders: SavedAgentProviders = {} ): AgentModelWiring | undefined { const agents = chatFacingAgents(modules) - const parsed = agents.map((agent) => - parseProviderTransform((agent.value as any).input_transforms?.['provider']) - ) + const parsed = agents.map((agent) => { + const value = agent.value as any + return value.agent + ? parseLinkedStep(savedProviders[normalizeAgentRef(value.agent)], value.input_transforms) + : parseProviderTransform(value.input_transforms?.['provider']) + }) if (parsed.length === 0) return undefined // An agent whose provider cannot be read is an agent the composer cannot speak for: // dropping it would let the rest declare a control that governs only some of them. @@ -219,19 +312,37 @@ export function resolveAgentModelWiring( const fields: AgentModelWiring['fields'] = {} const fixed: AgentModelWiring['fixed'] = {} + const disagreed = new Set<ProviderField>() for (const field of PROVIDER_FIELDS) { // Every agent has to supply the field the same way for the composer to speak for // them all. One wired name among agents that otherwise fix it is not agreement: // the control would move that one agent and leave the others where they are. const supplies = new Set(wirings.map((w) => JSON.stringify(fieldSupply(w, field)))) + // Disagreement leaves the field neither editable nor known: a control offered here // would govern one agent while the rest ran on something else. - if (supplies.size > 1) continue + if (supplies.size > 1) { + disagreed.add(field) + continue + } const supply: FieldSupply = JSON.parse([...supplies][0]) if (supply.kind === 'wired') fields[field] = supply.name else if (supply.kind === 'fixed') fixed[field] = supply.value } - return { fields, fixed, someAgentCannotRun } + // An empty input means one thing only where every agent falls back to the same saved value, + // and a saved value must not stand in for a field the agents disagree about. The saved effort + // belongs to the saved model, so it is only kept alongside one. + const common = (field: 'model' | 'reasoning_effort') => { + const values = new Set(wirings.map((w) => w.saved?.[field])) + return values.size === 1 && !disagreed.has(field) ? [...values][0] : undefined + } + const model = common('model') + return { + fields, + fixed, + someAgentCannotRun, + saved: model === undefined ? undefined : { model, reasoning_effort: common('reasoning_effort') } + } } /** @@ -357,11 +468,9 @@ export function withoutRejectedEffort( const effortInput = wiring.fields.reasoning_effort if (!effortInput) return values - const kindInput = wiring.fields.kind - const modelInput = wiring.fields.model const rejected = rejectsEffort( - kindInput ? values[kindInput] : wiring.fixed.kind, - modelInput ? values[modelInput] : wiring.fixed.model, + wiredFieldValue(wiring, values, 'kind'), + wiredFieldValue(wiring, values, 'model'), values[effortInput] ) return rejected ? { ...values, [effortInput]: '' } : values diff --git a/frontend/src/lib/components/flows/conversations/agentEditorChat.test.ts b/frontend/src/lib/components/flows/conversations/agentEditorChat.test.ts index c00c1e4297..99db5b8a9f 100644 --- a/frontend/src/lib/components/flows/conversations/agentEditorChat.test.ts +++ b/frontend/src/lib/components/flows/conversations/agentEditorChat.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' import type { FlowModule } from '$lib/gen' -import { agentChatFlow, agentChatGap, agentChatPath } from './agentEditorChat' +import { agentChatFlow, agentChatGap, agentChatPath, agentStepLabel } from './agentEditorChat' describe('agentChatPath', () => { it('is a path no flow can take, so a same-path flow never shares its conversations', () => { @@ -10,6 +10,14 @@ describe('agentChatPath', () => { }) }) +describe('agentStepLabel', () => { + it("names a run's agent step by the agent, a chat turn's included", () => { + expect(agentStepLabel('f/support/agent')).toBe('f/support/agent') + expect(agentStepLabel(agentChatPath('f/support/agent'))).toBe('f/support/agent') + expect(agentStepLabel(undefined)).toBe('AI Agent') + }) +}) + function agent(inputTransforms: Record<string, any>): FlowModule { return { id: '__wm_agent_root', diff --git a/frontend/src/lib/components/flows/conversations/agentEditorChat.ts b/frontend/src/lib/components/flows/conversations/agentEditorChat.ts index b754e04bb8..0f1bc86bda 100644 --- a/frontend/src/lib/components/flows/conversations/agentEditorChat.ts +++ b/frontend/src/lib/components/flows/conversations/agentEditorChat.ts @@ -13,6 +13,15 @@ export function agentChatPath(agentPath: string): string { return `${agentPath}.chat` } +/** The id of the one step a saved agent's run is made of, as the server names it too: job-read + * scoping and the run's agent detection match on it, so it is only ever relabeled for display. */ +export const AGENT_STEP_ID = '__wm_agent_root' + +/** What a run shows for that step: the agent it ran, read off the run's path. */ +export function agentStepLabel(runPath: string | undefined): string { + return runPath?.replace(/\.chat$/, '') || 'AI Agent' +} + /** * The inputs of the flow a saved agent is chatted with: the message, and the files the composer's * paperclip uploads. `user_message` is the name the server requires of a chat-mode run. diff --git a/frontend/src/lib/components/flows/conversations/messageAttachments.ts b/frontend/src/lib/components/flows/conversations/messageAttachments.ts index 36c7d103c3..18170a90df 100644 --- a/frontend/src/lib/components/flows/conversations/messageAttachments.ts +++ b/frontend/src/lib/components/flows/conversations/messageAttachments.ts @@ -1,6 +1,5 @@ /** The files a user message carried, as the lanes its bubble renders: image thumbnails and file chips. */ import type { ChatAttachment } from 'windmill-chat' -import { base } from '$lib/base' import { createAttachedFileContextElement, type ContextElement @@ -24,7 +23,7 @@ function looksLikeImage(attachment: ChatAttachment): boolean { function downloadUrl(workspace: string, attachment: ChatAttachment): string { const params = new URLSearchParams({ file_key: attachment.s3 }) if (attachment.storage) params.set('storage', attachment.storage) - return `${base}/api/w/${workspace}/job_helpers/download_s3_file?${params.toString()}` + return `/api/w/${workspace}/job_helpers/download_s3_file?${params.toString()}` } /** Without a workspace there is no link to build, so an image falls back to a file chip. */ diff --git a/frontend/src/lib/components/flows/earlyReturnCandidates.test.ts b/frontend/src/lib/components/flows/earlyReturnCandidates.test.ts new file mode 100644 index 0000000000..598d6fcd9b --- /dev/null +++ b/frontend/src/lib/components/flows/earlyReturnCandidates.test.ts @@ -0,0 +1,76 @@ +import { describe, it, expect } from 'vitest' +import type { FlowModule } from '$lib/gen' +import { earlyReturnCandidates } from './earlyReturnCandidates' + +function identity(id: string): FlowModule { + return { id, value: { type: 'identity' } } +} + +describe('earlyReturnCandidates', () => { + it('offers every step reached through branches, but not the steps inside loops', () => { + const modules: FlowModule[] = [ + identity('a'), + { + id: 'b', + value: { + type: 'branchone', + default: [identity('c')], + branches: [ + { + expr: 'true', + modules: [ + identity('d'), + { + id: 'e', + value: { + type: 'branchone', + default: [], + branches: [{ expr: 'true', modules: [identity('f')] }] + } + }, + { + id: 'g', + value: { type: 'branchall', branches: [{ modules: [identity('h')] }] } + }, + { + id: 'i', + value: { + type: 'forloopflow', + iterator: { type: 'javascript', expr: '[]' }, + skip_failures: false, + modules: [identity('j')] + } + } + ] + } + ] + } + }, + { id: 'k', value: { type: 'branchall', branches: [{ modules: [identity('l')] }] } }, + { + id: 'm', + value: { + type: 'forloopflow', + iterator: { type: 'javascript', expr: '[]' }, + skip_failures: false, + modules: [identity('n')] + } + } + ] + + expect(earlyReturnCandidates(modules)).toEqual([ + { id: 'a', deterministic: true }, + { id: 'b', deterministic: true }, + { id: 'c', deterministic: false }, + { id: 'd', deterministic: false }, + { id: 'e', deterministic: false }, + { id: 'f', deterministic: false }, + { id: 'g', deterministic: false }, + { id: 'h', deterministic: false }, + { id: 'i', deterministic: false }, + { id: 'k', deterministic: true }, + { id: 'l', deterministic: true }, + { id: 'm', deterministic: true } + ]) + }) +}) diff --git a/frontend/src/lib/components/flows/earlyReturnCandidates.ts b/frontend/src/lib/components/flows/earlyReturnCandidates.ts new file mode 100644 index 0000000000..0d838c9d2a --- /dev/null +++ b/frontend/src/lib/components/flows/earlyReturnCandidates.ts @@ -0,0 +1,28 @@ +import type { FlowModule } from '$lib/gen' + +export type EarlyReturnCandidate = { + id: string + // False for a step inside a branch to one: it only runs when its branch is taken. + deterministic: boolean +} + +// A loop's inner steps run once per iteration, so only the loop itself is offered. +export function earlyReturnCandidates(modules: FlowModule[]): EarlyReturnCandidate[] { + return withinBranches(modules, true) +} + +function withinBranches(modules: FlowModule[], deterministic: boolean): EarlyReturnCandidate[] { + return modules.flatMap((module) => { + const value = module.value + const nested = + value.type === 'branchone' + ? withinBranches([value.default, ...value.branches.map((b) => b.modules)].flat(), false) + : value.type === 'branchall' + ? withinBranches( + value.branches.flatMap((b) => b.modules), + deterministic + ) + : [] + return [{ id: module.id, deterministic }, ...nested] + }) +} diff --git a/frontend/src/lib/components/flows/flowInfers.ts b/frontend/src/lib/components/flows/flowInfers.ts index f2beefa0de..38a9a02c2d 100644 --- a/frontend/src/lib/components/flows/flowInfers.ts +++ b/frontend/src/lib/components/flows/flowInfers.ts @@ -3,8 +3,8 @@ import { loadSchemaFlow } from '$lib/scripts' import type { Schema } from '$lib/common' import { emptySchema } from '$lib/utils' import type { FlowModule, InputTransform } from '$lib/gen' -import { AGENT_FLOW_LOCAL_KEYS } from './agentResourceUtils' -import { AGENT_HISTORY_KEYS } from './agentFormFields' +import { AGENT_LINKED_STEP_KEYS } from './agentResourceUtils' +import { AGENT_UNSEEDED_KEYS } from './agentFormFields' /** Display names for the memory field's options, so anything else naming the setting an author * picked cannot drift from the button they see. */ @@ -390,20 +390,17 @@ export async function loadSchemaFromModule( } } else if (mod.type === 'aiagent') { let input_transforms = migrateAiAgentInputTransforms(mod.input_transforms ?? {}) - // A linked step's brain lives in the resource, so only the flow-local inputs get a placeholder - // transform: filling the brain keys back in would re-add the very fields linking strips, and - // they would be persisted on the next save. - const keys = mod.agent - ? (AGENT_FLOW_LOCAL_KEYS as readonly string[]) - : Object.keys(AI_AGENT_SCHEMA.properties ?? {}) + // A linked step's brain lives in the resource, so only the inputs it holds itself are kept: + // filling the brain keys back in would re-add the very fields linking strips, and they would + // be persisted on the next save. + const keys = mod.agent ? AGENT_LINKED_STEP_KEYS : Object.keys(AI_AGENT_SCHEMA.properties ?? {}) return { input_transforms: keys.reduce((accu, key) => { const transform = input_transforms[key] ?? - // A present history input is the step's choice at runtime, so it gets no placeholder. - ((AGENT_HISTORY_KEYS as readonly string[]).includes(key) - ? undefined - : { type: 'static', value: undefined }) + // A present history input or override is the step's choice at runtime, so it gets no + // placeholder. + (AGENT_UNSEEDED_KEYS.includes(key) ? undefined : { type: 'static', value: undefined }) if (transform) accu[key] = transform return accu }, {}), diff --git a/frontend/src/lib/components/flows/flowStateUtils.svelte.ts b/frontend/src/lib/components/flows/flowStateUtils.svelte.ts index 9d85a07452..030897a63b 100644 --- a/frontend/src/lib/components/flows/flowStateUtils.svelte.ts +++ b/frontend/src/lib/components/flows/flowStateUtils.svelte.ts @@ -108,7 +108,7 @@ export async function pickFlow( export async function createInlineScriptModule( language: RawScript['language'], kind: Script['kind'], - subkind: 'pgsql' | 'flow' | 'claudesandbox' | undefined, + subkind: 'pgsql' | 'flow' | 'claudesandbox' | 'pisandbox' | undefined, id: string, summary?: string ): Promise<[FlowModule, FlowModuleState]> { diff --git a/frontend/src/lib/components/flows/linkedAgentDrafts.ts b/frontend/src/lib/components/flows/linkedAgentDrafts.ts index 4a9aef24b1..9367b21b12 100644 --- a/frontend/src/lib/components/flows/linkedAgentDrafts.ts +++ b/frontend/src/lib/components/flows/linkedAgentDrafts.ts @@ -3,11 +3,12 @@ import { type FlowModule, type FlowValue, type InputTransform, + type OperatorSettings, type Resource } from '$lib/gen' import { UserDraft } from '$lib/userDraft.svelte' import { UserDraftDbSyncer } from '$lib/userDraftDbSyncer.svelte' -import { canWrite } from '$lib/utils' +import { canEditItem } from '$lib/editRights' import type { UserExt } from '$lib/stores' import { dfs } from './dfs' import { flowLocalInputs, type AIAgentConfig } from './agentResourceUtils' @@ -122,11 +123,15 @@ export interface LinkedAgentDraft { extraPerms: Record<string, boolean> } -/** Whether `user` may write this agent's resource. Split from the load so that resolving the - * drafts of a whole flow costs no `whoami` — only the deploy dialog needs the answer, and it - * looks the user up once for every agent it lists. */ -export function agentDraftCanWrite(draft: LinkedAgentDraft, user: UserExt | undefined): boolean { - return canWrite(draft.path, draft.extraPerms, user) +/** Whether `user` may write this agent's resource, in a workspace with these `operator_settings`. + * Split from the load so that resolving the drafts of a whole flow costs no `whoami` — only the + * deploy dialog needs the answer, and it looks the user up once for every agent it lists. */ +export function agentDraftCanWrite( + draft: LinkedAgentDraft, + user: UserExt | undefined, + operatorSettings: OperatorSettings | undefined +): boolean { + return canEditItem('agent', draft.path, draft.extraPerms, user, operatorSettings) } /** A link that cannot resolve for the user rather than because something went wrong: the agent was diff --git a/frontend/src/lib/components/flows/map/FlowModuleSchemaItemViewer.svelte b/frontend/src/lib/components/flows/map/FlowModuleSchemaItemViewer.svelte index a0ec4759f5..c87e20139e 100644 --- a/frontend/src/lib/components/flows/map/FlowModuleSchemaItemViewer.svelte +++ b/frontend/src/lib/components/flows/map/FlowModuleSchemaItemViewer.svelte @@ -4,6 +4,7 @@ import type { FlowNodeColorClasses } from '$lib/components/graph' import { twMerge } from 'tailwind-merge' import { getContext } from 'svelte' + import { AGENT_STEP_ID } from '../conversations/agentEditorChat' // Detached mode (sessions): a step's editor is hidden until asked for, so add the // hint to the name tooltip. Provided by FlowEditor; absent (=> false) elsewhere. @@ -69,7 +70,8 @@ </Popover> <div class="flex items-center space-x-2 relative" bind:clientWidth={idBadgeWidth}> - {#if id && id !== 'preprocessor' && !id.startsWith('failure') && !id.startsWith('subflow:')} + <!-- A saved agent's run is that one step, already named by the run page. --> + {#if id && id !== 'preprocessor' && id !== AGENT_STEP_ID && !id.startsWith('failure') && !id.startsWith('subflow:')} <Badge color="transparent" class="border-none" diff --git a/frontend/src/lib/components/flows/map/InsertModuleInner.svelte b/frontend/src/lib/components/flows/map/InsertModuleInner.svelte index 9cf4bcd264..62ec111b6c 100644 --- a/frontend/src/lib/components/flows/map/InsertModuleInner.svelte +++ b/frontend/src/lib/components/flows/map/InsertModuleInner.svelte @@ -117,17 +117,21 @@ logReusableAgentUsage('linked') dispatch('new', { kind: 'aiagent', agentPath }) } - function newClaudeSandbox() { + function newAiSandbox(subkind: 'claudesandbox' | 'pisandbox') { dispatch('close') dispatch('new', { kind: 'script', inlineScript: { language: 'bun', kind: 'script', - subkind: 'claudesandbox' + subkind } }) } + const aiSandboxes = [ + { label: 'Claude Code', subkind: 'claudesandbox' }, + { label: 'Pi', subkind: 'pisandbox' } + ] as const // Rows of the AI panes in render order. FlowInputsQuick owns the keyboard index for the other // panes and is unmounted while these render, so the two never fight over Enter or the arrows. @@ -137,7 +141,7 @@ return [newBlankAgent, ...saved.map((a) => () => newLinkedAgent(a.path))] } if (selectedKind === 'aisandbox') { - return [newClaudeSandbox] + return aiSandboxes.map((s) => () => newAiSandbox(s.subkind)) } return [] }) @@ -418,14 +422,16 @@ </div> {:else if selectedKind === 'aisandbox'} <div class="h-full overflow-auto grow min-w-0 p-2 gap-1 flex flex-col"> - <TopLevelNode - label="Claude Code" - neutral - returnIcon - selected={aiSelected === 0} - onSelect={newClaudeSandbox} - onHover={() => (selectedByKeyboard = 0)} - /> + {#each aiSandboxes as sandbox, i (sandbox.subkind)} + <TopLevelNode + label={sandbox.label} + neutral + returnIcon + selected={aiSelected === i} + onSelect={() => newAiSandbox(sandbox.subkind)} + onHover={() => (selectedByKeyboard = i)} + /> + {/each} </div> {:else} <FlowInputsQuick diff --git a/frontend/src/lib/components/flows/pickers/FlowScriptPicker.svelte b/frontend/src/lib/components/flows/pickers/FlowScriptPicker.svelte index 93909d13f3..0ae64f3a69 100644 --- a/frontend/src/lib/components/flows/pickers/FlowScriptPicker.svelte +++ b/frontend/src/lib/components/flows/pickers/FlowScriptPicker.svelte @@ -8,7 +8,7 @@ interface Props { disabled?: boolean label: string - lang?: SupportedLanguage | 'docker' | 'javascript' | 'claudesandbox' | undefined + lang?: SupportedLanguage | 'docker' | 'javascript' | 'claudesandbox' | 'pisandbox' | undefined id?: string | undefined } diff --git a/frontend/src/lib/components/flows/pickers/FlowScriptPickerQuick.svelte b/frontend/src/lib/components/flows/pickers/FlowScriptPickerQuick.svelte index 3ac279556f..673fce2525 100644 --- a/frontend/src/lib/components/flows/pickers/FlowScriptPickerQuick.svelte +++ b/frontend/src/lib/components/flows/pickers/FlowScriptPickerQuick.svelte @@ -7,7 +7,7 @@ interface Props { label: string - lang?: SupportedLanguage | 'docker' | 'javascript' | 'claudesandbox' | undefined + lang?: SupportedLanguage | 'docker' | 'javascript' | 'claudesandbox' | 'pisandbox' | undefined selected?: boolean eeRestricted: boolean enterpriseLangs?: string[] diff --git a/frontend/src/lib/components/flows/pickers/TopLevelNode.svelte b/frontend/src/lib/components/flows/pickers/TopLevelNode.svelte index 0c58f0fc73..a8f3e040c4 100644 --- a/frontend/src/lib/components/flows/pickers/TopLevelNode.svelte +++ b/frontend/src/lib/components/flows/pickers/TopLevelNode.svelte @@ -52,6 +52,7 @@ 'AI Decision': { icon: Scale, iconClass: 'text-ai' }, 'AI Sandbox': { icon: BotIcon, showChevron: true, iconClass: 'text-ai' }, 'Claude Code': { icon: BotIcon, iconClass: 'text-ai' }, + Pi: { icon: BotIcon, iconClass: 'text-ai' }, MCP: { icon: Plug }, 'Web Search': { icon: Globe } } diff --git a/frontend/src/lib/components/flows/propPicker/OutputBadge.svelte b/frontend/src/lib/components/flows/propPicker/OutputBadge.svelte index 507e74ba86..ecc8e07b11 100644 --- a/frontend/src/lib/components/flows/propPicker/OutputBadge.svelte +++ b/frontend/src/lib/components/flows/propPicker/OutputBadge.svelte @@ -1,7 +1,6 @@ <script lang="ts"> import type { Job } from '$lib/gen' import { twMerge } from 'tailwind-merge' - import { base } from '$lib/base' import { ExternalLink } from 'lucide-svelte' import { emptyString } from '$lib/utils' @@ -42,7 +41,7 @@ {#if !emptyString(job.id)} <a target="_blank" - href="{base}/run/{job.id}?workspace={job.workspace_id}" + href="/run/{job.id}?workspace={job.workspace_id}" class="text-right float-right text-gray-300 group-hover:text-gray-400 transition-all duration-200 dark:text-gray-500 dark:group-hover:text-gray-300" title="See run detail in a new tab" > diff --git a/frontend/src/lib/components/flows/propPicker/OutputPickerInner.svelte b/frontend/src/lib/components/flows/propPicker/OutputPickerInner.svelte index aa9b14b762..e63db4e960 100644 --- a/frontend/src/lib/components/flows/propPicker/OutputPickerInner.svelte +++ b/frontend/src/lib/components/flows/propPicker/OutputPickerInner.svelte @@ -28,7 +28,6 @@ import { twMerge } from 'tailwind-merge' import DisplayResultControlBar from '$lib/components/DisplayResultControlBar.svelte' import LogViewer from '$lib/components/LogViewer.svelte' - import { base } from '$lib/base' import { fade } from 'svelte/transition' import type { FlowEditorContext, OutputViewerJob } from '../types' import { NEVER_TESTED_THIS_FAR } from '../models' @@ -564,7 +563,6 @@ <DisplayResultControlBar workspaceId={selectedJob.workspace_id} jobId={selectedJob.id} - {base} result={selectedJob.result} disableTooltips={false} on:open-drawer={() => { @@ -576,7 +574,6 @@ {:else if mock?.enabled && displayResultMock && toolbarLocationMock === 'external'} <DisplayResultControlBar customUi={{ disableDownload: true }} - {base} result={mock.return_value} disableTooltips={false} on:open-drawer={() => { diff --git a/frontend/src/lib/components/flows/staleStepLocks.test.ts b/frontend/src/lib/components/flows/staleStepLocks.test.ts new file mode 100644 index 0000000000..ae12860391 --- /dev/null +++ b/frontend/src/lib/components/flows/staleStepLocks.test.ts @@ -0,0 +1,25 @@ +import { describe, it, expect } from 'vitest' +import { dropStaleStepLocks } from './staleStepLocks' + +const step = (id: string, content: string, lock?: string) => + ({ id, value: { type: 'rawscript', language: 'python3', content, lock } }) as any + +describe('dropStaleStepLocks', () => { + // A rename or duplicate gives the step a new id; its code and lock still match. + it('keeps the lock of a renamed or duplicated step whose code is unchanged', () => { + const base = { modules: [step('a', 'import requests', 'requests==2.0')] } + const value = { + modules: [ + step('a', 'import requests', 'requests==2.0'), + step('a_copy', 'import requests', 'requests==2.0'), + step('a_edited_copy', 'import yaml', 'requests==2.0') + ] + } + dropStaleStepLocks(value as any, base as any) + expect(value.modules.map((m) => m.value.lock)).toEqual([ + 'requests==2.0', + 'requests==2.0', + undefined + ]) + }) +}) diff --git a/frontend/src/lib/components/flows/staleStepLocks.ts b/frontend/src/lib/components/flows/staleStepLocks.ts new file mode 100644 index 0000000000..2b9cacfb72 --- /dev/null +++ b/frontend/src/lib/components/flows/staleStepLocks.ts @@ -0,0 +1,33 @@ +import type { FlowModule, FlowValue } from '$lib/gen' +import { forEachFlowModule } from './dfs' + +/** + * Drops, in place, the lock of every inline step whose code differs from the same step in + * `base`. The worker reuses any non-empty step lock, so a step whose code changed but kept its + * lock runs against the old dependencies. Unchanged steps keep theirs, so a deploy does not + * re-resolve (and possibly upgrade) what nobody touched. A step id `base` lacks (a renamed or + * duplicated step) keeps its lock only when some `base` step has the same code. Without a base + * nothing is dropped: a copied or imported flow carries locks that match its code. + */ +export function dropStaleStepLocks(value: FlowValue, base: FlowValue | undefined): void { + if (!base) return + const allModules = (v: FlowValue) => + [...(v.modules ?? []), v.preprocessor_module, v.failure_module].filter( + (m): m is FlowModule => m != null + ) + const contentOf = (m: FlowModule) => (m.value as { content?: unknown }).content + const baseContentById = new Map<string, unknown>() + const baseContents = new Set<unknown>() + forEachFlowModule(allModules(base), (m) => { + baseContentById.set(m.id, contentOf(m)) + baseContents.add(contentOf(m)) + }) + forEachFlowModule(allModules(value), (m) => { + const step = m.value as { content?: unknown; lock?: unknown } + if (step.lock == undefined) return + const unchanged = baseContentById.has(m.id) + ? baseContentById.get(m.id) === step.content + : baseContents.has(step.content) + if (!unchanged) delete step.lock + }) +} diff --git a/frontend/src/lib/components/flows/utils.svelte.ts b/frontend/src/lib/components/flows/utils.svelte.ts index 3efb4b30f0..3cac53cfe4 100644 --- a/frontend/src/lib/components/flows/utils.svelte.ts +++ b/frontend/src/lib/components/flows/utils.svelte.ts @@ -207,7 +207,8 @@ export async function runFlowPreview( tempScriptRefs?: Record<string, string>, // The session's acting workspace when previewing inside an AI-session flow // editor; falls back to the navigation workspace for full-page previews. - workspace?: string + workspace?: string, + onBehalfOf?: string ) { const ws = workspace ?? get(workspaceStore) ?? '' const value = await withAgentDrafts(flow.value, ws) @@ -219,7 +220,8 @@ export async function runFlowPreview( path: path, tag: flow.tag, restarted_from: restartedFrom, - temp_script_refs: tempScriptRefs + temp_script_refs: tempScriptRefs, + on_behalf_of: onBehalfOf }, memoryId: conversationId }) diff --git a/frontend/src/lib/components/git_sync/GitPushPreview.svelte b/frontend/src/lib/components/git_sync/GitPushPreview.svelte index bed6d741d1..25207b767c 100644 --- a/frontend/src/lib/components/git_sync/GitPushPreview.svelte +++ b/frontend/src/lib/components/git_sync/GitPushPreview.svelte @@ -14,6 +14,7 @@ buttons — the setup dialog puts them in its own footer, the standalone modal i import hubPaths from '$lib/hubPaths.json' import { jobManager } from '$lib/services/JobManager' import type { SyncResponse, SettingsObject } from '$lib/git-sync' + import { apiBaseUrl } from '$lib/apiBaseUrl.svelte' interface Props { gitRepoResourcePath: string @@ -39,7 +40,7 @@ buttons — the setup dialog puts them in its own footer, the standalone modal i let showCliInstructions = $state(false) const cliInstructions = $derived(`# Setup (only needed if local folder not initialized yet) npm install -g windmill-cli -wmill workspace add ${$workspaceStore} ${$workspaceStore} ${window.location.origin} +wmill workspace add ${$workspaceStore} ${$workspaceStore} ${apiBaseUrl()}/ wmill init --workspace ${$workspaceStore} --repository ${gitRepoResourcePath} # Pull workspace content to git repository diff --git a/frontend/src/lib/components/git_sync/GitSyncHomeBadge.svelte b/frontend/src/lib/components/git_sync/GitSyncHomeBadge.svelte index eec5662ceb..342f270801 100644 --- a/frontend/src/lib/components/git_sync/GitSyncHomeBadge.svelte +++ b/frontend/src/lib/components/git_sync/GitSyncHomeBadge.svelte @@ -31,7 +31,6 @@ import BitbucketIcon from '$lib/components/icons/BitbucketIcon.svelte' import AzureIcon from '$lib/components/icons/AzureIcon.svelte' import { superadmin, userStore, workspaceStore } from '$lib/stores' - import { base } from '$lib/base' import { Button, ButtonType } from '$lib/components/common' import Popover from '$lib/components/meltComponents/Popover.svelte' import TimeAgo from '$lib/components/TimeAgo.svelte' @@ -360,7 +359,7 @@ <div class="flex flex-col"> {#each repo.jobs as job (job.id)} <a - href="{base}/run/{job.id}?workspace={$workspaceStore}" + href="/run/{job.id}?workspace={$workspaceStore}" class="flex items-center gap-2 rounded px-1.5 py-1 hover:bg-surface-hover" > {#if job.type === 'QueuedJob'} @@ -389,7 +388,7 @@ </div> {/each} <a - href="{base}/runs?job_kinds=deploymentcallbacks&workspace={$workspaceStore}" + href="/runs?job_kinds=deploymentcallbacks&workspace={$workspaceStore}" class="text-accent hover:underline" > All sync jobs @@ -408,7 +407,7 @@ variant="default" unifiedSize="sm" startIcon={{ icon: Settings }} - href="{base}/workspace_settings?tab=git_sync" + href="/workspace_settings?tab=git_sync" > Git Sync settings </Button> @@ -442,7 +441,7 @@ <Button variant="subtle" unifiedSize="sm" startIcon={{ icon: EyeOff }} onClick={hide}> Hide </Button> - <Button variant="accent" unifiedSize="sm" href="{base}/workspace_settings?tab=git_sync"> + <Button variant="accent" unifiedSize="sm" href="/workspace_settings?tab=git_sync"> Set up Git Sync </Button> </div> diff --git a/frontend/src/lib/components/git_sync/GitSyncSection.svelte b/frontend/src/lib/components/git_sync/GitSyncSection.svelte index 3845706e7a..6906c89fe1 100644 --- a/frontend/src/lib/components/git_sync/GitSyncSection.svelte +++ b/frontend/src/lib/components/git_sync/GitSyncSection.svelte @@ -12,7 +12,6 @@ import type { GitSyncRepository } from './GitSyncContext.svelte' import GitSyncModalManager from './GitSyncModalManager.svelte' import { enterpriseLicense, workspaceStore, userWorkspaces } from '$lib/stores' - import { base } from '$lib/base' import { WorkspaceService } from '$lib/gen' import { sendUserToast } from '$lib/toast' import { apiErrorMessage } from '$lib/utils' @@ -108,7 +107,7 @@ const devPairingHref = $derived.by(() => { const parent = currentWorkspace?.parent_workspace_id if (!parent || !$userWorkspaces?.some((w) => w.id === parent)) return undefined - return `${base}/workspace_settings?workspace=${parent}&tab=dev_workspace` + return `/workspace_settings?workspace=${parent}&tab=dev_workspace` }) const repositories = $derived(gitSyncContext?.repositories ?? []) diff --git a/frontend/src/lib/components/graph/graphBuilder.svelte.ts b/frontend/src/lib/components/graph/graphBuilder.svelte.ts index e5741137d7..98a03f8c0f 100644 --- a/frontend/src/lib/components/graph/graphBuilder.svelte.ts +++ b/frontend/src/lib/components/graph/graphBuilder.svelte.ts @@ -38,7 +38,7 @@ export type InsertKind = export type InlineScript = { language: RawScript['language'] kind: Script['kind'] - subkind: 'pgsql' | 'flow' | 'claudesandbox' + subkind: 'pgsql' | 'flow' | 'claudesandbox' | 'pisandbox' summary?: string instructions?: string } diff --git a/frontend/src/lib/components/graph/renderers/nodes/NodeWrapper.svelte b/frontend/src/lib/components/graph/renderers/nodes/NodeWrapper.svelte index fecf82ee23..6a4d94db1f 100644 --- a/frontend/src/lib/components/graph/renderers/nodes/NodeWrapper.svelte +++ b/frontend/src/lib/components/graph/renderers/nodes/NodeWrapper.svelte @@ -3,6 +3,7 @@ import { Handle, Position } from '@xyflow/svelte' import { twMerge } from 'tailwind-merge' import ContextMenu, { type ContextMenuItem } from '../../../common/contextmenu/ContextMenu.svelte' + import { contextMenuItemsFromMenu } from '../../../common/contextmenu/fromMenuItems' import { getGraphContext } from '../../graphContext' import type { Item } from '$lib/utils' @@ -28,21 +29,7 @@ }: Props = $props() let resolvedContextMenuItems: ContextMenuItem[] | undefined = $derived( - contextMenuItems ?? - menuItems?.flatMap((item) => [ - ...(item.separatorTop - ? [{ id: `${item.displayName}-divider`, label: '', divider: true }] - : []), - { - id: item.displayName, - label: item.displayName, - icon: item.icon, - disabled: item.disabled, - type: item.type, - shortcut: item.shortcut, - onClick: item.action as (() => void) | undefined - } - ]) + contextMenuItems ?? (menuItems && contextMenuItemsFromMenu(menuItems)) ) // NodeWrapper is reused outside the flow graph (e.g. the app decision-tree diff --git a/frontend/src/lib/components/handlerDraft.svelte.ts b/frontend/src/lib/components/handlerDraft.svelte.ts new file mode 100644 index 0000000000..a1422e42ed --- /dev/null +++ b/frontend/src/lib/components/handlerDraft.svelte.ts @@ -0,0 +1,118 @@ +import type { ErrorHandler } from '$lib/gen' +import { WORKSPACE_SLACK_BOT_TOKEN_PATH } from '$lib/consts' +import hubPaths from '$lib/hubPaths.json' + +export type HandlerMode = 'error' | 'recovery' | 'success' +type BuiltinDestination = 'slack' | 'teams' | 'email' + +export type HandlerSlot = { path?: string; args: Record<string, any> } +export type HandlerDraft = { + selected: ErrorHandler + slack: HandlerSlot + teams: HandlerSlot + email: HandlerSlot + custom: HandlerSlot & { kind: 'script' | 'flow' } +} +type StoredHandler = { path?: string; kind: 'script' | 'flow'; args: Record<string, any> } + +const SLACK_BOT_ARG = '$res:' + WORKSPACE_SLACK_BOT_TOKEN_PATH + +// Suffixes rather than full paths, so a handler stored under an older hub id is still recognised. +// Email uses one script for every mode. +const EMAIL_SUFFIX = '/workspace-or-error-handler-email' +const BUILTIN_SUFFIXES: Record<HandlerMode, Record<'slack' | 'teams', string>> = { + error: { + slack: '/workspace-or-schedule-error-handler-slack', + teams: '/workspace-or-schedule-error-handler-teams' + }, + recovery: { + slack: '/schedule-recovery-handler-slack', + teams: '/schedule-recovery-handler-teams' + }, + success: { + slack: '/schedule-success-handler-slack', + teams: '/schedule-success-handler-teams' + } +} + +// The only settings each built-in hub script takes besides the ones the backend injects. +const BUILTIN_KEYS: Record<BuiltinDestination, string[]> = { + slack: ['channel'], + teams: ['channel', 'channel_name'], + email: ['email_recipients'] +} + +export function builtinHubPath(mode: HandlerMode, destination: 'slack' | 'teams'): string { + const key = + `${destination}${mode[0].toUpperCase()}${mode.slice(1)}Handler` as keyof typeof hubPaths + return hubPaths[key] +} + +export function handlerTypeForPath(mode: HandlerMode, path: string | undefined): ErrorHandler { + if (path?.startsWith('hub/')) { + if (path.endsWith(EMAIL_SUFFIX)) return 'email' + for (const [destination, suffix] of Object.entries(BUILTIN_SUFFIXES[mode])) { + if (path.endsWith(suffix)) return destination as BuiltinDestination + } + } + return 'custom' +} + +function emptyDraft(selected: ErrorHandler): HandlerDraft { + return { + selected, + slack: { args: {} }, + teams: { args: {} }, + email: { path: hubPaths.emailErrorHandler, args: {} }, + custom: { kind: 'script', args: {} } + } +} + +function pick(args: Record<string, any>, keys: string[]): Record<string, any> { + return Object.fromEntries(keys.filter((k) => args[k] !== undefined).map((k) => [k, args[k]])) +} + +/** Puts a stored handler into the slot of its destination; every other slot starts empty. */ +export function handlerDraftFromStored( + mode: HandlerMode, + path: string | undefined, + kind: 'script' | 'flow' = 'script', + args: Record<string, any> | null | undefined = {}, + opts: { asCustom?: boolean; emptySelected?: ErrorHandler } = {} +): HandlerDraft { + if (!path) return emptyDraft(opts.emptySelected ?? 'custom') + const destination = opts.asCustom ? 'custom' : handlerTypeForPath(mode, path) + const draft = emptyDraft(destination) + if (destination === 'custom') { + draft.custom = { path, kind, args: { ...(args ?? {}) } } + } else if (destination !== 'instance_alerts') { + draft[destination] = { path, args: pick(args ?? {}, BUILTIN_KEYS[destination]) } + } + return draft +} + +/** What a save stores: the selected destination only. */ +export function handlerDraftToStored(draft: HandlerDraft): StoredHandler { + const none: StoredHandler = { kind: 'script', args: {} } + switch (draft.selected) { + case 'custom': { + const { path, kind, args } = draft.custom + return path ? { path, kind, args: $state.snapshot(args) } : none + } + case 'slack': + case 'teams': + case 'email': { + const { path, args } = draft[draft.selected] + if (!path) return none + const stored = { path, kind: 'script' as const, args: $state.snapshot(args) } + if (draft.selected === 'slack') stored.args.slack = SLACK_BOT_ARG + return stored + } + default: + return none + } +} + +export function cloneHandlerDraft(draft: HandlerDraft): HandlerDraft { + return $state.snapshot(draft) as HandlerDraft +} diff --git a/frontend/src/lib/components/handlerDraft.test.ts b/frontend/src/lib/components/handlerDraft.test.ts new file mode 100644 index 0000000000..ee6ec4a040 --- /dev/null +++ b/frontend/src/lib/components/handlerDraft.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, it } from 'vitest' +import { + handlerDraftFromStored, + handlerDraftToStored, + handlerTypeForPath +} from './handlerDraft.svelte' + +const SLACK_BOT = '$res:f/slack_bot/bot_token' + +describe('handler draft', () => { + it('round-trips every destination unchanged', () => { + const stored = [ + { + path: 'hub/28794/workspace-or-schedule-error-handler-slack', + kind: 'script' as const, + args: { channel: 'alerts', slack: SLACK_BOT } + }, + { + path: 'hub/19742/workspace-or-schedule-error-handler-teams', + kind: 'script' as const, + args: { channel: 'c1', channel_name: 'General' } + }, + { + path: 'hub/19795/workspace-or-error-handler-email', + kind: 'script' as const, + args: { email_recipients: ['ops@example.com'] } + }, + { + path: 'f/handlers/on_error', + kind: 'flow' as const, + args: { slack: '$res:u/me/my_slack', channel: 'own' } + } + ] + for (const s of stored) { + const draft = handlerDraftFromStored('error', s.path, s.kind, s.args) + expect(handlerDraftToStored(draft)).toEqual(s) + } + }) + + it("saves only the selected destination's settings", () => { + const draft = handlerDraftFromStored('error', 'u/me/handler', 'script', { + webhook_url: 'https://hooks.example/custom' + }) + draft.selected = 'email' + draft.email.args.email_recipients = ['ops@example.com'] + expect(handlerDraftToStored(draft)).toEqual({ + path: 'hub/19795/workspace-or-error-handler-email', + kind: 'script', + args: { email_recipients: ['ops@example.com'] } + }) + }) + + it('recognises built-in handlers per mode', () => { + const recoverySlack = 'hub/28791/slack/schedule-recovery-handler-slack' + expect(handlerTypeForPath('recovery', recoverySlack)).toBe('slack') + expect(handlerTypeForPath('error', recoverySlack)).toBe('custom') + }) + + it('stores no handler when the destination has none', () => { + const draft = handlerDraftFromStored('error', undefined) + expect(handlerDraftToStored(draft)).toEqual({ kind: 'script', args: {} }) + draft.selected = 'slack' + expect(handlerDraftToStored(draft)).toEqual({ kind: 'script', args: {} }) + draft.selected = 'instance_alerts' + expect(handlerDraftToStored(draft)).toEqual({ kind: 'script', args: {} }) + }) +}) diff --git a/frontend/src/lib/components/home/CreateActionsMenu.svelte b/frontend/src/lib/components/home/CreateActionsMenu.svelte index 4b9e7f1e9b..2e22b0765c 100644 --- a/frontend/src/lib/components/home/CreateActionsMenu.svelte +++ b/frontend/src/lib/components/home/CreateActionsMenu.svelte @@ -1,5 +1,4 @@ <script lang="ts"> - import { base } from '$lib/base' import { goto } from '$lib/navigation' import { Button } from '$lib/components/common' import Drawer from '$lib/components/common/drawer/Drawer.svelte' @@ -20,19 +19,20 @@ PanelLeftClose } from 'lucide-svelte' import BarsStaggered from '$lib/components/icons/BarsStaggered.svelte' + import DbtIcon from '$lib/components/icons/DbtIcon.svelte' import { PythonIcon, TypeScriptIcon } from '$lib/components/common/languageIcons' import { HOME_SHOW_CREATE_FLOW, HOME_SHOW_CREATE_APP } from '$lib/consts' import { importFlowStore } from '$lib/components/flows/flowStore.svelte' import { importScriptStore } from '$lib/components/scripts/scriptStore.svelte' import { importStore } from '$lib/components/apps/store' import { conditionalMelt, getLocalSetting, storeLocalSetting } from '$lib/utils' - import { useOperatorBuilderFlows } from '$lib/operatorWriteRights' + import { useEditRights } from '$lib/operatorWriteRights' import { createDropdownMenu, melt } from '@melt-ui/svelte' import YAML from 'yaml' import type { Snippet } from 'svelte' import { logFeatureUsage } from '$lib/utils/featureUsage' - const operatorBuilderFlows = useOperatorBuilderFlows() + const editRights = useEditRights() interface Props { /** Replaces the default `New` button, e.g. with an inline text link. */ @@ -55,6 +55,23 @@ label: string icon: typeof PythonIcon onSelect: () => void + badge?: { label: string; class: string } + /** opened in a new tab from a link beside the variant */ + docHref?: string + /** shown in the doc panel while the variant is hovered, instead of its option's */ + doc?: Doc + } + + /** what the doc panel shows */ + type Doc = { + label: string + /** a lucide icon or a brand mark; rendered at 26px through both size APIs */ + icon: any + accent: string + tagline: string + description: string + bullets: string[] + badge?: { label: string; class: string } } /** an importable artifact kind handled by the shared YAML/JSON import drawer */ @@ -87,6 +104,9 @@ const badgeAdvanced = 'bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300' const badgeLegacy = 'bg-amber-100 text-amber-700 dark:bg-amber-900/40 dark:text-amber-300' const badgeAlpha = 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300' + const badgeRecommended = 'bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300' + + const DBT_DOCS = 'https://www.windmill.dev/docs/getting_started/scripts_quickstart/dbt' const allOptions: Option[] = [ { @@ -102,7 +122,7 @@ 'Auto-generated UI from parameters', 'Instant deploy & versioning' ], - onSelect: () => goto(`${base}/scripts/add`) + onSelect: () => goto('/scripts/add') }, ...(HOME_SHOW_CREATE_FLOW ? ([ @@ -119,7 +139,7 @@ 'Branches, loops & error handling', 'Suspend / approval steps' ], - onSelect: () => goto(`${base}/flows/add`), + onSelect: () => goto('/flows/add'), extras: [{ label: 'Import flow', onSelect: () => openImport('flow') }] } ] as Option[]) @@ -135,7 +155,7 @@ description: 'Full control over the UI with React or Svelte and a powerful AI agent. Best for complex apps that need full flexibility.', bullets: ['React or Svelte', 'Full flexibility & control', 'AI-assisted authoring'], - onSelect: () => goto(`${base}/apps_raw/add`), + onSelect: () => goto('/apps_raw/add'), extras: [{ label: 'Import full-code app', onSelect: () => openImport('app-fullcode') }] } ] as Option[]) @@ -153,7 +173,7 @@ 'Reusable as a step in any flow', 'Tools from scripts, flows and MCP' ], - onSelect: () => goto(`${base}/agents/add`) + onSelect: () => goto('/agents/add') }, ...(HOME_SHOW_CREATE_FLOW ? ([ @@ -170,18 +190,18 @@ 'Full control via the SDK', 'Versioned as a regular script' ], - onSelect: () => goto(`${base}/scripts/add?wac=typescript`), + onSelect: () => goto('/scripts/add?wac=typescript'), badge: { label: 'Advanced', class: badgeAdvanced }, variants: [ { label: 'TypeScript', icon: TypeScriptIcon, - onSelect: () => goto(`${base}/scripts/add?wac=typescript`) + onSelect: () => goto('/scripts/add?wac=typescript') }, { label: 'Python', icon: PythonIcon, - onSelect: () => goto(`${base}/scripts/add?wac=python`) + onSelect: () => goto('/scripts/add?wac=python') } ], extras: [{ label: 'Import Workflow-as-Code', onSelect: () => openImport('wac') }] @@ -199,8 +219,35 @@ 'Partitioned & incremental', 'Asset-aware lineage' ], - onSelect: () => goto(`${base}/pipeline`), - badge: { label: 'Alpha', class: badgeAlpha } + onSelect: () => goto('/pipeline'), + badge: { label: 'Alpha', class: badgeAlpha }, + variants: [ + { + label: 'Windmill pipelines', + icon: Workflow, + badge: { label: 'Recommended', class: badgeRecommended }, + onSelect: () => goto('/pipeline') + }, + { + label: 'dbt', + icon: DbtIcon, + docHref: DBT_DOCS, + onSelect: () => goto('/scripts/add?lang=dbt'), + doc: { + label: 'dbt', + icon: DbtIcon, + accent: 'orange', + tagline: 'Run an existing dbt project', + description: + 'A pipeline is Windmill’s own abstraction; an existing dbt project stays a dbt project, and runs here unchanged as its own kind of script, with dbt still owning its models, refs and tests. All it needs is a warehouse configured under Settings → dbt. Its models show up in the asset graph as dbt:// nodes, next to whatever pipelines you do build, so you can adopt pipelines later, or never.', + bullets: [ + 'Your dbt project, unchanged', + 'Needs a warehouse under Settings → dbt', + 'Models appear as dbt:// assets' + ] + } + } + ] } ] as Option[]) : []), @@ -215,7 +262,7 @@ description: 'Assemble an internal UI from 60+ components wired to your scripts and flows. Best for simple apps or apps that need minimal customization.', bullets: ['60+ ready-made components', 'No code required', 'Backed by scripts & flows'], - onSelect: () => goto(`${base}/apps/add`), + onSelect: () => goto('/apps/add'), badge: { label: 'Legacy', class: badgeLegacy }, extras: [{ label: 'Import low-code app', onSelect: () => openImport('app-lowcode') }] } @@ -266,12 +313,11 @@ } } - // A builder composes runnables that already exist, so only flows are offered: everything else - // here writes code, which the backend refuses from an operator. + // Only the kinds this user's role authors: a builder operator gets the kinds its rights grant. // Derived, not computed once: switching workspace only sets `workspaceStore`, it does not // remount this component, so a snapshot would keep the previous workspace's kinds. const options: Option[] = $derived( - $operatorBuilderFlows ? allOptions.filter((o) => o.key === 'flow') : allOptions + allOptions.filter((o) => editRights.roleCanAuthor(o.key === 'app-fullcode' ? 'raw_app' : o.key)) ) // the doc panel only shows while an option is hovered or focused, so the menu opens compact @@ -301,18 +347,25 @@ // per-row fan-out submenus: open to the right when there's room. The popover hugs // the right viewport edge on most screens, so the default flip (right → left) would // cover the doc panel — fall back below the trigger row instead. + const variantSubmenu = () => + builders.createSubmenu({ + positioning: { + placement: 'right-start', + gutter: 4, + flip: { fallbackPlacements: ['bottom-end', 'bottom-start', 'top-end', 'top-start'] }, + fitViewport: true, + overflowPadding: 8 + } + }) const { elements: { subTrigger: wacSubTrigger, subMenu: wacSubMenu }, states: { subOpen: wacSubOpen } - } = builders.createSubmenu({ - positioning: { - placement: 'right-start', - gutter: 4, - flip: { fallbackPlacements: ['bottom-end', 'bottom-start', 'top-end', 'top-start'] }, - fitViewport: true, - overflowPadding: 8 - } - }) + } = variantSubmenu() + const { + elements: { subTrigger: pipelineSubTrigger, subMenu: pipelineSubMenu }, + states: { subOpen: pipelineSubOpen } + } = variantSubmenu() + let variantSubOpen = $derived($wacSubOpen || $pipelineSubOpen) const { elements: { subTrigger: importSubTrigger, subMenu: importSubMenu }, states: { subOpen: importSubOpen } @@ -378,7 +431,10 @@ if (isOpen && !wasOpen) { logFeatureUsage('home', 'new_menu_open', { key: source }) } - if (!isOpen) activeKey = undefined + if (!isOpen) { + activeKey = undefined + activeVariantDoc = undefined + } wasOpen = isOpen }) @@ -389,17 +445,25 @@ // only persist the non-default (hidden) state, so a cleared key means "shown" storeLocalSetting(SHOW_DOC_SETTING, value ? undefined : 'false') } - // The pointer crosses the gutter outside the menu on its way into the Workflow-as-Code - // submenu, so leaving the menu keeps the panel while that submenu is open; it clears - // once the submenu closes with neither pointer nor focus left on the menu. + // The pointer crosses the gutter outside the menu on its way into a variant submenu, + // so leaving the menu keeps the panel while that submenu is open; it clears once the + // submenu closes with neither pointer nor focus left on the menu. let menuEl: HTMLDivElement | undefined = $state(undefined) $effect(() => { - if ($wacSubOpen || !menuEl) return + if (variantSubOpen || !menuEl) return if (!menuEl.matches(':hover') && !menuEl.contains(document.activeElement)) { activeKey = undefined } }) - let active = $derived(options.find((o) => o.key === activeKey)) + // A hovered variant with its own doc (dbt under Data pipelines) takes over the panel. + let activeVariantDoc: Doc | undefined = $state(undefined) + function highlightOption(key: string | undefined) { + activeKey = key + activeVariantDoc = undefined + } + let active: Doc | undefined = $derived( + activeVariantDoc ?? options.find((o) => o.key === activeKey) + ) let activeAc = $derived(active ? accentClasses[active.accent] : undefined) // shared YAML/JSON import drawer, reused by every "Import …" extra @@ -427,17 +491,17 @@ const parsed = importType === 'yaml' ? YAML.parse(importRaw) : JSON.parse(importRaw) if (importKind === 'flow') { importFlowStore.set(parsed) - await goto(`${base}/flows/add`) + await goto('/flows/add') } else if (importKind === 'wac') { importScriptStore.set(parsed) - await goto(`${base}/scripts/add?import=true`) + await goto('/scripts/add?import=true') } else if (importKind === 'app-fullcode') { // The raw app editor reads the payload from sessionStorage on mount. sessionStorage.setItem('rawAppImport', JSON.stringify(parsed)) - await goto(`${base}/apps_raw/add`) + await goto('/apps_raw/add') } else { importStore.set(parsed) - await goto(`${base}/apps/add`) + await goto('/apps/add') } importDrawer?.closeDrawer?.() } @@ -476,7 +540,7 @@ style={showDoc ? 'width: 780px;' : ''} bind:this={menuEl} onpointerleave={() => { - if (!$wacSubOpen) activeKey = undefined + if (!variantSubOpen) highlightOption(undefined) }} > <div @@ -492,7 +556,7 @@ <div class="w-12 h-12 rounded-xl flex items-center justify-center shrink-0 {activeAc.tile}" > - <active.icon size={26} class={activeAc.iconText} /> + <active.icon size={26} width={26} height={26} class={activeAc.iconText} /> </div> <div class="min-w-0"> <div class="flex flex-row items-center gap-2"> @@ -551,48 +615,92 @@ </span> {/if} {/snippet} + {#snippet variantRow( + option: Option, + ac: (typeof accentClasses)[string], + rowClass: string, + subTrigger: any, + subMenu: any, + subOpen: boolean + )} + <button + use:melt={subTrigger} + class={rowClass} + onfocusin={() => highlightOption(option.key)} + onpointerenter={() => highlightOption(option.key)} + > + {@render rowBody(option, ac)} + <ChevronRight size={14} class="shrink-0 text-tertiary" /> + </button> + {#if subOpen} + <!-- The invisible `before:` margin bridges the gutter to the trigger row: when + the submenu falls below its row, that gutter lies over the next row, and + crossing it highlights that item, which closes the submenu. --> + <div + use:melt={subMenu} + use:hugViewportRight + class="pointer-events-auto z-[6001] flex flex-col gap-0.5 p-1 min-w-52 w-max rounded-lg border border-gray-200 dark:border-gray-700 bg-surface shadow-xl focus:outline-none before:absolute before:-inset-2 before:-z-10 before:content-['']" + > + {#each option.variants ?? [] as variant (variant.label)} + {@const VariantIcon = variant.icon} + <div class="flex flex-row items-center gap-1"> + <button + use:melt={$item} + class="flex flex-row flex-1 items-center gap-2.5 rounded-md px-2 py-1.5 text-left cursor-pointer transition-colors focus:outline-none data-[highlighted]:bg-surface-hover hover:bg-surface-hover" + onclick={() => variant.onSelect()} + onfocusin={() => (activeVariantDoc = variant.doc)} + onpointerenter={() => (activeVariantDoc = variant.doc)} + > + <VariantIcon width={14} height={14} size={14} /> + <span class="text-xs font-medium text-primary whitespace-nowrap"> + {variant.label} + </span> + {#if variant.badge} + <span + class="shrink-0 rounded px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide {variant + .badge.class}" + > + {variant.badge.label} + </span> + {/if} + </button> + {#if variant.docHref} + <a + href={variant.docHref} + target="_blank" + rel="noreferrer" + class="px-2 text-[10px] text-tertiary hover:text-secondary hover:underline whitespace-nowrap" + onpointerenter={() => (activeVariantDoc = variant.doc)} + > + See documentation + </a> + {/if} + </div> + {/each} + </div> + {/if} + {/snippet} {#each options as option (option.key)} {@const ac = accentClasses[option.accent]} {@const rowClass = 'w-full flex flex-row items-center gap-2.5 rounded-md px-2 py-1.5 text-left cursor-pointer transition-colors focus:outline-none data-[highlighted]:bg-surface-hover hover:bg-surface-hover'} - {#if option.variants} - <button - use:melt={$wacSubTrigger} - class={rowClass} - onfocusin={() => (activeKey = option.key)} - onpointerenter={() => (activeKey = option.key)} - > - {@render rowBody(option, ac)} - <ChevronRight size={14} class="shrink-0 text-tertiary" /> - </button> - {#if $wacSubOpen} - <!-- The invisible `before:` margin bridges the gutter to the trigger row: when - the submenu falls below its row, that gutter lies over the next row, and - crossing it highlights that item, which closes the submenu. --> - <div - use:melt={$wacSubMenu} - use:hugViewportRight - class="pointer-events-auto z-[6001] flex flex-col gap-0.5 p-1 w-52 rounded-lg border border-gray-200 dark:border-gray-700 bg-surface shadow-xl focus:outline-none before:absolute before:-inset-2 before:-z-10 before:content-['']" - > - {#each option.variants ?? [] as variant (variant.label)} - {@const VariantIcon = variant.icon} - <button - use:melt={$item} - class="flex flex-row items-center gap-2.5 rounded-md px-2 py-1.5 text-left cursor-pointer transition-colors focus:outline-none data-[highlighted]:bg-surface-hover hover:bg-surface-hover" - onclick={() => variant.onSelect()} - > - <VariantIcon width={14} height={14} /> - <span class="text-xs font-medium text-primary">{variant.label}</span> - </button> - {/each} - </div> - {/if} + {#if option.variants && option.key === 'pipeline'} + {@render variantRow( + option, + ac, + rowClass, + $pipelineSubTrigger, + $pipelineSubMenu, + $pipelineSubOpen + )} + {:else if option.variants} + {@render variantRow(option, ac, rowClass, $wacSubTrigger, $wacSubMenu, $wacSubOpen)} {:else} <button use:melt={$item} class={rowClass} - onfocusin={() => (activeKey = option.key)} - onpointerenter={() => (activeKey = option.key)} + onfocusin={() => highlightOption(option.key)} + onpointerenter={() => highlightOption(option.key)} onclick={() => option.onSelect()} > {@render rowBody(option, ac)} @@ -605,8 +713,8 @@ <button use:melt={$importSubTrigger} class="w-full flex flex-row items-center gap-2.5 rounded-md px-2 py-1.5 text-left cursor-pointer transition-colors focus:outline-none data-[highlighted]:bg-surface-hover hover:bg-surface-hover" - onfocusin={() => (activeKey = undefined)} - onpointerenter={() => (activeKey = undefined)} + onfocusin={() => highlightOption(undefined)} + onpointerenter={() => highlightOption(undefined)} > <div class="w-6 h-6 rounded-md flex items-center justify-center shrink-0 bg-gray-100 dark:bg-gray-700" diff --git a/frontend/src/lib/components/home/HomeAIChat.svelte b/frontend/src/lib/components/home/HomeAIChat.svelte index c6f4956f0d..a4e6a1c726 100644 --- a/frontend/src/lib/components/home/HomeAIChat.svelte +++ b/frontend/src/lib/components/home/HomeAIChat.svelte @@ -16,6 +16,24 @@ prompt: 'Generate a weekly sales report from postgres and post it to Slack every Monday' } ] + + /** An operator's session can run what is deployed, read runs and call MCP servers, but + * cannot author scripts or apps. It composes flows only where the workspace grants + * `operator_settings.builder_flows`, so none of these asks it to build anything. */ + export const homeAIOperatorExamples: { label: string; prompt: string }[] = [ + { + label: 'Run a flow', + prompt: 'Find the flow that onboards a new employee and run it for Jane Doe, starting Monday' + }, + { + label: 'Rerun failed jobs', + prompt: 'List the jobs that failed today, tell me why, and rerun the ones that timed out' + }, + { + label: 'Summarize GitHub issues', + prompt: "Read this week's open GitHub issues and summarize the ones that mention billing" + } + ] </script> <script lang="ts"> @@ -32,12 +50,12 @@ import Button from '../common/button/Button.svelte' import { Badge } from '../common' import CloseButton from '../common/CloseButton.svelte' + import { logFeatureUsage } from '$lib/utils/featureUsage' import { startSessionWithPrompt } from '../sessions/sessionSwitch.svelte' import { copilotInfo, copilotWorkspace } from '$lib/aiStore' import { loadCopilot } from '$lib/components/copilot/loadCopilot' import { aiUserDisabled, hubBaseUrlStore, userStore, workspaceStore } from '$lib/stores' import { HOME_SHOW_HUB } from '$lib/consts' - import { base } from '$lib/base' import { getLocalSetting, storeLocalSetting } from '$lib/utils' import { isRuleActive } from '$lib/workspaceProtectionRules.svelte' import { useReducedMotion } from '$lib/svelte5Utils.svelte' @@ -65,17 +83,18 @@ const hubOffered = $derived(!$userStore?.operator && HOME_SHOW_HUB) let value = $state('') - // The stock examples, unless the invite that brought this person here wrote prompts for + // The stock examples for the reader's role, unless the invite that brought this person here wrote prompts for // them — those replace the set outright rather than joining it, since a prompt written // for someone's own stack next to "Ban Discord users" reads as the generic one. - let examples = $state(homeAIExamples) + let invitePrompts: { label: string; prompt: string }[] | undefined = $state(undefined) void onboardingProfile().then((p) => { if (!p?.starter_prompts?.length) return - examples = p.starter_prompts + invitePrompts = p.starter_prompts promptIndex = 0 - placeholder = examples[0].prompt }) - let placeholder = $state(homeAIExamples[0].prompt) + let examples = $derived( + invitePrompts ?? ($userStore?.operator ? homeAIOperatorExamples : homeAIExamples) + ) let placeholderVisible = $state(true) let homeConnectDrawer: HomeConnectDrawer | undefined = $state(undefined) @@ -90,7 +109,9 @@ // Removing puts the composer away rather than throwing it out, and the way back is one item in // the homepage menu — so the ellipsis flashes as it appears, in a corner nobody is watching // while the hero collapses in the middle of the page. - function removeComposer() { + // `no_ai` is the overlay's button, shown only while AI is unusable here. + function removeComposer(source: 'close' | 'no_ai') { + logFeatureUsage('home', 'ai_hero_remove', { key: source }) setCollapsed(true) if (reducedMotion.val) return headerMenu.pulse(1000) @@ -103,7 +124,10 @@ { displayName: 'Pin session hero to homepage', icon: WandSparkles, - action: () => setCollapsed(false) + action: () => { + logFeatureUsage('home', 'ai_hero_pin') + setCollapsed(false) + } } ] : []), @@ -211,7 +235,8 @@ // The index lives outside the effect so re-showing the composer resumes the rotation from the // prompt currently displayed rather than restarting it. const reducedMotion = useReducedMotion() - let promptIndex = 0 + let promptIndex = $state(0) + let placeholder = $derived(prompts[promptIndex % prompts.length]) $effect(() => { if (!showComposer || collapsed || reducedMotion.val) return let timer: ReturnType<typeof setTimeout> @@ -220,7 +245,6 @@ placeholderVisible = false timer = setTimeout(() => { promptIndex = (promptIndex + 1) % prompts.length - placeholder = prompts[promptIndex] placeholderVisible = true timer = setTimeout(next, CYCLE_MS) }, FADE_MS) @@ -242,11 +266,18 @@ <!-- The one dismiss control while the composer is usable; the overlay below carries its own once it takes over, so the two never show at the same time. --> <div class="absolute right-0 top-0 z-20"> - <CloseButton small noBg title="Remove session chat" onClick={removeComposer} /> + <CloseButton + small + noBg + title="Remove session chat" + onClick={() => removeComposer('close')} + /> </div> {/if} <div class="flex items-center justify-center gap-2 mb-4"> - <p class="text-center font-regular text-3xl">Build with AI</p> + <p class="text-center font-regular text-3xl"> + {$userStore?.operator ? 'Run with AI' : 'Build with AI'} + </p> <Badge color="blue" small>Beta</Badge> </div> <!-- Anchors the send button / model settings to the input, not to the whole block — the row @@ -261,7 +292,9 @@ underlyingInputEl="textarea" inputProps={{ rows: 4, - 'aria-label': 'Describe what you want to build', + 'aria-label': $userStore?.operator + ? 'Describe what you want to do' + : 'Describe what you want to build', onkeydown: onKeydown }} /> @@ -324,12 +357,14 @@ unifiedSize="sm" variant="accent" startIcon={{ icon: freeTierExhausted ? KeyRound : Settings }} - href="{base}/workspace_settings?tab=ai" + href="/workspace_settings?tab=ai" > {freeTierExhausted ? 'Add your own API key' : 'Configure AI'} </Button> {/if} - <Button unifiedSize="sm" variant="default" onClick={removeComposer}>Remove</Button> + <Button unifiedSize="sm" variant="default" onClick={() => removeComposer('no_ai')} + >Remove</Button + > </div> </div> {/if} diff --git a/frontend/src/lib/components/home/HomeConnectDrawer.svelte b/frontend/src/lib/components/home/HomeConnectDrawer.svelte index e08ac2ddea..2b86025549 100644 --- a/frontend/src/lib/components/home/HomeConnectDrawer.svelte +++ b/frontend/src/lib/components/home/HomeConnectDrawer.svelte @@ -6,6 +6,7 @@ import { Bot, ExternalLink, Terminal } from 'lucide-svelte' import { shell } from 'svelte-highlight/languages' import { mcpTokenUrlDisabled } from '$lib/mcpAuth' + import { apiBaseUrl } from '$lib/apiBaseUrl.svelte' type ConnectTab = 'cli' | 'mcp' @@ -14,7 +15,7 @@ let selectedTab: ConnectTab = $state('cli') let openVersion = $state(0) - const origin = $derived(typeof window === 'undefined' ? '' : window.location.origin) + const origin = $derived(typeof window === 'undefined' ? '' : `${apiBaseUrl()}/`) const workspaceId = $derived($workspaceStore ?? '<workspace>') const cliCommands = $derived(`npm install -g windmill-cli wmill workspace add ${workspaceId} ${workspaceId} ${origin} @@ -55,7 +56,8 @@ wmill sync pull`) <h3 class="text-sm font-semibold text-emphasis">Local setup</h3> <p class="text-xs text-secondary max-w-xl"> Run this in your local repo to bind the current workspace, create - <code class="rounded bg-surface-secondary px-1 py-0.5 font-mono text-2xs text-emphasis" + <code + class="rounded bg-surface-secondary px-1 py-0.5 font-mono text-2xs text-emphasis" >wmill.yaml</code >, and pull the latest files. </p> @@ -80,15 +82,18 @@ wmill sync pull`) /> <p class="text-2xs text-secondary"> - <code class="rounded bg-surface-secondary px-1 py-0.5 font-mono text-2xs text-emphasis" + <code + class="rounded bg-surface-secondary px-1 py-0.5 font-mono text-2xs text-emphasis" >wmill workspace add</code > will handle authentication, - <code class="rounded bg-surface-secondary px-1 py-0.5 font-mono text-2xs text-emphasis" + <code + class="rounded bg-surface-secondary px-1 py-0.5 font-mono text-2xs text-emphasis" >wmill init</code > bootstraps the local config, and - <code class="rounded bg-surface-secondary px-1 py-0.5 font-mono text-2xs text-emphasis" + <code + class="rounded bg-surface-secondary px-1 py-0.5 font-mono text-2xs text-emphasis" >wmill sync pull</code > fetches the workspace content. diff --git a/frontend/src/lib/components/home/Item.svelte b/frontend/src/lib/components/home/Item.svelte index a8837d555a..67dac7b3dd 100644 --- a/frontend/src/lib/components/home/Item.svelte +++ b/frontend/src/lib/components/home/Item.svelte @@ -45,10 +45,9 @@ // A raw app the listing returns is an `app` row carrying `raw_app`, and is // selectable like any other app. The separate `raw_app` type is the legacy // listing shape, which renders through RawAppRow — no selection control there, - // so it must not enter the selection either. An agent is a resource underneath, - // which none of the bulk actions handle. + // so it must not enter the selection either. let bulkItem = $derived( - homeSelection?.available && item.type !== 'raw_app' && item.type !== 'agent' + homeSelection?.available && item.type !== 'raw_app' ? toBulkItem(item, $userStore, $workspaceStore) : undefined ) @@ -145,6 +144,7 @@ {depth} bind:menuOpen {keyboardSelected} + {rowSelection} /> {/if} diff --git a/frontend/src/lib/components/home/ItemsList.svelte b/frontend/src/lib/components/home/ItemsList.svelte index e44bcb08aa..7e71cd5a02 100644 --- a/frontend/src/lib/components/home/ItemsList.svelte +++ b/frontend/src/lib/components/home/ItemsList.svelte @@ -10,7 +10,6 @@ type ListableApp, type Script, ScriptService, - ResourceService, type Flow, type ListableRawApp, type ListableResource, @@ -19,7 +18,7 @@ import { resource } from 'runed' import { getDraftItems } from '$lib/workspaceDrafts.svelte' import { disableHubStore, userStore, workspaceStore } from '$lib/stores' - import { useOperatorBuilderFlows } from '$lib/operatorWriteRights' + import { useEditRights } from '$lib/operatorWriteRights' import type uFuzzy from '@leeoniya/ufuzzy' import { ArrowDownUp, @@ -50,7 +49,7 @@ import ToggleButtonGroup from '../common/toggleButton-v2/ToggleButtonGroup.svelte' import ToggleButton from '../common/toggleButton-v2/ToggleButton.svelte' import FlowIcon from './FlowIcon.svelte' - import { canWrite, getLocalSetting, isOwner, storeLocalSetting } from '$lib/utils' + import { getLocalSetting, isOwner, storeLocalSetting } from '$lib/utils' import { sendUserToast } from '$lib/toast' import Drawer from '../common/drawer/Drawer.svelte' import HighlightCode from '../HighlightCode.svelte' @@ -60,12 +59,11 @@ import { effectivePath, type ItemType } from './treeViewUtils' import { tick, untrack } from 'svelte' import { triggerableByAI } from '$lib/actions/triggerableByAI.svelte' - import { NetworkIcon } from 'lucide-svelte' - import { base } from '$lib/base' + import PipelineRow from '../common/table/PipelineRow.svelte' import BulkActionsBar from './BulkActionsBar.svelte' import { HomeSelection, setHomeSelection, toBulkItem } from './homeSelection.svelte' - const operatorBuilderFlows = useOperatorBuilderFlows() + const editRights = useEditRights() interface Props { subtab?: 'flow' | 'script' | 'app' | 'agent' @@ -176,12 +174,7 @@ let itemKind = $derived( (filterValues.val.kind ?? 'all') as 'script' | 'flow' | 'app' | 'agent' | 'all' ) - // Agents are `ai_agent` resources, listed through the resource endpoint: the runnables - // endpoint has no such kind, so it is asked for nothing on the agent view and for every - // kind on the combined one. - let showsRunnables = $derived(itemKind !== 'agent') - let showsAgents = $derived(itemKind === 'all' || itemKind === 'agent') - let runnableKinds = $derived(itemKind === 'all' || itemKind === 'agent' ? undefined : itemKind) + let runnableKinds = $derived(itemKind === 'all' ? undefined : itemKind) let archived = $derived(!!filterValues.val.archived) let includeWithoutMain = $derived((filterValues.val.include_library ?? true) as boolean) let filterUserFolders = $derived(!!filterValues.val.only_user_folders) @@ -319,11 +312,7 @@ let flows: TableFlow[] | undefined = $state() let apps: TableApp[] | undefined = $state() let raw_apps: TableRawApp[] | undefined = $state() - // Starts empty rather than undefined: the runnables page decides when the list renders, - // and agents join it when their own request lands. - let agents: TableAgent[] = $state([]) - let agentOwnerCounts: Record<string, number> = $state({}) - let agentsGen = 0 + let agents: TableAgent[] | undefined = $state() // Monotonic fetch-order counter stamped onto each row as it arrives (see TableItem.ord). let fetchOrd = 0 @@ -354,97 +343,28 @@ } } - function mapRunnable(it: RunnableItem): TableScript | TableFlow | TableApp { + function mapRunnable(it: RunnableItem): TableScript | TableFlow | TableApp | TableAgent { const base = { ...it, canWrite: - canWrite(it.path, (it.extra_perms ?? {}) as any, $userStore) && - (it.type === 'script' || it.workspace_id == $workspaceStore) && - // The builder right covers flows only; a script or an app is still off limits, so - // the row must not offer edit or delete for those. - (!$userStore?.operator || (it.type === 'flow' && $operatorBuilderFlows)) + editRights.canEditItem( + it.type === 'app' && it.raw_app ? 'raw_app' : it.type, + it.path, + (it.extra_perms ?? {}) as any + ) && + (it.type === 'script' || it.workspace_id == $workspaceStore) } // combinedItems reads a script's time from `created_at`; the endpoint's // unified `edited_at` holds exactly that for scripts. if (it.type === 'script') return { ...base, created_at: it.edited_at } as unknown as TableScript + // An agent row reads its resource's description, which the endpoint reports as `summary`. + if (it.type === 'agent') return { ...base, description: it.summary } as unknown as TableAgent return base as unknown as TableFlow | TableApp } - /** - * The workspace's saved agents, as the kind the home page shows them as. Read from the - * resource listing, which the runnables' keyset order knows nothing of, so the order is applied - * here and the rows are stamped before every runnable ordinal: the agents lead as one block and - * a page of runnables keeps the server's order. Leading rather than trailing, or the list's - * first window would never reach them past a page of runnables. - */ - async function loadAgents(): Promise<void> { - const ws = $workspaceStore - const gen = ++agentsGen - if (!ws || !$userStore || !showsAgents || archived) { - agents = [] - agentOwnerCounts = {} - return - } - const rows: ListableResource[] = [] - try { - // Paged even though search and scoping run over the whole set here: the listing caps a - // page, and only the first carries the draft-only rows, so a short page ends it. - const perPage = 1000 - for (let page = 1; ; page++) { - const batch = await ResourceService.listResource({ - workspace: ws, - resourceType: 'ai_agent', - includeDraftOnly: true, - page, - perPage - }) - rows.push(...batch) - if (batch.length < perPage || gen !== agentsGen) break - } - } catch (e: any) { - if (gen !== agentsGen) return - sendUserToast(`Failed to load agents: ${e?.body ?? e?.message ?? e}`, true) - agents = [] - agentOwnerCounts = {} - return - } - if (gen !== agentsGen) return - // Counted before the owner scope: the chips and tree nodes list every owner. - const counts: Record<string, number> = {} - for (const r of rows) { - const owner = effectivePath(r).split('/').slice(0, 2).join('/') - counts[owner] = (counts[owner] ?? 0) + 1 - } - agentOwnerCounts = counts - const scoped = ownerFilter - ? rows.filter((r) => effectivePath(r).startsWith(ownerFilter + '/')) - : rows - const byTime = (r: ListableResource) => new Date(r.edited_at ?? 0).getTime() - const sorted = [...scoped].sort((a, b) => { - switch (sortOrder) { - case 'updated_asc': - return byTime(a) - byTime(b) - case 'name_asc': - return cmp(effectivePath(a), effectivePath(b)) - case 'name_desc': - return cmp(effectivePath(b), effectivePath(a)) - default: - return byTime(b) - byTime(a) - } - }) - agents = sorted.map((r, i) => ({ - ...r, - summary: r.description || undefined, - canWrite: canWrite(r.path, (r.extra_perms ?? {}) as any, $userStore) && !$userStore?.operator, - ord: AGENT_ORD_BASE + i - })) - } - /** Below any ordinal a runnables page stamps (they count up from 0), so agents lead as a block. */ - const AGENT_ORD_BASE = -1_000_000 - // The merged, server-ordered, keyset-paginated source. `reset` reloads from // the first page (order/filter change or workspace switch); otherwise it - // appends the next page. All three kinds arrive interleaved and are split into + // appends the next page. Every kind arrives interleaved and are split into // the existing per-kind arrays so the downstream pipeline is unchanged. async function loadRunnables(reset: boolean): Promise<void> { const ws = $workspaceStore @@ -458,25 +378,6 @@ // arrays (mixing streams) or clobber the pending reset's generation. if (!reset && serverCursor === undefined) return if (scripts === undefined) loading = true - // One load per reset: agents are fetched whole, so a load-more has nothing to append. - const agentsLoad = reset ? loadAgents() : undefined - if (!showsRunnables) { - // Supersedes a page still in flight, which would otherwise land in the agent view. - const gen = ++loadGen - serverCursor = undefined - hasMoreServer = false - // The rows on screen stay until the agents replace them, as a reload keeps them, or the - // view reads as empty in between. - await agentsLoad - if (gen !== loadGen) return - scripts = [] - flows = [] - apps = [] - raw_apps = [] - pipelineMemberFolders = new Set() - loading = false - return - } if (reset) { serverCursor = undefined hasMoreServer = false @@ -519,18 +420,13 @@ // A newer request superseded this one (e.g. order changed mid-flight); drop // this response so a stale page/cursor can't be mixed with the new order. if (gen !== loadGen) return - // Landed together with the agents fetched beside it, or a workspace holding only agents - // reads as empty until they arrive. - if (agentsLoad) { - await agentsLoad - if (gen !== loadGen) return - } serverCursor = res.next_cursor ?? undefined hasMoreServer = !!res.next_cursor const s: TableScript[] = reset ? [] : [...(scripts ?? [])] const f: TableFlow[] = reset ? [] : [...(flows ?? [])] const a: TableApp[] = reset ? [] : [...(apps ?? [])] + const ag: TableAgent[] = reset ? [] : [...(agents ?? [])] const memberFolders = reset ? new Set<string>() : new Set(pipelineMemberFolders) if (reset) fetchOrd = 0 for (const it of res.items ?? []) { @@ -546,11 +442,14 @@ f.push({ ...mapRunnable(it), ord: fetchOrd++ } as TableFlow) } else if (it.type === 'app') { a.push({ ...mapRunnable(it), ord: fetchOrd++ } as TableApp) + } else if (it.type === 'agent') { + ag.push({ ...mapRunnable(it), ord: fetchOrd++ } as TableAgent) } } scripts = s flows = f apps = a + agents = ag raw_apps = [] pipelineMemberFolders = memberFolders loading = false @@ -564,10 +463,13 @@ // skipping ones already present. Lets a search reach matches outside the loaded // browse window without re-fetching the whole list. function mergeRunnables(newItems: RunnableItem[]) { - const have = new Set([...(scripts ?? []), ...(flows ?? []), ...(apps ?? [])].map(itemKey)) + const have = new Set( + [...(scripts ?? []), ...(flows ?? []), ...(apps ?? []), ...(agents ?? [])].map(itemKey) + ) const s = [...(scripts ?? [])] const f = [...(flows ?? [])] const a = [...(apps ?? [])] + const ag = [...(agents ?? [])] const memberFolders = new Set(pipelineMemberFolders) let changed = false for (const it of newItems) { @@ -583,12 +485,14 @@ if (it.type === 'script') s.push(mapped as TableScript) else if (it.type === 'flow') f.push(mapped as TableFlow) else if (it.type === 'app') a.push(mapped as TableApp) + else if (it.type === 'agent') ag.push(mapped as TableAgent) changed = true } if (changed) { scripts = s flows = f apps = a + agents = ag pipelineMemberFolders = memberFolders } } @@ -656,13 +560,6 @@ // Track the prefix as open first — even a no-op call (re-expanding a cached node) // means it's on screen, so later reloads must refresh it. openOwners.add(owner) - // The agent view has no runnables to page in: its rows are the loaded agents, which - // `treeSource` adds itself. Rows an owner held from another kind go with the switch. - if (!showsRunnables) { - treeOwnerItems = treeOwnerItems.filter((x) => !effectivePath(x).startsWith(`${owner}/`)) - ownerLoad[owner] = { hasMore: false, loading: false, loaded: true, gen: treeGen } - return - } const st = ownerLoad[owner] // Only a load for the CURRENT generation blocks a new one. A load left in flight // by a superseded generation (treeGen bumped on a sort/filter reload) has already @@ -835,6 +732,8 @@ // keeping a dead path. `tick` lets the reloaded rows re-register first. const renderedBefore = homeSelection.renderedKeys void ownerCountsRes.refetch() + // Deleting a pipeline removes it from this list, which no item reload covers. + void pipelineFoldersRes.refetch() await reloadItems() await tick() homeSelection.dropVanished(renderedBefore) @@ -1103,7 +1002,6 @@ [() => $workspaceStore, () => archived, () => itemKind, () => includeWithoutMain], async ([ws, showArchived, kind, withoutMain]) => { if (!ws || showArchived) return undefined - if (kind === 'agent') return {} try { const res = await ScriptService.countRunnablesByOwner({ workspace: ws, @@ -1119,16 +1017,7 @@ } } ) - // The runnables endpoint never counts an agent, so the loaded agents are added per owner. - let ownerCounts = $derived.by(() => { - const runnables = ownerCountsRes.current - if (runnables == undefined) return undefined - const counts = { ...runnables } - for (const [owner, n] of Object.entries(agentOwnerCounts)) { - counts[owner] = (counts[owner] ?? 0) + n - } - return counts - }) + let ownerCounts = $derived(ownerCountsRes.current) // The counts decide which owners the tree renders, so drawing it before they land // would show every workspace folder and then prune it away. Hold the skeleton // until the first response instead — it is fetched in parallel with the listing, @@ -1210,7 +1099,10 @@ * whose direct-deploy protection cleared `showEditButtons` — must not be shown them. * Reading archived items is not a write, so it is not gated on this. */ - let canCreateHere = $derived((!$userStore?.operator || $operatorBuilderFlows) && showEditButtons) + // Every author can create a flow or a full-code app, except a builder granted only the other. + let canCreateHere = $derived( + (editRights.roleCanAuthor('flow') || editRights.roleCanAuthor('raw_app')) && showEditButtons + ) // The workspace itself holds nothing — no filter is narrowing the list away. It stays // false until the first load resolves: a skeleton already means "loading", and the @@ -1309,8 +1201,7 @@ const kind = itemKind // Any term/scope change restarts search paging. searchCursor = undefined - // Agents are all loaded, so the client-side search over them is already complete. - if (term === '' || !ws || !$userStore || kind === 'agent') return + if (term === '' || !ws || !$userStore) return const handle = setTimeout(async () => { let res: { items: RunnableItem[]; next_cursor?: string } try { @@ -1366,7 +1257,7 @@ search: term, showArchived: showArchived ? true : undefined, includeWithoutMain: withoutMain ? true : undefined, - kinds: kind !== 'all' && kind !== 'agent' ? kind : undefined, + kinds: kind !== 'all' ? kind : undefined, pathStart: owner ? owner + '/' : undefined, includeDraftOnly: true, perPage: 1000, @@ -1418,7 +1309,7 @@ type: 'raw_app' as 'raw_app', time: new Date(x.edited_at).getTime() })), - ...agents.map((x) => ({ + ...(agents ?? []).map((x) => ({ ...x, type: 'agent' as 'agent', time: new Date(x.edited_at ?? 0).getTime() @@ -1482,12 +1373,10 @@ // injected as a node and its rows come from the on-demand `treeOwnerItems` store, // so the tree never depends on which owners happen to be in the loaded window. // Otherwise (scoped/search/label) the tree just groups the global `items`. - // Agents ride along in lazy mode too: the owner store is fed by the runnables endpoint, - // which never returns one, while the resource listing already holds them all. let treeSource = $derived( treeLazyMode - ? [...treeOwnerItems, ...agents.map((x) => ({ ...x, type: 'agent' as 'agent' }))].filter( - (x) => filterItemsPathsBaseOnUserFilters(x, filterUserFolders, filterUserFoldersType) + ? treeOwnerItems.filter((x) => + filterItemsPathsBaseOnUserFilters(x, filterUserFolders, filterUserFoldersType) ) : items ) @@ -1820,8 +1709,7 @@ homeSelection.active && selectedIndex >= 0 && selectedIndex < displayedItems.length && - displayedItems[selectedIndex].type !== 'raw_app' && - displayedItems[selectedIndex].type !== 'agent' + displayedItems[selectedIndex].type !== 'raw_app' ) { e.preventDefault() homeSelection.toggle( @@ -2042,7 +1930,7 @@ script and flow hub pickers observe. Nor for a builder: a hub project brings scripts and apps along. --> <CreateActionsMenu - onImportHubProject={$disableHubStore || $operatorBuilderFlows + onImportHubProject={$disableHubStore || !editRights.roleCanAuthor('script') ? undefined : () => (hubPickerOpen = true)} /> @@ -2168,13 +2056,7 @@ <div class="border rounded-md bg-surface-tertiary" class:wm-imported={justImported}> {#if filter === ''} {#each [...visiblePipelineFolders].sort() as folder (folder)} - <a - href="{base}/pipeline/{encodeURIComponent(folder)}" - class="w-full inline-flex items-center gap-4 px-4 py-3 border-b last:border-b-0 hover:bg-surface-hover transition-colors text-sm first-of-type:rounded-t-md" - > - <NetworkIcon size={16} class="text-emerald-600 dark:text-emerald-400" /> - <span class="text-xs font-medium text-emphasis truncate">Pipeline · f/{folder}</span> - </a> + <PipelineRow {folder} onDeleted={reloadItemsAndCounts} /> {/each} {/if} {#each displayedItems as item, i (item.type + '/' + item.path + (item.hash ? '/' + item.hash : ''))} diff --git a/frontend/src/lib/components/home/TreeView.svelte b/frontend/src/lib/components/home/TreeView.svelte index 4c6f3e8ae6..806787cb76 100644 --- a/frontend/src/lib/components/home/TreeView.svelte +++ b/frontend/src/lib/components/home/TreeView.svelte @@ -1,14 +1,14 @@ <script lang="ts"> import TreeView from './TreeView.svelte' - import { onDestroy, untrack, type Snippet } from 'svelte' + import { createEventDispatcher, onDestroy, untrack, type Snippet } from 'svelte' import ResizeTransitionWrapper from '$lib/components/common/ResizeTransitionWrapper.svelte' - import { ChevronDown, ChevronUp, Folder, FolderTree, NetworkIcon, User } from 'lucide-svelte' + import { ChevronDown, ChevronUp, Folder, FolderTree, User } from 'lucide-svelte' + import PipelineRow from '../common/table/PipelineRow.svelte' import Item from './Item.svelte' import { countLeaves, type FolderItem, type ItemType, type UserItem } from './treeViewUtils' import { twMerge } from 'tailwind-merge' import { pluralize } from '$lib/utils' - import { base } from '$lib/base' import { Button } from '$lib/components/common' interface Props { @@ -74,6 +74,8 @@ let visualDepth = $derived(depth + indent) + const dispatch = createEventDispatcher<{ reload: void }>() + // Bounds the request burst from "expand all": however many root owners the tree // renders (its slice grows as you scroll), it fetches at most this many. Lazy owners // past the cap stay collapsed and load on a single click (see the effect). @@ -316,17 +318,12 @@ {#if opened || isSearching} <div> {#if hasPipeline && isFolder(item)} - <!-- py-3 matches common/table/Row.svelte so this row sits at - the same height as the script/flow/app rows that follow - it under the same folder; py-2 was visibly shorter. --> - <a - href="{base}/pipeline/{encodeURIComponent(item.folderName)}" - class="flex items-center gap-4 px-4 py-3 border-b text-sm hover:bg-surface-hover transition-colors" - style="padding-left: {(visualDepth + 1) * 16}px;" - > - <NetworkIcon size={16} class="text-emerald-600 dark:text-emerald-400" /> - <span class="text-xs font-medium text-emphasis">Pipeline</span> - </a> + <PipelineRow + folder={item.folderName} + depth={visualDepth + 1} + label="Pipeline" + onDeleted={() => dispatch('reload')} + /> {/if} {#each item.items.slice(0, effectiveMax) as subItem, index ((subItem['path'] ? subItem['type'] + '__' + subItem['path'] + '__' + index : undefined) ?? 'folder__' + subItem['folderName'] + '__' + index)} <TreeView diff --git a/frontend/src/lib/components/home/WorkspaceEmptyState.svelte b/frontend/src/lib/components/home/WorkspaceEmptyState.svelte index 1f7bebb1ce..6e828eee34 100644 --- a/frontend/src/lib/components/home/WorkspaceEmptyState.svelte +++ b/frontend/src/lib/components/home/WorkspaceEmptyState.svelte @@ -4,11 +4,11 @@ import Popover from '$lib/components/meltComponents/Popover.svelte' import type { HubProjectPick } from '$lib/hubProject' import { disableHubStore } from '$lib/stores' - import { useOperatorBuilderFlows } from '$lib/operatorWriteRights' + import { useOperatorBuilderRights } from '$lib/operatorWriteRights' import CreateActionsMenu from './CreateActionsMenu.svelte' import HubTemplatePicker from './HubTemplatePicker.svelte' - const operatorBuilderFlows = useOperatorBuilderFlows() + const operatorBuilderRights = useOperatorBuilderRights() interface Props { /** A project was chosen here. The list owns the import dialog, and opens it on this. */ @@ -39,7 +39,7 @@ const rowOpacities = [1, 0.7, 0.4] // A builder gets no hub template: a hub project brings scripts and apps along. - const showHub = $derived(!$disableHubStore && !$operatorBuilderFlows) + const showHub = $derived(!$disableHubStore && !$operatorBuilderRights) // The inline "create a new one" link is the anchor for the very same New menu the // toolbar button opens, so the menu pops next to the words that promised it. diff --git a/frontend/src/lib/components/home/bulkActions.test.ts b/frontend/src/lib/components/home/bulkActions.test.ts index ccc29d063e..e00d5f5da5 100644 --- a/frontend/src/lib/components/home/bulkActions.test.ts +++ b/frontend/src/lib/components/home/bulkActions.test.ts @@ -57,6 +57,15 @@ describe('blockedReason', () => { expect(blockedReason('unarchive', item({ archived: false }), admin)).toBeDefined() }) + // AgentRow's delete is `disabled: !canWrite`; the server moves no resource draft. + it('gates an agent as its row does, and keeps a draft-only one in place', () => { + const agent = item({ kind: 'agent', owner: false }) + expect(blockedReason('delete', agent, member)).toBeUndefined() + expect(blockedReason('delete', { ...agent, canWrite: false }, member)).toBeDefined() + expect(blockedReason('archive', agent, admin)).toBeDefined() + expect(blockedReason('move', item({ kind: 'agent', draftOnly: true }), admin)).toBeDefined() + }) + it('lets a draft-only row move or discard, never archive/delete', () => { const draftOnly = item({ draftOnly: true, isDraft: true }) expect(blockedReason('discard', draftOnly, admin)).toBeUndefined() diff --git a/frontend/src/lib/components/home/bulkActions.ts b/frontend/src/lib/components/home/bulkActions.ts index 2345311459..20a65ec596 100644 --- a/frontend/src/lib/components/home/bulkActions.ts +++ b/frontend/src/lib/components/home/bulkActions.ts @@ -8,18 +8,19 @@ * addresses the deployed row. A draft-only item is therefore not deletable — * there is nothing deployed at its path. */ -import { AppService, DraftService, FlowService, ScriptService } from '$lib/gen' +import { AppService, DraftService, FlowService, ResourceService, ScriptService } from '$lib/gen' import type { UserDraftItemKind } from '$lib/gen' import { updateItemPathAndSummary } from '$lib/components/moveRenameManager' import { discardDraft } from '$lib/utils_draft_deploy' import type { BulkItem } from './homeSelection.svelte' -/** The draft overlay is the one place a raw app is its own kind. Narrowed to the - * four kinds `moveDraft` accepts — a `BulkItem` is never anything else, and - * saying so lets the compiler check that rather than trusting it. */ +/** The draft overlay is the one place a raw app is its own kind, and an agent's + * draft is filed as the resource it is. Narrowed so the compiler checks that a + * `BulkItem` never maps to anything else. */ function draftKind( item: BulkItem -): Extract<UserDraftItemKind, 'script' | 'flow' | 'app' | 'raw_app'> { +): Extract<UserDraftItemKind, 'script' | 'flow' | 'app' | 'raw_app' | 'resource'> { + if (item.kind === 'agent') return 'resource' return item.kind === 'app' && item.rawApp ? 'raw_app' : item.kind } @@ -43,6 +44,9 @@ export function blockedReason( switch (action) { case 'move': if (item.archived) return 'archived items cannot be moved' + // The server moves only script, flow and app drafts. + if (item.kind === 'agent' && item.draftOnly) + return 'a draft-only agent is moved by changing its path in the editor' if (!item.owner) return notOwner if (!item.canWrite) return 'you do not have write permission on this path' return undefined @@ -94,9 +98,11 @@ async function moveItem(ctx: BulkContext, item: BulkItem, target: string): Promi if (item.draftOnly) { // Nothing is deployed at this path, so there is no deploy to re-run: the // item IS its draft row, and moving it rewrites that row. + const kind = draftKind(item) + if (kind === 'resource') throw new Error('a draft-only agent cannot be moved here') await DraftService.moveDraft({ workspace: ctx.workspace, - kind: draftKind(item), + kind, path: item.path, requestBody: { new_path: newPath } }) @@ -138,6 +144,8 @@ async function deleteItem(ctx: BulkContext, item: BulkItem): Promise<void> { await ScriptService.deleteScriptByPath({ workspace: ctx.workspace, path: item.path }) } else if (item.kind === 'flow') { await FlowService.deleteFlowByPath({ workspace: ctx.workspace, path: item.path }) + } else if (item.kind === 'agent') { + await ResourceService.deleteResource({ workspace: ctx.workspace, path: item.path }) } else { await AppService.deleteApp({ workspace: ctx.workspace, path: item.path }) } diff --git a/frontend/src/lib/components/home/homeSelection.svelte.ts b/frontend/src/lib/components/home/homeSelection.svelte.ts index 70acdfa0fd..0b4cfcba7a 100644 --- a/frontend/src/lib/components/home/homeSelection.svelte.ts +++ b/frontend/src/lib/components/home/homeSelection.svelte.ts @@ -13,7 +13,7 @@ import type { UserExt } from '$lib/stores' /** A raw app is not a kind of its own here: the listing returns it as an `app` * row carrying `raw_app`, which every action addresses through `BulkItem.rawApp` * (only the draft overlay distinguishes the two). */ -export type BulkKind = 'script' | 'flow' | 'app' +export type BulkKind = 'script' | 'flow' | 'app' | 'agent' /** The flattened row facts every bulk action needs, snapshotted at selection * time so an action still knows what it is acting on after the list reloads. */ diff --git a/frontend/src/lib/components/icons/ExcelIcon.svelte b/frontend/src/lib/components/icons/ExcelIcon.svelte new file mode 100644 index 0000000000..250214c56f --- /dev/null +++ b/frontend/src/lib/components/icons/ExcelIcon.svelte @@ -0,0 +1,76 @@ +<script lang="ts"> + interface Props { + height?: string + width?: string + size?: number + } + + let { height, width, size = 24 }: Props = $props() + let effectiveWidth = $derived(width ?? `${size}px`) + let effectiveHeight = $derived(height ?? `${size}px`) +</script> + +<!-- Microsoft's Excel-Icon-FY26 asset (cdn-dynmedia-1.microsoft.com), paths and gradient stops verbatim. + Microsoft's trademark guidelines forbid altering their brand assets, so the full-colour mark ships unchanged in both themes. --> +<svg + width={effectiveWidth} + height={effectiveHeight} + viewBox="0 0 48 48" + xmlns="http://www.w3.org/2000/svg" + fill="none" +> +<path d="M9 17.5C9 15.0147 11.0147 13 13.5 13H39V39C39 40.6569 37.6569 42 36 42H15C11.6863 42 9 39.3137 9 36V17.5Z" fill="url(#ms-excel-0)"/> +<path d="M9 17.5C9 15.0147 11.0147 13 13.5 13H39V39C39 40.6569 37.6569 42 36 42H15C11.6863 42 9 39.3137 9 36V17.5Z" fill="url(#ms-excel-1)" fill-opacity="0.7"/> +<path d="M9 22.4999C9 20.0147 11.0147 17.9999 13.5 17.9999H27C25.3431 17.9999 24 19.3431 24 20.9999V26.9999C24 28.6568 22.6569 29.9999 21 29.9999H15C11.6863 29.9999 9 32.6862 9 35.9999V22.4999Z" fill="url(#ms-excel-2)"/> +<path d="M9 22.4999C9 20.0147 11.0147 17.9999 13.5 17.9999H27C25.3431 17.9999 24 19.3431 24 20.9999V26.9999C24 28.6568 22.6569 29.9999 21 29.9999H15C11.6863 29.9999 9 32.6862 9 35.9999V22.4999Z" fill="url(#ms-excel-3)" fill-opacity="0.3"/> +<path d="M9 12C9 8.68629 11.6863 6 15 6H27V18H15C11.6863 18 9 20.6863 9 24V12Z" fill="url(#ms-excel-4)"/> +<path d="M9 12C9 8.68629 11.6863 6 15 6H27V18H15C11.6863 18 9 20.6863 9 24V12Z" fill="url(#ms-excel-5)"/> +<path d="M9 12C9 8.68629 11.6863 6 15 6H27V18H15C11.6863 18 9 20.6863 9 24V12Z" fill="url(#ms-excel-6)"/> +<rect width="15" height="12" rx="3" transform="matrix(-1 0 0 1 39 6)" fill="url(#ms-excel-7)"/> +<rect x="4" y="23" width="16" height="16" rx="3.25" fill="url(#ms-excel-8)"/> +<rect x="4" y="23" width="16" height="16" rx="3.25" fill="url(#ms-excel-9)" fill-opacity="0.3"/> +<path d="M16.2056 35.5714H13.7393L12.1907 32.6577C12.1355 32.5557 12.093 32.4749 12.0633 32.4154C12.0378 32.3517 12.0102 32.2794 11.9804 32.1987H11.9549C11.9167 32.3007 11.8806 32.3836 11.8466 32.4473C11.8126 32.5111 11.7722 32.5897 11.7255 32.6832L10.1196 35.5714H7.79352L10.5848 30.9936L7.9847 26.4286H10.4191L11.7956 29.0299C11.8508 29.1362 11.8976 29.2297 11.9358 29.3104C11.9783 29.3869 12.0208 29.4783 12.0633 29.5846H12.0888C12.1482 29.4613 12.195 29.3636 12.229 29.2913C12.2672 29.2191 12.3182 29.1234 12.3819 29.0044L13.8094 26.4286H16.1291L13.4908 30.9235L16.2056 35.5714Z" fill="white"/> +<defs> +<radialGradient id="ms-excel-0" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(39 44.4167) rotate(-133.549) scale(41.1236 31.9082)"> +<stop offset="0.0647233" stop-color="#379539"/> +<stop offset="0.422149" stop-color="#297C2D"/> +<stop offset="0.703448" stop-color="#15561C"/> +</radialGradient> +<radialGradient id="ms-excel-1" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(18.1667 23.4722) rotate(-135.971) scale(16.6611 12.8906)"> +<stop stop-color="#073B10"/> +<stop offset="0.992234" stop-color="#084A13" stop-opacity="0"/> +</radialGradient> +<linearGradient id="ms-excel-2" x1="9" y1="26.9999" x2="22.7848" y2="26.9999" gradientUnits="userSpaceOnUse"> +<stop stop-color="#52D17C"/> +<stop offset="0.328512" stop-color="#4AA647"/> +</linearGradient> +<linearGradient id="ms-excel-3" x1="22.5" y1="17.9999" x2="22.5" y2="30.5027" gradientUnits="userSpaceOnUse"> +<stop stop-color="#29852F"/> +<stop offset="0.499968" stop-color="#4AA647" stop-opacity="0"/> +</linearGradient> +<linearGradient id="ms-excel-4" x1="9.66301" y1="20.5895" x2="26.2944" y2="6.16483" gradientUnits="userSpaceOnUse"> +<stop stop-color="#66D052"/> +<stop offset="1" stop-color="#85E972"/> +</linearGradient> +<radialGradient id="ms-excel-5" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(26.352 13.6634) rotate(-180) scale(9.01883 19.094)"> +<stop offset="0.292495" stop-color="#4EB43B"/> +<stop offset="1" stop-color="#72CC61" stop-opacity="0"/> +</radialGradient> +<linearGradient id="ms-excel-6" x1="17.1147" y1="14.3923" x2="9" y2="14.3923" gradientUnits="userSpaceOnUse"> +<stop offset="0.183694" stop-color="#C0E075" stop-opacity="0"/> +<stop offset="1" stop-color="#D1EB95"/> +</linearGradient> +<radialGradient id="ms-excel-7" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(-1.91094 13.6794) rotate(-38.9697) scale(21.751 21.6904)"> +<stop offset="0.439983" stop-color="#79E96D"/> +<stop offset="1" stop-color="#D0EB76"/> +</radialGradient> +<radialGradient id="ms-excel-8" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(4 23) rotate(45) scale(22.6274 64.4141)"> +<stop stop-color="#20A85E"/> +<stop offset="0.94375" stop-color="#09442A"/> +</radialGradient> +<radialGradient id="ms-excel-9" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(12 32.6) rotate(90) scale(11.2 12.9)"> +<stop offset="0.580357" stop-color="#33A662" stop-opacity="0"/> +<stop offset="0.973806" stop-color="#98F0B0"/> +</radialGradient> +</defs> +</svg> diff --git a/frontend/src/lib/components/icons/OnedriveIcon.svelte b/frontend/src/lib/components/icons/OnedriveIcon.svelte new file mode 100644 index 0000000000..71b5f60cf4 --- /dev/null +++ b/frontend/src/lib/components/icons/OnedriveIcon.svelte @@ -0,0 +1,69 @@ +<script lang="ts"> + interface Props { + height?: string + width?: string + size?: number + } + + let { height, width, size = 24 }: Props = $props() + let effectiveWidth = $derived(width ?? `${size}px`) + let effectiveHeight = $derived(height ?? `${size}px`) +</script> + +<!-- Microsoft's OneDrive-Icon-FY26 asset (cdn-dynmedia-1.microsoft.com), paths and gradient stops verbatim. + Microsoft's trademark guidelines forbid altering their brand assets, so the full-colour mark ships unchanged in both themes. --> +<svg + width={effectiveWidth} + height={effectiveHeight} + viewBox="0 0 48 48" + xmlns="http://www.w3.org/2000/svg" + fill="none" +> +<path d="M14.3386 13.6726C7.73405 13.6728 2.7972 19.0791 2.42554 25.1018C2.65561 26.3995 3.41182 28.9621 4.59605 28.8305C6.07633 28.666 9.80446 28.8305 12.9843 23.0738C15.3072 18.8685 20.0856 13.6725 14.3386 13.6726Z" fill="url(#ms-onedrive-0)"/> +<path d="M12.8114 15.9208C10.5913 19.4358 7.60292 24.4724 6.59433 26.0573C5.39543 27.9413 2.22036 27.1409 2.48339 24.4405C2.45746 24.6597 2.43754 24.8807 2.42381 25.1032C1.98946 32.1289 7.55988 37.9635 14.4916 37.9635C22.1313 37.9635 40.3512 28.4448 38.5073 18.9074C36.5639 13.3012 31.1015 9.28009 24.911 9.28009C18.7205 9.28009 14.753 12.8466 12.8114 15.9208Z" fill="url(#ms-onedrive-1)"/> +<path d="M12.8114 15.9208C10.5913 19.4358 7.60292 24.4724 6.59433 26.0573C5.39543 27.9413 2.22036 27.1409 2.48339 24.4405C2.45746 24.6597 2.43754 24.8807 2.42381 25.1032C1.98946 32.1289 7.55988 37.9635 14.4916 37.9635C22.1313 37.9635 40.3512 28.4448 38.5073 18.9074C36.5639 13.3012 31.1015 9.28009 24.911 9.28009C18.7205 9.28009 14.753 12.8466 12.8114 15.9208Z" fill="url(#ms-onedrive-2)" fill-opacity="0.4"/> +<path d="M12.8114 15.9208C10.5913 19.4358 7.60292 24.4724 6.59433 26.0573C5.39543 27.9413 2.22036 27.1409 2.48339 24.4405C2.45746 24.6597 2.43754 24.8807 2.42381 25.1032C1.98946 32.1289 7.55988 37.9635 14.4916 37.9635C22.1313 37.9635 40.3512 28.4448 38.5073 18.9074C36.5639 13.3012 31.1015 9.28009 24.911 9.28009C18.7205 9.28009 14.753 12.8466 12.8114 15.9208Z" fill="url(#ms-onedrive-3)"/> +<path d="M12.8114 15.9208C10.5913 19.4358 7.60292 24.4724 6.59433 26.0573C5.39543 27.9413 2.22036 27.1409 2.48339 24.4405C2.45746 24.6597 2.43754 24.8807 2.42381 25.1032C1.98946 32.1289 7.55988 37.9635 14.4916 37.9635C22.1313 37.9635 40.3512 28.4448 38.5073 18.9074C36.5639 13.3012 31.1015 9.28009 24.911 9.28009C18.7205 9.28009 14.753 12.8466 12.8114 15.9208Z" fill="url(#ms-onedrive-4)" fill-opacity="0.6"/> +<path d="M12.8114 15.9208C10.5913 19.4358 7.60292 24.4724 6.59433 26.0573C5.39543 27.9413 2.22036 27.1409 2.48339 24.4405C2.45746 24.6597 2.43754 24.8807 2.42381 25.1032C1.98946 32.1289 7.55988 37.9635 14.4916 37.9635C22.1313 37.9635 40.3512 28.4448 38.5073 18.9074C36.5639 13.3012 31.1015 9.28009 24.911 9.28009C18.7205 9.28009 14.753 12.8466 12.8114 15.9208Z" fill="url(#ms-onedrive-5)" fill-opacity="0.9"/> +<path d="M14.38 37.9665C14.38 37.9665 32.6214 38.0024 35.7155 38.0024C41.3306 38.0024 45.5999 33.4181 45.6 28.0688C45.6 22.7194 41.2449 18.1629 35.7155 18.1629C30.1861 18.1629 27.0019 22.2996 24.6102 26.815C21.8077 32.1062 18.2326 37.903 14.38 37.9665Z" fill="url(#ms-onedrive-6)"/> +<path d="M14.38 37.9665C14.38 37.9665 32.6214 38.0024 35.7155 38.0024C41.3306 38.0024 45.5999 33.4181 45.6 28.0688C45.6 22.7194 41.2449 18.1629 35.7155 18.1629C30.1861 18.1629 27.0019 22.2996 24.6102 26.815C21.8077 32.1062 18.2326 37.903 14.38 37.9665Z" fill="url(#ms-onedrive-7)" fill-opacity="0.4"/> +<path d="M14.38 37.9665C14.38 37.9665 32.6214 38.0024 35.7155 38.0024C41.3306 38.0024 45.5999 33.4181 45.6 28.0688C45.6 22.7194 41.2449 18.1629 35.7155 18.1629C30.1861 18.1629 27.0019 22.2996 24.6102 26.815C21.8077 32.1062 18.2326 37.903 14.38 37.9665Z" fill="url(#ms-onedrive-8)" fill-opacity="0.9"/> +<defs> +<radialGradient id="ms-onedrive-0" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(3.24464 15.2511) rotate(50.1526) scale(13.6159 22.5845)"> +<stop stop-color="#4894FE"/> +<stop offset="0.695072" stop-color="#0934B3"/> +</radialGradient> +<radialGradient id="ms-onedrive-1" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(39.7971 -0.425349) rotate(130.923) scale(58.5497 43.3858)"> +<stop offset="0.165327" stop-color="#23C0FE"/> +<stop offset="0.534" stop-color="#1C91FF"/> +</radialGradient> +<radialGradient id="ms-onedrive-2" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(12.0798 16.0264) rotate(-139.986) scale(11.9037 27.2501)"> +<stop stop-color="white"/> +<stop offset="0.660528" stop-color="#ADC0FF" stop-opacity="0"/> +</radialGradient> +<radialGradient id="ms-onedrive-3" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(25.0236 30.0957) rotate(-139.764) scale(13.4172 20.3769)"> +<stop stop-color="#033ACC"/> +<stop offset="1" stop-color="#368EFF" stop-opacity="0"/> +</radialGradient> +<radialGradient id="ms-onedrive-4" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(11.2919 8.37262) rotate(66.5713) scale(29.4404 31.7826)"> +<stop offset="0.592618" stop-color="#3464E3" stop-opacity="0"/> +<stop offset="1" stop-color="#033ACC"/> +</radialGradient> +<radialGradient id="ms-onedrive-5" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(39.3251 2.63231) rotate(135) scale(43.306 67.8459)"> +<stop stop-color="#4BFDE8"/> +<stop offset="0.543937" stop-color="#4BFDE8" stop-opacity="0"/> +</radialGradient> +<linearGradient id="ms-onedrive-6" x1="29.9997" y1="37.9823" x2="29.9997" y2="18.3982" gradientUnits="userSpaceOnUse"> +<stop stop-color="#0086FF"/> +<stop offset="0.49" stop-color="#00BBFF"/> +</linearGradient> +<radialGradient id="ms-onedrive-7" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(19.7659 20.4961) rotate(21.6324) scale(19.6236 37.1605)"> +<stop stop-color="white"/> +<stop offset="0.785262" stop-color="white" stop-opacity="0"/> +</radialGradient> +<radialGradient id="ms-onedrive-8" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(44.9897 16.6252) rotate(139.243) scale(26.9034 26.9946)"> +<stop stop-color="#4BFDE8"/> +<stop offset="0.584724" stop-color="#4BFDE8" stop-opacity="0"/> +</radialGradient> +</defs> +</svg> diff --git a/frontend/src/lib/components/icons/OutlookIcon.svelte b/frontend/src/lib/components/icons/OutlookIcon.svelte new file mode 100644 index 0000000000..a9cec0cfa6 --- /dev/null +++ b/frontend/src/lib/components/icons/OutlookIcon.svelte @@ -0,0 +1,94 @@ +<script lang="ts"> + interface Props { + height?: string + width?: string + size?: number + } + + let { height, width, size = 24 }: Props = $props() + let effectiveWidth = $derived(width ?? `${size}px`) + let effectiveHeight = $derived(height ?? `${size}px`) +</script> + +<!-- Microsoft's Outlook-Icon-FY26 asset (cdn-dynmedia-1.microsoft.com, served on microsoft.com/microsoft-365/outlook), paths and gradient stops verbatim. + Microsoft's trademark guidelines forbid altering their brand assets, so the full-colour mark ships unchanged in both themes. --> +<svg + width={effectiveWidth} + height={effectiveHeight} + viewBox="0 0 48 48" + xmlns="http://www.w3.org/2000/svg" + fill="none" +> +<path d="M30.9322 9.34307L7.97588 23.8943L6.00165 20.7797V18.0959C6.00165 17.1188 6.49634 16.2081 7.31603 15.6762L20.6606 7.01716C22.6937 5.69792 25.3125 5.69771 27.3458 7.01665L30.9322 9.34307Z" fill="url(#ms-outlook-0)"/> +<path d="M27.1402 6.88928C27.2092 6.93033 27.2777 6.97284 27.3455 7.01682L37.76 13.7724L11.9375 30.1404L7.97498 23.8891L26.9262 11.8533C28.7213 10.7133 28.7999 8.14871 27.1402 6.88928Z" fill="url(#ms-outlook-1)"/> +<path d="M27.1402 6.88928C27.2092 6.93033 27.2777 6.97284 27.3455 7.01682L37.76 13.7724L11.9375 30.1404L7.97498 23.8891L26.9262 11.8533C28.7213 10.7133 28.7999 8.14871 27.1402 6.88928Z" fill="url(#ms-outlook-2)" fill-opacity="0.2"/> +<path d="M22.2402 33.2659L11.9377 30.1406L33.842 16.2557C35.6868 15.0864 35.682 12.3932 33.8331 11.2304L33.7344 11.1684L34.0185 11.3451L40.685 15.6695C41.5049 16.2014 41.9998 17.1122 41.9998 18.0895V20.687L22.2402 33.2659Z" fill="url(#ms-outlook-3)"/> +<path d="M22.2402 33.2659L11.9377 30.1406L33.842 16.2557C35.6868 15.0864 35.682 12.3932 33.8331 11.2304L33.7344 11.1684L34.0185 11.3451L40.685 15.6695C41.5049 16.2014 41.9998 17.1122 41.9998 18.0895V20.687L22.2402 33.2659Z" fill="url(#ms-outlook-4)" fill-opacity="0.2"/> +<path d="M27.3458 7.01665C25.3125 5.69771 22.6937 5.69792 20.6605 7.01716L7.31603 15.6762C6.49634 16.2081 6.00165 17.1188 6.00165 18.0959V18.2272C6.03382 19.208 6.55002 20.1121 7.38373 20.6378L23.9764 31.0985L40.6108 20.6537C41.4747 20.1112 41.999 19.1628 41.999 18.1427V20.6873L41.9994 18.0896C41.9994 17.1123 41.5045 16.2015 40.6846 15.6696L27.3458 7.01665Z" fill="url(#ms-outlook-5)"/> +<path d="M21.0513 42.0035H35.748C39.1998 42.0035 41.998 39.2053 41.998 35.7535L41.998 18.1426C41.998 19.1627 41.4736 20.1111 40.6098 20.6536L18.7495 34.3798C17.5703 35.1202 16.8546 36.4149 16.8547 37.8073C16.8549 40.1248 18.7337 42.0035 21.0513 42.0035Z" fill="url(#ms-outlook-6)"/> +<path d="M21.0513 42.0035H35.748C39.1998 42.0035 41.998 39.2053 41.998 35.7535L41.998 18.1426C41.998 19.1627 41.4736 20.1111 40.6098 20.6536L18.7495 34.3798C17.5703 35.1202 16.8546 36.4149 16.8547 37.8073C16.8549 40.1248 18.7337 42.0035 21.0513 42.0035Z" fill="url(#ms-outlook-7)" fill-opacity="0.4"/> +<path d="M21.0513 42.0035H35.748C39.1998 42.0035 41.998 39.2053 41.998 35.7535L41.998 18.1426C41.998 19.1627 41.4736 20.1111 40.6098 20.6536L18.7495 34.3798C17.5703 35.1202 16.8546 36.4149 16.8547 37.8073C16.8549 40.1248 18.7337 42.0035 21.0513 42.0035Z" fill="url(#ms-outlook-8)" fill-opacity="0.5"/> +<path d="M27.0268 42.0023H12.2492C8.79745 42.0023 5.99923 39.2041 5.99923 35.7523V18.1297C5.99923 19.1478 6.52165 20.0948 7.38292 20.6377L29.2215 34.4058C30.4171 35.1595 31.1423 36.4741 31.1421 37.8874C31.1419 40.1601 29.2995 42.0023 27.0268 42.0023Z" fill="url(#ms-outlook-9)"/> +<path d="M27.0268 42.0023H12.2492C8.79745 42.0023 5.99923 39.2041 5.99923 35.7523V18.1297C5.99923 19.1478 6.52165 20.0948 7.38292 20.6377L29.2215 34.4058C30.4171 35.1595 31.1423 36.4741 31.1421 37.8874C31.1419 40.1601 29.2995 42.0023 27.0268 42.0023Z" fill="url(#ms-outlook-10)"/> +<rect x="4" y="23" width="16" height="16" rx="3.25" fill="url(#ms-outlook-11)"/> +<rect x="4" y="23" width="16" height="16" rx="3.25" fill="url(#ms-outlook-12)" fill-opacity="0.5"/> +<path d="M11.959 35.5999C10.636 35.5999 9.54994 35.186 8.70069 34.3583C7.85144 33.5306 7.42682 32.4505 7.42682 31.1179C7.42682 29.7107 7.85785 28.5726 8.7199 27.7035C9.58195 26.8345 10.7107 26.3999 12.1062 26.3999C13.4249 26.3999 14.4982 26.8158 15.3261 27.6477C16.1583 28.4795 16.5744 29.5762 16.5744 30.9378C16.5744 32.3367 16.1433 33.4644 15.2813 34.3211C14.4235 35.1736 13.3161 35.5999 11.959 35.5999ZM11.9974 33.8431C12.7186 33.8431 13.299 33.5968 13.7386 33.1044C14.1781 32.6119 14.3979 31.9269 14.3979 31.0496C14.3979 30.1349 14.1845 29.4231 13.7578 28.9141C13.331 28.405 12.7613 28.1505 12.0486 28.1505C11.3146 28.1505 10.7235 28.4133 10.2754 28.9389C9.82733 29.4604 9.60328 30.1515 9.60328 31.0123C9.60328 31.8856 9.82733 32.5767 10.2754 33.0857C10.7235 33.5906 11.2975 33.8431 11.9974 33.8431Z" fill="white"/> +<path d="M11.9554 35.7233C10.6375 35.7233 9.55551 35.2982 8.7095 34.448C7.8635 33.5977 7.44049 32.4881 7.44049 31.1192C7.44049 29.6737 7.86987 28.5046 8.72864 27.6119C9.5874 26.7191 10.7119 26.2727 12.102 26.2727C13.4157 26.2727 14.4849 26.7 15.3097 27.5545C16.1387 28.409 16.5532 29.5356 16.5532 30.9343C16.5532 32.3712 16.1238 33.5297 15.265 34.4097C14.4105 35.2855 13.3073 35.7233 11.9554 35.7233ZM11.9936 33.9187C12.7121 33.9187 13.2903 33.6657 13.7282 33.1598C14.1661 32.6539 14.385 31.9503 14.385 31.049C14.385 30.1095 14.1724 29.3783 13.7473 28.8554C13.3222 28.3325 12.7546 28.071 12.0447 28.071C11.3134 28.071 10.7246 28.341 10.2782 28.8809C9.83185 29.4165 9.60865 30.1265 9.60865 31.0108C9.60865 31.9078 9.83185 32.6178 10.2782 33.1407C10.7246 33.6593 11.2964 33.9187 11.9936 33.9187Z" fill="white"/> +<defs> +<linearGradient id="ms-outlook-0" x1="9.98908" y1="22.3649" x2="30.9322" y2="9.37495" gradientUnits="userSpaceOnUse"> +<stop stop-color="#20A7FA"/> +<stop offset="0.4" stop-color="#3BD5FF"/> +<stop offset="1" stop-color="#C4B0FF"/> +</linearGradient> +<linearGradient id="ms-outlook-1" x1="17.1972" y1="26.7945" x2="28.8562" y2="8.12575" gradientUnits="userSpaceOnUse"> +<stop stop-color="#165AD9"/> +<stop offset="0.5008" stop-color="#1880E5"/> +<stop offset="1" stop-color="#8587FF"/> +</linearGradient> +<linearGradient id="ms-outlook-2" x1="25.7005" y1="27.0484" x2="12.7563" y2="16.5013" gradientUnits="userSpaceOnUse"> +<stop offset="0.236946" stop-color="#448AFF" stop-opacity="0"/> +<stop offset="0.792113" stop-color="#0032B1"/> +</linearGradient> +<linearGradient id="ms-outlook-3" x1="24.0534" y1="31.1099" x2="44.51" y2="18.0177" gradientUnits="userSpaceOnUse"> +<stop stop-color="#1A43A6"/> +<stop offset="0.492267" stop-color="#2052CB"/> +<stop offset="1" stop-color="#5F20CB"/> +</linearGradient> +<linearGradient id="ms-outlook-4" x1="29.8281" y1="30.3273" x2="17.3975" y2="19.5708" gradientUnits="userSpaceOnUse"> +<stop stop-color="#0045B9" stop-opacity="0"/> +<stop offset="0.669859" stop-color="#0D1F69"/> +</linearGradient> +<radialGradient id="ms-outlook-5" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(24.0018 6.81788) rotate(-90) scale(27.0027 29.2262)"> +<stop offset="0.568182" stop-color="#275FF0" stop-opacity="0"/> +<stop offset="0.992424" stop-color="#002177"/> +</radialGradient> +<linearGradient id="ms-outlook-6" x1="41.998" y1="29.9431" x2="23.8517" y2="29.9431" gradientUnits="userSpaceOnUse"> +<stop stop-color="#4DC4FF"/> +<stop offset="0.196145" stop-color="#0FAFFF"/> +</linearGradient> +<radialGradient id="ms-outlook-7" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(28.0928 37.9117) rotate(-45) scale(11.572)"> +<stop offset="0.259477" stop-color="#0060D1"/> +<stop offset="0.908166" stop-color="#0383F1" stop-opacity="0"/> +</radialGradient> +<radialGradient id="ms-outlook-8" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(10.6314 46.472) rotate(-52.6577) scale(39.2814 35.5204)"> +<stop offset="0.732317" stop-color="#F4A7F7" stop-opacity="0"/> +<stop offset="1" stop-color="#F4A7F7"/> +</radialGradient> +<radialGradient id="ms-outlook-9" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(18.5708 27.5319) rotate(123.339) scale(20.7258 53.7859)"> +<stop stop-color="#49DEFF"/> +<stop offset="0.724349" stop-color="#29C3FF"/> +</radialGradient> +<linearGradient id="ms-outlook-10" x1="3.45756" y1="37.8723" x2="20.9291" y2="37.8597" gradientUnits="userSpaceOnUse"> +<stop offset="0.205882" stop-color="#6CE0FF"/> +<stop offset="0.535" stop-color="#50D5FF" stop-opacity="0"/> +</linearGradient> +<radialGradient id="ms-outlook-11" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(3.94291 23.6154) rotate(46.9242) scale(21.0618)"> +<stop offset="0.038877" stop-color="#0091FF"/> +<stop offset="0.919119" stop-color="#183DAD"/> +</radialGradient> +<radialGradient id="ms-outlook-12" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(12 32.7439) rotate(90) scale(11.2 12.9188)"> +<stop offset="0.557796" stop-color="#0FA5F7" stop-opacity="0"/> +<stop offset="1" stop-color="#74C6FF"/> +</radialGradient> +</defs> +</svg> diff --git a/frontend/src/lib/components/icons/SharepointIcon.svelte b/frontend/src/lib/components/icons/SharepointIcon.svelte new file mode 100644 index 0000000000..26e1a30e72 --- /dev/null +++ b/frontend/src/lib/components/icons/SharepointIcon.svelte @@ -0,0 +1,88 @@ +<script lang="ts"> + interface Props { + height?: string + width?: string + size?: number + } + + let { height, width, size = 24 }: Props = $props() + let effectiveWidth = $derived(width ?? `${size}px`) + let effectiveHeight = $derived(height ?? `${size}px`) +</script> + +<!-- Microsoft's SharePoint-Icon-FY26 asset (cdn-dynmedia-1.microsoft.com), paths and gradient stops verbatim. + Microsoft's trademark guidelines forbid altering their brand assets, so the full-colour mark ships unchanged in both themes. --> +<svg + width={effectiveWidth} + height={effectiveHeight} + viewBox="0 0 48 48" + xmlns="http://www.w3.org/2000/svg" + fill="none" +> +<path d="M19 28C25.6274 28 31 22.6274 31 16C31 9.37258 25.6274 4 19 4C12.3726 4 7 9.37258 7 16C7 22.6274 12.3726 28 19 28Z" fill="url(#ms-sharepoint-0)"/> +<path d="M19 28C25.6274 28 31 22.6274 31 16C31 9.37258 25.6274 4 19 4C12.3726 4 7 9.37258 7 16C7 22.6274 12.3726 28 19 28Z" fill="url(#ms-sharepoint-1)" fill-opacity="0.2"/> +<path d="M19 28C25.6274 28 31 22.6274 31 16C31 9.37258 25.6274 4 19 4C12.3726 4 7 9.37258 7 16C7 22.6274 12.3726 28 19 28Z" fill="url(#ms-sharepoint-2)" fill-opacity="0.31"/> +<path d="M19 28C25.6274 28 31 22.6274 31 16C31 9.37258 25.6274 4 19 4C12.3726 4 7 9.37258 7 16C7 22.6274 12.3726 28 19 28Z" fill="url(#ms-sharepoint-3)" fill-opacity="0.7"/> +<path d="M29.9453 36C35.4682 36 39.9453 31.5228 39.9453 26C39.9453 20.4772 35.4682 16 29.9453 16C24.4225 16 19.9453 20.4772 19.9453 26C19.9453 31.5228 24.4225 36 29.9453 36Z" fill="url(#ms-sharepoint-4)"/> +<path d="M29.9453 36C35.4682 36 39.9453 31.5228 39.9453 26C39.9453 20.4772 35.4682 16 29.9453 16C24.4225 16 19.9453 20.4772 19.9453 26C19.9453 31.5228 24.4225 36 29.9453 36Z" fill="url(#ms-sharepoint-5)" fill-opacity="0.5"/> +<path d="M29.9453 36C35.4682 36 39.9453 31.5228 39.9453 26C39.9453 20.4772 35.4682 16 29.9453 16C24.4225 16 19.9453 20.4772 19.9453 26C19.9453 31.5228 24.4225 36 29.9453 36Z" fill="url(#ms-sharepoint-6)" fill-opacity="0.7"/> +<path d="M20.5 44C25.1944 44 29 40.1944 29 35.5C29 30.8056 25.1944 27 20.5 27C15.8056 27 12 30.8056 12 35.5C12 40.1944 15.8056 44 20.5 44Z" fill="url(#ms-sharepoint-7)"/> +<path d="M20.5 44C25.1944 44 29 40.1944 29 35.5C29 30.8056 25.1944 27 20.5 27C15.8056 27 12 30.8056 12 35.5C12 40.1944 15.8056 44 20.5 44Z" fill="url(#ms-sharepoint-8)" fill-opacity="0.32"/> +<rect x="4" y="23" width="16" height="16" rx="3.25" fill="url(#ms-sharepoint-9)"/> +<rect x="4" y="23" width="16" height="16" rx="3.25" fill="url(#ms-sharepoint-10)" fill-opacity="0.6"/> +<path d="M8.55579 33.6836L10.2892 32.8076C10.4846 33.1901 10.7395 33.4718 11.0539 33.6528C11.3725 33.8338 11.7209 33.9243 12.099 33.9243C12.5196 33.9243 12.8404 33.842 13.0613 33.6775C13.2823 33.5089 13.3927 33.2559 13.3927 32.9187C13.3927 32.6554 13.2865 32.4333 13.0741 32.2524C12.8617 32.0673 12.4857 31.9275 11.9461 31.8329C10.918 31.6519 10.1702 31.3352 9.70289 30.8828C9.2398 30.4304 9.00825 29.8669 9.00825 29.1924C9.00825 28.3534 9.31415 27.683 9.92593 27.1812C10.5377 26.6795 11.3449 26.4286 12.3476 26.4286C13.0231 26.4286 13.6179 26.5623 14.132 26.8296C14.646 27.0969 15.0539 27.4794 15.3555 27.9771L13.6604 28.8223C13.4734 28.5426 13.2716 28.3411 13.055 28.2177C12.8383 28.0902 12.5664 28.0264 12.2392 28.0264C11.8484 28.0264 11.551 28.1087 11.3471 28.2732C11.1474 28.4377 11.0475 28.6516 11.0475 28.9148C11.0475 29.141 11.1431 29.3405 11.3343 29.5132C11.5297 29.6818 11.9206 29.8196 12.5069 29.9266C13.4926 30.1075 14.2275 30.4366 14.7119 30.9136C15.2005 31.3866 15.4447 31.985 15.4447 32.7089C15.4447 33.5891 15.1537 34.2862 14.5717 34.8003C13.9896 35.3144 13.1591 35.5714 12.0799 35.5714C11.2982 35.5714 10.5929 35.4069 9.96417 35.0779C9.33964 34.7448 8.87018 34.28 8.55579 33.6836Z" fill="white"/> +<path d="M8.55322 33.772L10.2878 32.8665C10.4833 33.2618 10.7384 33.5531 11.053 33.7401C11.3718 33.9272 11.7204 34.0207 12.0988 34.0207C12.5197 34.0207 12.8407 33.9357 13.0617 33.7656C13.2828 33.5913 13.3933 33.3299 13.3933 32.9813C13.3933 32.7092 13.287 32.4796 13.0745 32.2925C12.8619 32.1012 12.4857 31.9567 11.9458 31.8589C10.9169 31.6719 10.1687 31.3445 9.70107 30.8769C9.23768 30.4092 9.00599 29.8268 9.00599 29.1296C9.00599 28.2623 9.31208 27.5694 9.92427 27.0507C10.5365 26.532 11.3442 26.2727 12.3475 26.2727C13.0235 26.2727 13.6186 26.4109 14.1331 26.6872C14.6475 26.9635 15.0556 27.3589 15.3574 27.8733L13.6612 28.747C13.4741 28.4579 13.2722 28.2496 13.0554 28.122C12.8385 27.9902 12.5665 27.9243 12.2391 27.9243C11.848 27.9243 11.5504 28.0094 11.3463 28.1794C11.1465 28.3495 11.0466 28.5705 11.0466 28.8426C11.0466 29.0764 11.1423 29.2826 11.3336 29.4612C11.5291 29.6355 11.9203 29.7779 12.5069 29.8884C13.4932 30.0755 14.2287 30.4156 14.7134 30.9088C15.2023 31.3976 15.4467 32.0162 15.4467 32.7644C15.4467 33.6742 15.1555 34.3948 14.5731 34.9262C13.9906 35.4576 13.1595 35.7233 12.0797 35.7233C11.2974 35.7233 10.5917 35.5533 9.96253 35.2132C9.33759 34.8688 8.86782 34.3884 8.55322 33.772Z" fill="white"/> +<defs> +<linearGradient id="ms-sharepoint-0" x1="10" y1="7" x2="26" y2="28" gradientUnits="userSpaceOnUse"> +<stop stop-color="#00E3DF"/> +<stop offset="0.410156" stop-color="#0097A8"/> +<stop offset="1" stop-color="#007791"/> +</linearGradient> +<radialGradient id="ms-sharepoint-1" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(22.6718 31.3198) rotate(-112.448) scale(18.4261 33.1291)"> +<stop offset="0.28573" stop-color="#003B5D"/> +<stop offset="0.612265" stop-color="#004A6C" stop-opacity="0.688298"/> +<stop offset="0.968041" stop-color="#006F94" stop-opacity="0"/> +</radialGradient> +<radialGradient id="ms-sharepoint-2" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(23.0954 26.0253) rotate(-112.063) scale(15.5519 27.9272)"> +<stop offset="0.259744" stop-color="#002A42"/> +<stop offset="0.612265" stop-color="#004261" stop-opacity="0.688298"/> +<stop offset="0.968041" stop-color="#006F94" stop-opacity="0"/> +</radialGradient> +<radialGradient id="ms-sharepoint-3" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(25.8486 5.27069) rotate(124.447) scale(13.0107)"> +<stop stop-color="#78EDFF"/> +<stop offset="1" stop-color="#2CCFCA" stop-opacity="0"/> +</radialGradient> +<linearGradient id="ms-sharepoint-4" x1="22.4453" y1="18.5" x2="35.7786" y2="36" gradientUnits="userSpaceOnUse"> +<stop stop-color="#00E3DF"/> +<stop offset="0.476427" stop-color="#00A2B8"/> +<stop offset="0.945063" stop-color="#00637C"/> +</linearGradient> +<radialGradient id="ms-sharepoint-5" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(24.2161 34.3333) rotate(-70.8012) scale(12.3537 22.2587)"> +<stop stop-color="#003B5D"/> +<stop offset="0.492035" stop-color="#004C6C" stop-opacity="0.72"/> +<stop offset="0.968041" stop-color="#007A86" stop-opacity="0"/> +</radialGradient> +<radialGradient id="ms-sharepoint-6" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(35.6525 17.0589) rotate(124.447) scale(10.8423)"> +<stop stop-color="#78EDFF"/> +<stop offset="1" stop-color="#2CCFCA" stop-opacity="0"/> +</radialGradient> +<linearGradient id="ms-sharepoint-7" x1="14.55" y1="27.85" x2="23.05" y2="44.85" gradientUnits="userSpaceOnUse"> +<stop offset="0.0534989" stop-color="#75FFF6"/> +<stop offset="0.51144" stop-color="#00C7D1"/> +<stop offset="0.96002" stop-color="#0096AD"/> +</linearGradient> +<linearGradient id="ms-sharepoint-8" x1="28.961" y1="44.0008" x2="24.4188" y2="37.6258" gradientUnits="userSpaceOnUse"> +<stop offset="0.259744" stop-color="#0E5A5D"/> +<stop offset="0.535716" stop-color="#126C6B" stop-opacity="0.688298"/> +<stop offset="0.968041" stop-color="#1C948A" stop-opacity="0"/> +</linearGradient> +<radialGradient id="ms-sharepoint-9" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(4 23) rotate(45) scale(22.6274)"> +<stop offset="0.0625" stop-color="#00B6BD"/> +<stop offset="0.890131" stop-color="#00495C"/> +</radialGradient> +<radialGradient id="ms-sharepoint-10" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(12 32.6) rotate(90) scale(11.2 12.75)"> +<stop offset="0.566964" stop-color="#1E8581" stop-opacity="0"/> +<stop offset="0.973806" stop-color="#1ECBE6"/> +</radialGradient> +</defs> +</svg> diff --git a/frontend/src/lib/components/icons/WordIcon.svelte b/frontend/src/lib/components/icons/WordIcon.svelte new file mode 100644 index 0000000000..e72371b1e6 --- /dev/null +++ b/frontend/src/lib/components/icons/WordIcon.svelte @@ -0,0 +1,65 @@ +<script lang="ts"> + interface Props { + height?: string + width?: string + size?: number + } + + let { height, width, size = 24 }: Props = $props() + let effectiveWidth = $derived(width ?? `${size}px`) + let effectiveHeight = $derived(height ?? `${size}px`) +</script> + +<!-- Microsoft's Word-Icon-FY26 asset (cdn-dynmedia-1.microsoft.com), paths and gradient stops verbatim. + Microsoft's trademark guidelines forbid altering their brand assets, so the full-colour mark ships unchanged in both themes. --> +<svg + width={effectiveWidth} + height={effectiveHeight} + viewBox="0 0 48 48" + xmlns="http://www.w3.org/2000/svg" + fill="none" +> +<path d="M9 33.0901L23 16L39 27.1052V38.5C39 40.433 37.433 42 35.5 42H15C11.6863 42 9 39.3137 9 36V33.0901Z" fill="url(#ms-word-0)"/> +<path d="M9 21.0385C9 18.5532 11.0147 16.5385 13.5 16.5385H33.8889L39 14V26.5C39 28.433 37.433 30 35.5 30H15C11.6863 30 9 32.6863 9 36V21.0385Z" fill="url(#ms-word-1)"/> +<path d="M9 21.0385C9 18.5532 11.0147 16.5385 13.5 16.5385H33.8889L39 14V26.5C39 28.433 37.433 30 35.5 30H15C11.6863 30 9 32.6863 9 36V21.0385Z" fill="url(#ms-word-2)" fill-opacity="0.6"/> +<path d="M9 21.0385C9 18.5532 11.0147 16.5385 13.5 16.5385H33.8889L39 14V26.5C39 28.433 37.433 30 35.5 30H15C11.6863 30 9 32.6863 9 36V21.0385Z" fill="url(#ms-word-3)" fill-opacity="0.1"/> +<path d="M9 12C9 8.68629 11.6863 6 15 6H35.5C37.433 6 39 7.567 39 9.5V14.5C39 16.433 37.433 18 35.5 18H15C11.6863 18 9 20.6863 9 24V12Z" fill="url(#ms-word-4)"/> +<path d="M9 12C9 8.68629 11.6863 6 15 6H35.5C37.433 6 39 7.567 39 9.5V14.5C39 16.433 37.433 18 35.5 18H15C11.6863 18 9 20.6863 9 24V12Z" fill="url(#ms-word-5)" fill-opacity="0.8"/> +<rect x="4" y="23" width="16" height="16" rx="3.25" fill="url(#ms-word-6)"/> +<rect x="4" y="23" width="16" height="16" rx="3.25" fill="url(#ms-word-7)" fill-opacity="0.65"/> +<path d="M17.4859 26.4286L15.5167 35.5703L13.1628 35.5714L12.0002 30.0857L10.7832 35.5714H8.40686L6.51451 26.4297H8.45546L9.62308 32.4629L10.7832 26.4297H13.1628L14.3774 32.4629L15.5167 26.4297L17.4859 26.4286Z" fill="white"/> +<defs> +<radialGradient id="ms-word-0" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(38.1254 41.9993) scale(47.5733 20.1494)"> +<stop offset="0.180414" stop-color="#1657F4"/> +<stop offset="0.574542" stop-color="#0036C4"/> +</radialGradient> +<linearGradient id="ms-word-1" x1="9" y1="25" x2="31.9747" y2="25" gradientUnits="userSpaceOnUse"> +<stop stop-color="#66C0FF"/> +<stop offset="0.25606" stop-color="#0094F0"/> +</linearGradient> +<radialGradient id="ms-word-2" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(39 14.7158) rotate(133.546) scale(29.3648 72.3194)"> +<stop offset="0.140259" stop-color="#D471FF"/> +<stop offset="0.830508" stop-color="#509DF5" stop-opacity="0"/> +</radialGradient> +<radialGradient id="ms-word-3" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(34.6111 29.2308) rotate(90) scale(18.6154 101.647)"> +<stop offset="0.283333" stop-color="#4F006F" stop-opacity="0"/> +<stop offset="1" stop-color="#4F006F"/> +</radialGradient> +<linearGradient id="ms-word-4" x1="9" y1="15" x2="38.9918" y2="15.4954" gradientUnits="userSpaceOnUse"> +<stop stop-color="#9DEAFF"/> +<stop offset="0.201276" stop-color="#3BD5FF"/> +</linearGradient> +<radialGradient id="ms-word-5" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(39 6.58563) rotate(166.855) scale(29.4949 70.6435)"> +<stop offset="0.0606583" stop-color="#E4A7FE"/> +<stop offset="0.538869" stop-color="#E4A7FE" stop-opacity="0"/> +</radialGradient> +<radialGradient id="ms-word-6" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(4 23) rotate(45) scale(22.6274)"> +<stop offset="0.0811439" stop-color="#367AF2"/> +<stop offset="0.871875" stop-color="#001A8F"/> +</radialGradient> +<radialGradient id="ms-word-7" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(12 32.6) rotate(90) scale(11.2 12.765)"> +<stop offset="0.586954" stop-color="#2763E5" stop-opacity="0"/> +<stop offset="0.973806" stop-color="#58AAFE"/> +</radialGradient> +</defs> +</svg> diff --git a/frontend/src/lib/components/icons/index.ts b/frontend/src/lib/components/icons/index.ts index bbefc16469..c8f4cd8f38 100644 --- a/frontend/src/lib/components/icons/index.ts +++ b/frontend/src/lib/components/icons/index.ts @@ -3,6 +3,10 @@ import DbIcon from './DbIcon.svelte' import DiscordIcon from './DiscordIcon.svelte' import GcalIcon from './GcalIcon.svelte' import GdriveIcon from './GdriveIcon.svelte' +import OnedriveIcon from './OnedriveIcon.svelte' +import SharepointIcon from './SharepointIcon.svelte' +import ExcelIcon from './ExcelIcon.svelte' +import WordIcon from './WordIcon.svelte' import GithubIcon from './GithubIcon.svelte' import GitlabIcon from './GitlabIcon.svelte' import GmailIcon from './GmailIcon.svelte' @@ -90,6 +94,7 @@ import ResendIcon from './ResendIcon.svelte' import PushoverIcon from './PushoverIcon.svelte' import QuickbooksIcon from './QuickbooksIcon.svelte' import MsTeamsIcon from './MSTeamsIcon.svelte' +import OutlookIcon from './OutlookIcon.svelte' import MailgunIcon from './MailgunIcon.svelte' import IpinfoIcon from './IpinfoIcon.svelte' import GoogleCloudIcon from './GoogleCloudIcon.svelte' @@ -360,6 +365,10 @@ export const APP_TO_ICON_COMPONENT = { gcloud: GoogleCloudIcon, gcal: GcalIcon, gdrive: GdriveIcon, + ms_onedrive: OnedriveIcon, + ms_sharepoint: SharepointIcon, + ms_excel: ExcelIcon, + ms_word: WordIcon, airtable: AirtableIcon, toggl: TogglIcon, s3: S3Icon, @@ -443,8 +452,10 @@ export const APP_TO_ICON_COMPONENT = { resend: ResendIcon, pushover: PushoverIcon, quickbooks: QuickbooksIcon, + ms_teams: MsTeamsIcon, ms_teams_webhook: MsTeamsIcon, teams: MsTeamsIcon, + ms_outlook: OutlookIcon, mailgun: MailgunIcon, ipinfo: IpinfoIcon, gworkspace: GoogleIcon, @@ -692,6 +703,10 @@ export { DiscordIcon, GcalIcon, GdriveIcon, + OnedriveIcon, + SharepointIcon, + ExcelIcon, + WordIcon, GithubIcon, GitlabIcon, GmailIcon, @@ -776,6 +791,7 @@ export { PushoverIcon, QuickbooksIcon, MsTeamsIcon, + OutlookIcon, MailgunIcon, IpinfoIcon, GoogleCloudIcon, diff --git a/frontend/src/lib/components/instanceSettings.ts b/frontend/src/lib/components/instanceSettings.ts index 9701b74e30..9c55834caa 100644 --- a/frontend/src/lib/components/instanceSettings.ts +++ b/frontend/src/lib/components/instanceSettings.ts @@ -5,6 +5,7 @@ import { instanceBannerFormError } from './instanceBanner' import { ACCENT_COLOR_SETTING, parseAccentColor } from '$lib/accentColor' import { parseMaxTokenExpirationDays } from '$lib/tokenExpiration' import { writable } from 'svelte/store' +import { OidcService } from '$lib/gen' /** * Bumped after instance settings are successfully saved. Settings whose display @@ -76,6 +77,7 @@ export interface Setting { | 'retention_overrides' | 'instance_banner' | 'accent_color' + | 'agent_workload_identity_issuers' storage: SettingStorage advancedToggle?: { label: string @@ -175,8 +177,7 @@ export function isValidWebhookBaseUrl(value: unknown): boolean { return ( (url.protocol === 'http:' || url.protocol === 'https:') && url.host !== '' && - // Userinfo would end up in the per-repository receiver stored in workspace - // settings, which workspace admins can read. + // Userinfo would end up in URLs that users who are not instance admins can read. url.username === '' && url.password === '' && // Tested on the raw string, not `url.search`/`url.hash`: those are `''` for a @@ -187,6 +188,8 @@ export function isValidWebhookBaseUrl(value: unknown): boolean { // `new URL` silently percent-encodes a space in the path, where the server // rejects it outright. !/\s/.test(trimmed) && + // Shell-active characters: the URL is pasted into commands users copy. + !/[$`'"\\;&|<>(){}*!]/.test(trimmed) && !trimmed.endsWith('/') ) } @@ -207,7 +210,29 @@ export const settings: Record<string, Setting[]> = { (value?.startsWith('http') && value.includes('://') && !value?.endsWith('/') && - !value?.endsWith(' ')) + !value?.endsWith(' ')), + advancedToggle: { + label: 'The API is served on a different url than the UI', + onChange(values) { + values['api_base_url'] = values['api_base_url'] == null ? '' : null + return values + }, + checked: (values) => values['api_base_url'] != null + } + }, + { + label: 'API base url', + description: + 'Base url shown to users for the endpoints external clients call (webhooks, HTTP routes, push trigger endpoints, the CLI remote), without trailing slash. Leave empty to show the url the UI is browsed on. Set it when the API is served on a separate domain or behind an API gateway. If that url does not also serve the UI, the CLI must authenticate with a token rather than the browser login.', + key: 'api_base_url', + fieldType: 'text', + placeholder: 'https://api.windmill.company.com', + storage: 'setting', + ee_only: '', + hiddenIfNull: true, + error: + 'API base url must be an http:// or https:// url with a host, no embedded username or password, no query string or fragment, no shell metacharacters, and no trailing slash', + isValid: isValidWebhookBaseUrl }, { label: 'Email domain', @@ -354,6 +379,15 @@ export const settings: Record<string, Setting[]> = { value === null || value === '' || parseAccentColor(value) !== undefined + }, + { + label: 'Sync resource types from the hub daily', + description: + 'Every day, the server updates the resource types of the admins workspace from the Hub, overwriting local edits to the types the Hub also defines. Superadmins can also sync them on demand with "Sync resource types with Hub".', + key: 'sync_hub_resource_types_daily', + fieldType: 'boolean', + storage: 'setting', + hideInQuickSetup: true } ], Jobs: [ @@ -797,24 +831,27 @@ export const settings: Record<string, Setting[]> = { ee_only: '' } ], + 'Agent workers': [ + { + label: 'Workload identity issuers', + key: 'agent_workload_identity_issuers', + description: + 'An issuer lets an agent worker authenticate with a short-lived token its platform issues it (a Kubernetes projected service account token, a SPIFFE JWT-SVID, ...) in place of an agent token: point AGENT_IDENTITY_TOKEN_FILE at it. The token must be signed by a trusted issuer, carry its audience, and match a rule, which decides the worker group and tags the agent may serve. <a href="https://www.windmill.dev/docs/core_concepts/agent_workers">Learn more</a>', + fieldType: 'agent_workload_identity_issuers', + storage: 'setting', + ee_only: '' + } + ], 'DB Health': [], + 'OIDC signing': [], Registries: [ { label: 'Instance Python Version', description: 'Default python version for newly deployed scripts', key: 'instance_python_version', fieldType: 'select_python', - // To change latest stable version: - // 1. Change placeholder in instanceSettings.ts - // 2. Change LATEST_STABLE_PY in dockerfile - // 3. Change #[default] annotation for PyVersion in backend - placeholder: '3.10,3.11,3.12,3.13', + placeholder: '3.10,3.11,3.12,3.13,3.14,3.15', select_items: [ - { - label: 'Latest Stable', - value: 'default', - tooltip: 'python-3.12' - }, { label: '3.10' }, @@ -826,6 +863,12 @@ export const settings: Record<string, Setting[]> = { }, { label: '3.13' + }, + { + label: '3.14' + }, + { + label: '3.15' } ], storage: 'setting' @@ -1223,7 +1266,7 @@ export const settings: Record<string, Setting[]> = { storage: 'setting', ee_only: '', error: - 'Webhook base url must be an http:// or https:// url with a host, no embedded username or password, no query string or fragment, and no trailing slash', + 'Webhook base url must be an http:// or https:// url with a host, no embedded username or password, no query string or fragment, no shell metacharacters, and no trailing slash', isValid: isValidWebhookBaseUrl } ], @@ -1306,6 +1349,20 @@ export const instanceSettingsNavigationGroups = [ aiId: 'instance-settings-scim-saml', aiDescription: 'Instance SCIM/SAML settings', isEE: true + }, + { + id: 'agent_workers', + label: 'Agent workers', + aiId: 'instance-settings-agent-workers', + aiDescription: 'Workload identity issuers agent workers can authenticate with', + isEE: true + }, + { + id: 'oidc_signing', + label: 'OIDC signing', + aiId: 'instance-settings-oidc-signing', + aiDescription: 'Keys that sign and verify the OIDC tokens Windmill issues', + isEE: true } ] }, @@ -1463,6 +1520,8 @@ export const tabToCategoryMap: Record<string, string> = { github_enterprise_app: 'GitHub App', websocket: 'WebSocket', db_health: 'DB Health', + oidc_signing: 'OIDC signing', + agent_workers: 'Agent workers', lsp: 'LSP' } @@ -1472,6 +1531,30 @@ export const tabToAuthSubTab: Record<string, 'sso' | 'oauth' | 'scim'> = { scim_saml: 'scim' } +/** + * "OIDC signing" is listed only on instances that sign with an external signer: its page + * says nothing actionable elsewhere. + */ +export function listedNavigationGroups<G extends { items: { id: string }[] }>( + groups: G[], + externalOidcSigner: boolean +): G[] { + if (externalOidcSigner) return groups + return groups.map((group) => ({ + ...group, + items: group.items.filter((item) => item.id !== 'oidc_signing') + })) +} + +/** The status endpoint is EE only: call it once the license is known. */ +export async function usesExternalOidcSigner(): Promise<boolean> { + try { + return (await OidcService.getOidcSigningStatus()).mode === 'external' + } catch { + return false + } +} + // Navigation groups for the initial setup flow (no Users tab) export const setupNavigationGroups = instanceSettingsNavigationGroups .map((group) => ({ @@ -1500,6 +1583,8 @@ export const categoryToTabMap: Record<string, string> = { 'GitHub App': 'github_enterprise_app', WebSocket: 'websocket', 'DB Health': 'db_health', + 'OIDC signing': 'oidc_signing', + 'Agent workers': 'agent_workers', LSP: 'lsp' } diff --git a/frontend/src/lib/components/instanceSettings/AgentWorkloadIdentityIssuers.svelte b/frontend/src/lib/components/instanceSettings/AgentWorkloadIdentityIssuers.svelte new file mode 100644 index 0000000000..f7eb91a8b7 --- /dev/null +++ b/frontend/src/lib/components/instanceSettings/AgentWorkloadIdentityIssuers.svelte @@ -0,0 +1,276 @@ +<script lang="ts"> + import type { Writable } from 'svelte/store' + import { Button } from '../common' + import TextInput from '../text_input/TextInput.svelte' + import ToggleButtonGroup from '../common/toggleButton-v2/ToggleButtonGroup.svelte' + import ToggleButton from '../common/toggleButton-v2/ToggleButton.svelte' + import { Plus, Trash2, X } from 'lucide-svelte' + + interface Props { + values: Writable<Record<string, any>> + disabled?: boolean + } + + let { values, disabled = false }: Props = $props() + + const KEY = 'agent_workload_identity_issuers' + + type KeySource = 'discovery' | 'jwks_uri' | 'inline' + type ClaimRow = { id: number; path: string; value: string } + type RuleRow = { id: number; claims: ClaimRow[]; worker_group: string; tags: string } + type IssuerRow = { + id: number + issuer: string + audience: string + keySource: KeySource + jwks_uri: string + jwks: string + rules: RuleRow[] + } + + let nextId = 0 + // Rows keep a stable identity while editing; `lastSynced` tells our own writes to + // `$values[KEY]` apart from external ones (load, save, discard), which re-hydrate. + let issuers = $state<IssuerRow[]>([]) + let lastSynced: string | undefined = undefined + + function newRule(): RuleRow { + return { + id: nextId++, + claims: [{ id: nextId++, path: 'sub', value: '' }], + worker_group: '', + tags: '' + } + } + + function toRows(v: unknown): IssuerRow[] { + if (!Array.isArray(v)) return [] + return v.map((i: any) => ({ + id: nextId++, + issuer: i.issuer ?? '', + audience: i.audience ?? '', + keySource: i.jwks ? 'inline' : i.jwks_uri ? 'jwks_uri' : 'discovery', + jwks_uri: i.jwks_uri ?? '', + jwks: i.jwks ?? '', + rules: (i.rules ?? []).map((r: any) => ({ + id: nextId++, + claims: Object.entries(r.claims ?? {}).map(([path, value]) => ({ + id: nextId++, + path, + value: String(value) + })), + worker_group: r.worker_group ?? '', + tags: (r.tags ?? []).join(', ') + })) + })) + } + + function serialize(rows: IssuerRow[]): any[] | undefined { + if (rows.length === 0) return undefined + return rows.map((i) => ({ + issuer: i.issuer.trim(), + ...(i.keySource === 'jwks_uri' && i.jwks_uri.trim() ? { jwks_uri: i.jwks_uri.trim() } : {}), + ...(i.keySource === 'inline' && i.jwks.trim() ? { jwks: i.jwks.trim() } : {}), + audience: i.audience.trim(), + rules: i.rules.map((r) => ({ + claims: Object.fromEntries( + r.claims.filter((c) => c.path.trim()).map((c) => [c.path.trim(), c.value]) + ), + worker_group: r.worker_group.trim(), + tags: r.tags + .split(',') + .map((t) => t.trim()) + .filter((t) => t) + })) + })) + } + + $effect(() => { + const cur = JSON.stringify($values[KEY] ?? null) + if (cur === lastSynced) return + lastSynced = cur + issuers = toRows($values[KEY]) + }) + + $effect(() => { + const next = serialize(issuers) + if (lastSynced === undefined) return + const nextStr = JSON.stringify(next ?? null) + // Compare against the stored value normalized the same way, so loading a value whose + // keys are ordered differently does not mark the form dirty. + if (nextStr === JSON.stringify(serialize(toRows($values[KEY])) ?? null)) return + lastSynced = nextStr + $values[KEY] = next + }) + + function addIssuer() { + issuers.push({ + id: nextId++, + issuer: '', + audience: 'windmill', + keySource: 'discovery', + jwks_uri: '', + jwks: '', + rules: [newRule()] + }) + } +</script> + +<div class="flex flex-col gap-4"> + {#each issuers as issuer, i (issuer.id)} + <div class="flex flex-col gap-3 p-4 rounded-md border"> + <div class="flex items-center justify-between"> + <span class="text-xs font-semibold text-emphasis">Issuer {i + 1}</span> + <Button + variant="subtle" + unifiedSize="xs" + startIcon={{ icon: Trash2 }} + iconOnly + {disabled} + aria-label="Remove issuer" + onclick={() => issuers.splice(i, 1)} + /> + </div> + <label class="flex flex-col gap-1"> + <span class="text-xs text-secondary">Issuer (must equal the token's iss)</span> + <TextInput + bind:value={issuer.issuer} + inputProps={{ placeholder: 'https://kubernetes.default.svc.cluster.local', disabled }} + /> + </label> + <label class="flex flex-col gap-1"> + <span class="text-xs text-secondary">Audience (must be in the token's aud)</span> + <TextInput + bind:value={issuer.audience} + inputProps={{ placeholder: 'windmill', disabled }} + /> + </label> + <div class="flex flex-col gap-1"> + <span class="text-xs text-secondary">Signing keys</span> + <ToggleButtonGroup bind:selected={issuer.keySource} {disabled}> + {#snippet children({ item })} + <ToggleButton + value="discovery" + label="OIDC discovery" + tooltip="Read jwks_uri from <issuer>/.well-known/openid-configuration" + {item} + /> + <ToggleButton value="jwks_uri" label="JWKS URL" {item} /> + <ToggleButton + value="inline" + label="Inline JWKS" + tooltip="For an issuer this instance cannot reach, e.g. the output of kubectl get --raw /openid/v1/jwks" + {item} + /> + {/snippet} + </ToggleButtonGroup> + {#if issuer.keySource === 'jwks_uri'} + <TextInput + bind:value={issuer.jwks_uri} + inputProps={{ placeholder: 'https://issuer.example.com/keys', disabled }} + /> + {:else if issuer.keySource === 'inline'} + <TextInput + underlyingInputEl="textarea" + bind:value={issuer.jwks} + inputProps={{ placeholder: '{"keys": [...]}', rows: 4, disabled }} + /> + {/if} + </div> + <div class="flex flex-col gap-2"> + <span class="text-xs text-secondary"> + Rules, tried in order: the first whose claims all match gives the agent its worker group + and tags. A token no rule matches is refused. + </span> + {#each issuer.rules as rule, j (rule.id)} + <div class="flex flex-col gap-2 border-l-2 border-surface-selected pl-3"> + <div class="flex items-center justify-between"> + <span class="text-2xs font-semibold text-secondary">Rule {j + 1}</span> + <Button + variant="subtle" + unifiedSize="xs" + startIcon={{ icon: Trash2 }} + iconOnly + {disabled} + aria-label="Remove rule" + onclick={() => issuer.rules.splice(j, 1)} + /> + </div> + {#each rule.claims as claim, k (claim.id)} + <div class="flex items-center gap-2"> + <TextInput + bind:value={claim.path} + class="w-64" + inputProps={{ placeholder: 'kubernetes.io.namespace', disabled }} + /> + <span class="text-xs text-secondary">=</span> + <TextInput + bind:value={claim.value} + inputProps={{ placeholder: 'system:serviceaccount:<ns>:<sa>', disabled }} + /> + <Button + variant="subtle" + unifiedSize="xs" + startIcon={{ icon: X }} + iconOnly + disabled={disabled || rule.claims.length <= 1} + aria-label="Remove claim" + onclick={() => rule.claims.splice(k, 1)} + /> + </div> + {/each} + <div class="flex"> + <Button + variant="subtle" + unifiedSize="xs" + startIcon={{ icon: Plus }} + {disabled} + onclick={() => rule.claims.push({ id: nextId++, path: '', value: '' })} + > + Add claim + </Button> + </div> + <div class="flex gap-2"> + <label class="flex flex-col gap-1 w-48"> + <span class="text-2xs text-secondary">Worker group</span> + <TextInput + bind:value={rule.worker_group} + inputProps={{ placeholder: 'k8s', disabled }} + /> + </label> + <label class="flex flex-col gap-1 grow"> + <span class="text-2xs text-secondary">Tags (comma separated)</span> + <TextInput + bind:value={rule.tags} + inputProps={{ placeholder: 'dbt, etl', disabled }} + /> + </label> + </div> + </div> + {/each} + <div class="flex"> + <Button + variant="default" + unifiedSize="sm" + startIcon={{ icon: Plus }} + {disabled} + onclick={() => issuer.rules.push(newRule())} + > + Add rule + </Button> + </div> + </div> + </div> + {/each} + <div class="flex"> + <Button + variant="default" + unifiedSize="sm" + startIcon={{ icon: Plus }} + {disabled} + onclick={addIssuer} + > + Add issuer + </Button> + </div> +</div> diff --git a/frontend/src/lib/components/instanceSettings/CriticalAlertChannels.svelte b/frontend/src/lib/components/instanceSettings/CriticalAlertChannels.svelte index 5b1289eefc..6df7dd51d6 100644 --- a/frontend/src/lib/components/instanceSettings/CriticalAlertChannels.svelte +++ b/frontend/src/lib/components/instanceSettings/CriticalAlertChannels.svelte @@ -42,7 +42,8 @@ ) } - const isTeamsConnected = $derived(isTeamsOAuthConfigured(oauths?.teams)) + // TODO: drop the pre-rename `teams` fallback with the backend one. + const isTeamsConnected = $derived(isTeamsOAuthConfigured(oauths?.ms_teams ?? oauths?.teams)) // Compute dynamic order based on channel presence const slackOrder = $derived(slackChannels.length > 0 ? 1 : 4) diff --git a/frontend/src/lib/components/instanceSettings/InstanceAISettings.svelte b/frontend/src/lib/components/instanceSettings/InstanceAISettings.svelte index 8d7d107940..2f2145da9b 100644 --- a/frontend/src/lib/components/instanceSettings/InstanceAISettings.svelte +++ b/frontend/src/lib/components/instanceSettings/InstanceAISettings.svelte @@ -1,5 +1,5 @@ <script lang="ts"> - import { JobService, SettingService, WorkspaceService, type AIConfig } from '$lib/gen' + import { SettingService, WorkspaceService, type AIConfig } from '$lib/gen' import { setCopilotInfo } from '$lib/aiStore' import { workspaceStore, userStore } from '$lib/stores' import { getUserExt } from '$lib/user' @@ -7,6 +7,7 @@ import { workspaceAIClients } from '../copilot/lib' import AISettings from '../workspaceSettings/AISettings.svelte' import { Alert, Button } from '../common' + import SettingCard from './SettingCard.svelte' interface Props { hasUnsavedChanges?: boolean @@ -80,20 +81,15 @@ hubSyncStatus = 'loading' hubSyncMessage = '' try { - await JobService.runWaitResultScriptByPath({ - workspace: 'admins', - path: 'u/admin/hub_sync', - requestBody: {} - }) + const res = await fetch('/api/settings/sync_cached_resource_types', { method: 'POST' }) + if (!res.ok) { + const body = await res.text() + throw new Error(body || res.statusText) + } + hubSyncMessage = await res.text() hubSyncStatus = 'success' - hubSyncMessage = 'Resource types synced from hub successfully' } catch (e: any) { - hubSyncMessage = - e?.body?.error?.message || - e?.body?.message || - (typeof e?.body === 'string' ? e.body : null) || - e?.message || - 'Failed to sync from hub' + hubSyncMessage = e?.message ?? 'Failed to sync from hub' hubSyncStatus = 'error' } } @@ -101,37 +97,31 @@ {#if loaded} {#if showHubSync} - <div - class="p-3 border rounded-md bg-surface-secondary mb-4 mt-4 flex items-center justify-between gap-4" + <SettingCard + label="Resource types" + description="AI providers require their resource types. Sync from the Hub if they are missing." + class="my-4" > - <div> - <p class="text-xs font-medium text-secondary">Resource types</p> - <p class="text-2xs text-tertiary mt-0.5"> - AI providers require their resource types. Sync from the Hub if they are missing. - </p> - </div> - <Button - variant="default" - unifiedSize="sm" - loading={hubSyncStatus === 'loading'} - onClick={syncFromHub} - > - Sync from hub - </Button> - </div> - {#if hubSyncStatus === 'success'} - <div class="mb-4"> - <Alert type="success" title="Resource types synced"> + {#snippet headerAction()} + <Button + variant="default" + unifiedSize="sm" + loading={hubSyncStatus === 'loading'} + onClick={syncFromHub} + > + Sync from hub + </Button> + {/snippet} + {#if hubSyncStatus === 'success'} + <Alert type="success" title="Resource types synced" class="mt-2"> {hubSyncMessage} </Alert> - </div> - {:else if hubSyncStatus === 'error'} - <div class="mb-4"> - <Alert type="error" title="Sync failed"> + {:else if hubSyncStatus === 'error'} + <Alert type="error" title="Sync failed" class="mt-2"> {hubSyncMessage} </Alert> - </div> - {/if} + {/if} + </SettingCard> {/if} <AISettings diff --git a/frontend/src/lib/components/instanceSettings/OidcSigningStatus.svelte b/frontend/src/lib/components/instanceSettings/OidcSigningStatus.svelte new file mode 100644 index 0000000000..e223b7452c --- /dev/null +++ b/frontend/src/lib/components/instanceSettings/OidcSigningStatus.svelte @@ -0,0 +1,100 @@ +<script lang="ts"> + import { OidcService } from '$lib/gen' + import { Alert, Badge, CopyButton } from '$lib/components/common' + import DataTable from '$lib/components/table/DataTable.svelte' + import Head from '$lib/components/table/Head.svelte' + import Cell from '$lib/components/table/Cell.svelte' + import { displayDate } from '$lib/utils' + + type Status = Awaited<ReturnType<typeof OidcService.getOidcSigningStatus>> + + let status = $state<Status | undefined>(undefined) + let loadError = $state<string | undefined>(undefined) + + const modeLabels: Record<Status['mode'], string> = { + database: 'Key stored in the database', + file: 'Key file (OIDC_SIGNING_KEY_FILE)', + external: 'External signer (OIDC_SIGNER_URL)' + } + + $effect(() => { + OidcService.getOidcSigningStatus() + .then((s) => { + status = s + loadError = undefined + }) + .catch((e) => { + loadError = e?.body ?? e?.message ?? String(e) + }) + }) +</script> + +{#if loadError} + <Alert type="error" title="Could not load the OIDC signing status">{loadError}</Alert> +{:else if status} + <div class="flex flex-col gap-4"> + <div class="text-xs text-primary"> + <span class="text-secondary">Tokens are signed by:</span> + {modeLabels[status.mode]} + </div> + {#if status.signer} + <div class="flex flex-wrap items-center gap-2 text-xs text-primary"> + <span class="text-secondary">Last key listing:</span> + {status.signer.last_refresh_success + ? displayDate(status.signer.last_refresh_success) + : 'never'} + {#if status.signer.breaker !== 'closed'} + <Badge color="red">Signer unreachable</Badge> + {:else if !status.signer.last_refresh_error && status.signer.last_refresh_success} + <Badge color="green">Signer reachable</Badge> + {/if} + </div> + {#if status.signer.last_refresh_error} + <Alert type="warning" title="The last key listing was refused"> + {status.signer.last_refresh_error} + </Alert> + {/if} + {#if status.signer.keys_from_store} + <Alert type="warning" title="The signer has not answered since this server started"> + The keys below are those stored by the last accepted listing. Tokens cannot be signed + until the signer answers. + </Alert> + {/if} + {#if status.signer.tls_files_error} + <Alert type="warning" title="The mTLS files on disk are not in use"> + {status.signer.tls_files_error}. The previous certificate and key are kept. + </Alert> + {/if} + {/if} + <DataTable size="xs"> + <Head> + <tr> + <Cell head first>Key ID (kid)</Cell> + <Cell head>Algorithm</Cell> + <Cell head>State</Cell> + <Cell head last>Source</Cell> + </tr> + </Head> + <tbody> + {#each status.keys as key, i (`${key.source}:${key.kid ?? i}`)} + <tr> + <Cell first> + <span class="flex items-center gap-1 font-mono text-xs"> + {key.kid} + {#if key.kid}<CopyButton value={key.kid} />{/if} + </span> + </Cell> + <Cell>{key.alg}</Cell> + <Cell> + <Badge color={key.state === 'active' ? 'green' : 'gray'}>{key.state}</Badge> + </Cell> + <Cell last>{key.source}</Cell> + </tr> + {/each} + </tbody> + </DataTable> + {#if status.keys.length === 0} + <div class="text-xs text-secondary">The JWKS serves no key.</div> + {/if} + </div> +{/if} diff --git a/frontend/src/lib/components/instanceSettingsWebhookBaseUrl.test.ts b/frontend/src/lib/components/instanceSettingsWebhookBaseUrl.test.ts index c8545b073e..175a251315 100644 --- a/frontend/src/lib/components/instanceSettingsWebhookBaseUrl.test.ts +++ b/frontend/src/lib/components/instanceSettingsWebhookBaseUrl.test.ts @@ -29,7 +29,10 @@ const REJECTED = [ 'https://hooks.example.com?', 'https://hooks.example.com#', 'https://user:password@hooks.example.com', - 'https://user@hooks.example.com' + 'https://user@hooks.example.com', + 'https://hooks.example.com/$(uname)', + 'https://hooks.example.com/`uname`', + 'https://hooks.example.com/a;b' ] describe('isValidWebhookBaseUrl', () => { @@ -41,10 +44,13 @@ describe('isValidWebhookBaseUrl', () => { expect(isValidWebhookBaseUrl(value)).toBe(false) }) - it.each([true, 42, {}, [], null] as unknown[])('rejects the non-string %j without throwing', (value) => { - // `Setting.isValid` is typed `any` and YAML mode can supply any JSON shape. - expect(isValidWebhookBaseUrl(value as never)).toBe(value === null) - }) + it.each([true, 42, {}, [], null] as unknown[])( + 'rejects the non-string %j without throwing', + (value) => { + // `Setting.isValid` is typed `any` and YAML mode can supply any JSON shape. + expect(isValidWebhookBaseUrl(value as never)).toBe(value === null) + } + ) it('treats unset and blank as valid, since the setting is optional', () => { expect(isValidWebhookBaseUrl(undefined)).toBe(true) diff --git a/frontend/src/lib/components/jobs/MissingWorkerTagAlert.svelte b/frontend/src/lib/components/jobs/MissingWorkerTagAlert.svelte index c6b86b1cc7..1dbeb984bd 100644 --- a/frontend/src/lib/components/jobs/MissingWorkerTagAlert.svelte +++ b/frontend/src/lib/components/jobs/MissingWorkerTagAlert.svelte @@ -1,10 +1,17 @@ <script lang="ts"> - import { base } from '$app/paths' import Alert from '$lib/components/common/alert/Alert.svelte' import { WorkerService } from '$lib/gen' import { resource } from 'runed' import { hasWorkerForTag } from './missingWorker' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + import { userWorkspaces } from '$lib/stores' + import { + devWorkspaceTagSuffix, + devWorkspaceSkipNonDevForks, + isIsolatedWorkspaceId, + loadDevWorkspaceTagSuffix, + withDevSuffix + } from '$lib/devWorkspaceTags' const operatingWorkspace = useOperatingWorkspace() @@ -25,16 +32,34 @@ // `tag`, so probing the bare tag would warn about a tag nothing uses. The // in-flight check in `pollJobResult` reads the job's real tag and still covers // those instances. + // A dev workspace's jobs run on the suffixed tag, which only groups serving dev workspaces pull. + let devSuffix = $derived( + $devWorkspaceTagSuffix && + isIsolatedWorkspaceId(ws, $userWorkspaces, $devWorkspaceSkipNonDevForks) + ? $devWorkspaceTagSuffix + : undefined + ) + let runTag = $derived(devSuffix ? withDevSuffix(tag, devSuffix) : tag) const served = resource( - () => [ws, tag] as const, - async ([ws, tag]) => { + () => [ws, runTag] as const, + async ([ws, runTag]) => { + await loadDevWorkspaceTagSuffix() if (!ws || (await WorkerService.isDefaultTagsPerWorkspace())) return true - return await hasWorkerForTag(ws, tag) + return await hasWorkerForTag(ws, runTag) } ) </script> -{#if served.current === false} +{#if served.current === false && devSuffix} + <div class={className}> + <Alert type="warning" title="No worker is running for the "{runTag}" tag" size="xs"> + {subject} run as Windmill jobs tagged <b>{tag}</b>, which this workspace, a dev workspace or a + fork, runs as <b>{runTag}</b>. No worker is currently listening to it, so they stay queued + until one is. An admin can serve it by flagging a worker group that lists <b>{tag}</b> as + serving dev workspaces on the <a href="/workers">workers page</a>. + </Alert> + </div> +{:else if served.current === false} <div class={className}> <!-- Deliberately not phrased as "this tag is not configured": a correctly tagged group sitting at zero replicas is indistinguishable from one in @@ -43,7 +68,7 @@ {subject} run as Windmill jobs tagged <b>{tag}</b>, and no worker is currently listening to that tag, so they stay queued until one is. If no worker group is meant to serve it, add <b>{tag}</b> - to a group's worker tags on the <a href="{base}/workers">workers page</a>. + to a group's worker tags on the <a href="/workers">workers page</a>. </Alert> </div> {/if} diff --git a/frontend/src/lib/components/jobs/missingWorker.ts b/frontend/src/lib/components/jobs/missingWorker.ts index e392e06d3e..699f0ab9c1 100644 --- a/frontend/src/lib/components/jobs/missingWorker.ts +++ b/frontend/src/lib/components/jobs/missingWorker.ts @@ -1,4 +1,5 @@ import { JobService, WorkerService } from '$lib/gen' +import { devTagNoWorkerHint, loadDevWorkspaceTagSuffix } from '$lib/devWorkspaceTags' /** * A queued job whose tag no running worker serves is never picked up: without @@ -15,9 +16,10 @@ export class NoWorkerForTagError extends Error { constructor(tag: string) { super( `No worker has been listening to the tag "${tag}" while this job waited, so it was never ` + - `picked up. It stays queued and will run once a worker with that tag comes online. ` + - `Add "${tag}" to the worker tags of one of your worker groups (Workers page), or run a ` + - `worker that serves it.` + `picked up. It stays queued and will run once a worker with that tag comes online.` + + (devTagNoWorkerHint(tag) || + ` Add "${tag}" to the worker tags of one of your worker groups (Workers page), or run ` + + `a worker that serves it.`) ) this.name = 'NoWorkerForTagError' this.tag = tag @@ -28,8 +30,10 @@ export class NoWorkerForTagError extends Error { export function queuedWithoutWorkerMessage(tag: string): string { return ( `No worker is listening to the tag "${tag}", so this operation is queued and will only run ` + - `once one is. Add "${tag}" to the worker tags of one of your worker groups (Workers page), ` + - `or run a worker that serves it.` + `once one is.` + + (devTagNoWorkerHint(tag) || + ` Add "${tag}" to the worker tags of one of your worker groups (Workers page), or run a ` + + `worker that serves it.`) ) } @@ -68,7 +72,9 @@ export async function missingWorkerTagOfQueuedJob( try { const job = await JobService.getJob({ workspace, id: jobId, noCode: true, noLogs: true }) if (job.type !== 'QueuedJob' || job.running || !job.tag) return undefined - return (await hasWorkerForTag(workspace, job.tag)) ? undefined : job.tag + if (await hasWorkerForTag(workspace, job.tag)) return undefined + await loadDevWorkspaceTagSuffix() + return job.tag } catch (err) { console.warn('Could not determine whether a worker serves the job tag', err) return undefined diff --git a/frontend/src/lib/components/mcp/McpConnect.svelte b/frontend/src/lib/components/mcp/McpConnect.svelte index 1fe1a2fed9..a8808aa052 100644 --- a/frontend/src/lib/components/mcp/McpConnect.svelte +++ b/frontend/src/lib/components/mcp/McpConnect.svelte @@ -8,7 +8,6 @@ import McpServerOAuthConnect from './McpServerOAuthConnect.svelte' import OauthScopes from '$lib/components/OauthScopes.svelte' import { sameTopDomainOrigin } from '$lib/cookies' - import { base } from '$lib/base' import { onDestroy, untrack } from 'svelte' import { ExternalLink, Pen } from 'lucide-svelte' import { MCP_REGISTRY, findMcpEntry, findMcpEntryByUrl } from './registry' @@ -449,7 +448,7 @@ Under <span class="font-mono">u/{$userStore?.username ?? 'you'}</span> it is yours alone; in a folder, everyone in it can use the connection and its token. Saved as an <a - href="{base}/resources?workspace={ws}" + href="/resources?workspace={ws}" target="_blank" rel="noopener noreferrer" class="text-accent hover:underline inline-flex items-center gap-1" diff --git a/frontend/src/lib/components/mcp/mcpMenu.svelte.ts b/frontend/src/lib/components/mcp/mcpMenu.svelte.ts index a911d71c07..853d994014 100644 --- a/frontend/src/lib/components/mcp/mcpMenu.svelte.ts +++ b/frontend/src/lib/components/mcp/mcpMenu.svelte.ts @@ -1,4 +1,4 @@ -import { List, Plus } from 'lucide-svelte' +import { List, Loader2, Plus } from 'lucide-svelte' import type { Component } from 'svelte' import { get } from 'svelte/store' import { ResourceService } from '$lib/gen' @@ -27,6 +27,14 @@ const MAX_MENU_SERVERS = 8 // menu nobody is reading that far down. const MAX_ICON_LOOKUPS = 20 +// Not `disabled`: melt stamps that on a row at mount and never clears it, and the +// unkeyed submenu reuses this row for the first server once the load lands. +const loadingItem: Item = { + displayName: 'Loading…', + icon: Loader2, + iconProps: { class: 'animate-spin shrink-0' } +} + /** * The chat "+" menu's MCP submenu: one row per connected server, checked when it * is on, then the way to manage them. Connecting and deleting live in the @@ -38,7 +46,7 @@ export class McpMenu { #seq = 0 /** Rows for the workspace named by `#rowsWorkspace`, and meaningless for any other. */ #rows = $state<Row[]>([]) - #rowsWorkspace: string | undefined = undefined + #rowsWorkspace = $state<string | undefined>(undefined) constructor(manager: AIChatManager, onManage: () => void) { this.#manager = manager @@ -73,6 +81,10 @@ export class McpMenu { editedAt: r.edited_at, enabled: isMcpEnabled(ws, r.path) })) + // Enabled first: those are the ones a quick visit is most likely about. + // Sorted here, once per load, not in `items()`: the open submenu re-derives + // from `items()`, so a toggle would move rows under the cursor. + .sort((a, b) => Number(b.enabled) - Number(a.enabled) || a.path.localeCompare(b.path)) this.#rowsWorkspace = ws void this.#loadIcons(ws, seq) } catch { @@ -143,23 +155,22 @@ export class McpMenu { await this.#manager.refreshMcpServers(ws) } - /** Loaded on open so the checks are current. */ - async items(closeMenu?: () => void): Promise<Item[]> { + /** Called on open so the checks are current; never awaited, see `items`. */ + refresh() { + const ws = this.#ws + if (ws) void this.#load(ws) + } + + /** + * Built from the live rows, so call it from a getter: the submenu then fills in + * when a load lands instead of the whole "+" menu waiting on the fetch. Rows for + * another workspace are not shown — same path, different server. + */ + items(closeMenu?: () => void): Item[] { const ws = this.#ws if (!ws) return [] - // The menu opens on what is already known and refreshes behind it: awaited - // inline it would stall the whole "+" menu, attachments included. Rows for - // another workspace are not "already known" — same path, different server. - if (this.#rowsWorkspace !== ws) { - this.#rows = [] - await this.#load(ws) - } else { - void this.#load(ws) - } - // Enabled first: those are the ones a quick visit is most likely about. - const ordered = [...this.#rows].sort( - (a, b) => Number(b.enabled) - Number(a.enabled) || a.path.localeCompare(b.path) - ) + if (this.#rowsWorkspace !== ws) return [loadingItem] + const ordered = this.#rows const shown = ordered.slice(0, MAX_MENU_SERVERS) const manage = () => { closeMenu?.() diff --git a/frontend/src/lib/components/mcp/providerIcon.ts b/frontend/src/lib/components/mcp/providerIcon.ts index ed8d059a57..a666b2b1c5 100644 --- a/frontend/src/lib/components/mcp/providerIcon.ts +++ b/frontend/src/lib/components/mcp/providerIcon.ts @@ -12,8 +12,11 @@ import { findMcpEntry, findMcpEntryByUrl } from './registry' * the chat does not otherwise reach that barrel. `import.meta.glob` gives the * filenames at build time and the module only when a match is actually used, so * a workspace with two connections downloads two icons. + * + * The pattern is relative because svelte-package rewrites `$lib` only in import + * specifiers: an aliased glob ships as-is and no consumer's bundler expands it. */ -const iconModules = import.meta.glob('$lib/components/icons/*.svelte') as Record< +const iconModules = import.meta.glob('../icons/*.svelte') as Record< string, () => Promise<{ default: Component<any> }> > diff --git a/frontend/src/lib/components/otherUserDraftLoad.svelte.ts b/frontend/src/lib/components/otherUserDraftLoad.svelte.ts index 7ba5cde6fb..e2bf7c87d8 100644 --- a/frontend/src/lib/components/otherUserDraftLoad.svelte.ts +++ b/frontend/src/lib/components/otherUserDraftLoad.svelte.ts @@ -1,6 +1,5 @@ import { SvelteMap, SvelteSet } from 'svelte/reactivity' import { goto } from '$lib/navigation' -import { base } from '$app/paths' import { UserDraft, draftValuesEqual, type UserDraftItemKind } from '$lib/userDraft.svelte' import { UserDraftDbSyncer } from '$lib/userDraftDbSyncer.svelte' @@ -55,13 +54,13 @@ const overwriteOpen = new SvelteSet<string>() export function editRouteFor(itemKind: UserDraftItemKind, path: string): string { switch (itemKind) { case 'script': - return `${base}/scripts/edit/${path}` + return `/scripts/edit/${path}` case 'flow': - return `${base}/flows/edit/${path}` + return `/flows/edit/${path}` case 'app': - return `${base}/apps/edit/${path}` + return `/apps/edit/${path}` case 'raw_app': - return `${base}/apps_raw/edit/${path}` + return `/apps_raw/edit/${path}` default: throw new Error(`Cannot load drafts of kind ${itemKind}`) } diff --git a/frontend/src/lib/components/pageHeaderRegistry.svelte.ts b/frontend/src/lib/components/pageHeaderRegistry.svelte.ts index 3167d636e9..91f092e88d 100644 --- a/frontend/src/lib/components/pageHeaderRegistry.svelte.ts +++ b/frontend/src/lib/components/pageHeaderRegistry.svelte.ts @@ -24,10 +24,16 @@ export type PageHeaderItem = { /** A page with no item of its own, such as a list: the breadcrumb is the section alone. */ export type PageHeaderSection = { label: string + /** The page the section belongs to, when the section is one pane of it — a settings page's + * active tab. Drawn as a lead segment before `label`. */ + parent?: string /** Rendered in place of `label` when the name is itself a control, such as an editable title. */ content?: Snippet /** Scopes the segment's picker, when the section maps to a kind of item. */ kind?: WorkspaceItemKind + /** No chevron after the name: the page's siblings are not the workspace's pages and items, + * which is all that picker offers. A session is one. */ + noNavPicker?: boolean } export type PageHeaderContent = { @@ -49,6 +55,26 @@ export type PageHeaderContent = { * controls share one shape that opens into the page below. The bar gives up its right padding * to it, since the surface is what meets the edge. */ actionsFill?: boolean + /** How many levels past the full row these actions can fold through, each a narrower row than + * the last. The bar picks the level from the room its breadcrumb leaves once it has dropped + * all it can, and the page reads it back as `pageHeader.actionFold`. Without it the actions + * never fold and the breadcrumb gives up width around them. */ + actionFolds?: number + /** How many of the `actionFolds` levels come before the breadcrumb drops anything: buttons + * that are there only while the bar has room for everything. */ + earlyActionFolds?: number + /** Changes whenever the actions may have changed width at a level that is not on screen — a + * run's Cancel, folded into a menu, going once the job completes. The bar keeps what it + * measured per version, so a new one is measured afresh rather than judged by stale widths. */ + actionsVersion?: string + /** A second row of the band, under the breadcrumb and the actions: where a control too wide + * for one row goes at a fold that has no room for it beside them, rather than being squeezed + * until it is useless. The band is taller while it is there. */ + belowBar?: Snippet + /** The fold from which the bar shows `belowBar`. The bar decides rather than the page passing + * the row in only at that fold: the fold is derived from this registration, so a registration + * that read it would be a cycle. */ + belowBarFold?: number /** Rendered right after the page's name in the breadcrumb: a mark that belongs to the name, * like a documentation tooltip, or a control that acts on the thing named — an app's Edit, * which at the far end of the bar would be a journey away from what it edits. */ @@ -88,10 +114,9 @@ let entries = $state<{ id: number; get: () => PageHeaderContent }[]>([]) let nextId = 0 /** - * Below this bar width a page keeps one button — the thing the page is for — and folds the rest - * into the menu it already shows when compact. A phone in portrait is ~390px of bar and a tablet - * in portrait ~720; the breadcrumb with its workspace disc takes ~150 of either, which is why the - * line sits above the tablet rather than between the two. + * A phone's bar: a tighter gutter, and the width below which controls that cannot fold through + * `actionFolds` — a flexible filter row, a banner — slim down. A phone in portrait is ~390px of + * bar and a tablet in portrait ~720, which is why the line sits above the tablet. */ export const PHONE_BAR = 800 @@ -109,6 +134,9 @@ export const BAR_HEIGHT_PX = 48 // share that row with the breadcrumb, so it is the width they crowd against — not the window's, // which the sidebar and a page's side panel both take from. let barWidth = $state(0) +// The bar owns the fold level: it is derived from the bar's own measurements, so the bar hands +// over a getter rather than writing a copy that an effect would have to keep in step. +let actionFoldSource = $state<(() => number) | undefined>(undefined) /** * One registration's content, or undefined while it cannot answer. @@ -148,6 +176,11 @@ export const pageHeader = { if (c.barRightInset !== undefined) merged.barRightInset = c.barRightInset if (c.actionsFlexible !== undefined) merged.actionsFlexible = c.actionsFlexible if (c.actionsFill !== undefined) merged.actionsFill = c.actionsFill + if (c.actionFolds !== undefined) merged.actionFolds = c.actionFolds + if (c.earlyActionFolds !== undefined) merged.earlyActionFolds = c.earlyActionFolds + if (c.actionsVersion !== undefined) merged.actionsVersion = c.actionsVersion + if (c.belowBar !== undefined) merged.belowBar = c.belowBar + if (c.belowBarFold !== undefined) merged.belowBarFold = c.belowBarFold if (c.separator !== undefined) merged.separator = c.separator } return merged @@ -173,6 +206,17 @@ export const pageHeader = { setBarWidth(w: number) { barWidth = w }, + /** How far the page's actions are folded: 0 for the full row, up to its `actionFolds`. */ + get actionFold(): number { + return actionFoldSource?.() ?? 0 + }, + /** Called by the bar once; returns the release to call when the bar goes away. */ + provideActionFold(get: () => number): () => void { + actionFoldSource = get + return () => { + if (actionFoldSource === get) actionFoldSource = undefined + } + }, /** Registers on mount and returns the id to release on destroy. */ register(get: () => PageHeaderContent): number { const id = nextId++ diff --git a/frontend/src/lib/components/pageHeaderStages.test.ts b/frontend/src/lib/components/pageHeaderStages.test.ts new file mode 100644 index 0000000000..7366fdd244 --- /dev/null +++ b/frontend/src/lib/components/pageHeaderStages.test.ts @@ -0,0 +1,77 @@ +import { describe, expect, it } from 'vitest' +import { BAR_STAGES, fitBar, type BarMeasure } from './pageHeaderStages' + +// Each stage 50px narrower than the last, so the bar width alone says which one fits. +const trail = BAR_STAGES.map((_, i) => 600 - i * 50) +const base: BarMeasure = { + barWidth: 2000, + chrome: 0, + trail, + summary: BAR_STAGES.map(() => 0), + actions: [300, 200, 100], + folds: 2, + natural: { family: 0, fork: 0, summary: 0, name: 0 } +} + +describe('fitBar', () => { + it('picks the first stage that fits beside the full row of actions', () => { + expect(fitBar({ ...base, barWidth: 900 }).stage).toBe(0) + expect(fitBar({ ...base, barWidth: 800 })).toMatchObject({ stage: 2, fold: 0 }) + }) + + it('folds the actions only once the breadcrumb is at its last stage, and keeps it there', () => { + // 350 + 300 overflows a 600px bar; 350 + 200 fits. Stage 0 would fit beside the folded row + // too, but the parts a narrowing bar dropped do not come back when the buttons fold. + expect(fitBar({ ...base, barWidth: 600 })).toMatchObject({ stage: 5, fold: 1 }) + expect(fitBar({ ...base, barWidth: 400 })).toMatchObject({ stage: 5, fold: 2 }) + }) + + it('spends early folds before the breadcrumb drops anything', () => { + // 600 + 200 fits an 800px bar at the first fold; without early folds stage 2 would have + // dropped parts beside the full row instead. + expect(fitBar({ ...base, barWidth: 800, earlyFolds: 1 })).toMatchObject({ stage: 0, fold: 1 }) + // Past that, the breadcrumb gives way at the early fold before the later folds start. + expect(fitBar({ ...base, barWidth: 700, earlyFolds: 1 })).toMatchObject({ stage: 2, fold: 1 }) + }) + + it('tries a level it has not seen at the width of the next one folded further', () => { + // Only the second fold has been measured: the levels before it are assumed no wider, so the + // bar tries the full row first and goes on to the first fold once it has seen it overflow. + const unseen = { ...base, barWidth: 600, actions: [undefined, undefined, 100] } + expect(fitBar(unseen).fold).toBe(0) + expect(fitBar({ ...unseen, actions: [300, undefined, 100] }).fold).toBe(1) + }) + + it("takes the squeeze from the path's name before the summary", () => { + const fit = fitBar({ + ...base, + barWidth: 360, + actions: [0], + folds: 0, + trail: trail.map((w) => w - 400), + summary: BAR_STAGES.map(() => 100), + natural: { family: 0, fork: 0, summary: 300, name: 300 } + }) + // Stage 0 at its floors is 300px; whole, the name and the summary add 140 and 100, so 180 + // has to go: all 140 the name has above its floor, then 40 from the summary. + expect(fit).toMatchObject({ stage: 0, caps: { name: 160, summary: 260 }, scopesGive: false }) + }) + + it('keeps the summary and drops the path when only one of them fits', () => { + const natural = { family: 0, fork: 0, summary: 300, name: 300 } + // Stage 2 is the first without the path: the name is no longer a part the bar sizes. + const fit = fitBar({ ...base, barWidth: 520, natural, actions: [0], folds: 0 }) + expect(fit.stage).toBe(2) + expect(fit.caps.name).toBeUndefined() + // A placeholder offering to add a summary names nothing: the path stays a part the bar sizes. + const placeholder = fitBar({ + ...base, + barWidth: 520, + natural, + actions: [0], + folds: 0, + summaryNamesItem: false + }) + expect(placeholder.caps.name).toBeDefined() + }) +}) diff --git a/frontend/src/lib/components/pageHeaderStages.ts b/frontend/src/lib/components/pageHeaderStages.ts new file mode 100644 index 0000000000..ca776c9199 --- /dev/null +++ b/frontend/src/lib/components/pageHeaderStages.ts @@ -0,0 +1,213 @@ +/** + * How the page header gives up width. Whole parts drop in a fixed order, and the bar shows the + * first stage whose parts, each held at its floor width, fit beside the page's actions. Which + * stage that is depends on the names in the bar rather than on a pixel breakpoint. Past the last + * stage the page's actions fold, one level at a time; past their last level the item's name and + * its summary truncate, then the folders above it. + */ + +/** What the breadcrumb itself drops. */ +export type TrailStage = { + /** Inside a fork, the family's name before the fork's. Outside one it is the workspace's own + * name and stays until `wsButton`. */ + familyName: boolean + /** The item's path. Dropped only for an item that has a summary: the summary is what a + * person calls the thing, while its path is where it is filed. Without one, the path is the + * item's only name and stays. */ + path: boolean + forkName: boolean + /** The workspace part as its disc alone, still leading home, beside its picker's chevron. */ + wsButton: boolean + /** The folders between the first one and the name; collapsed, they read as `…`. */ + middleLevels: boolean +} + +export type BarStage = TrailStage & { label: string } + +export const BAR_STAGES: BarStage[] = [ + { + label: 'Full', + familyName: true, + path: true, + forkName: true, + wsButton: false, + middleLevels: true + }, + { + label: 'Family name dropped', + familyName: false, + path: true, + forkName: true, + wsButton: false, + middleLevels: true + }, + { + label: 'Path dropped for the summary', + familyName: false, + path: false, + forkName: true, + wsButton: false, + middleLevels: true + }, + { + label: 'Fork name dropped', + familyName: false, + path: false, + forkName: false, + wsButton: false, + middleLevels: true + }, + { + label: 'Workspace as its disc', + familyName: false, + path: false, + forkName: false, + wsButton: true, + middleLevels: true + }, + { + label: 'Middle folders collapsed', + familyName: false, + path: false, + forkName: false, + wsButton: true, + middleLevels: false + } +] + +export type Part = 'family' | 'fork' | 'summary' | 'name' + +/** The trail at each stage with its names at their floors, and each name's own width. */ +export type TrailMeasures = { trail: number[]; family: number; fork: number; name: number } + +/** The width a part may truncate to before the next stage drops something whole. The summary's + * is wide: below it the path goes rather than the summary losing most of what it says. */ +export const FLOOR: Record<Part, number> = { family: 56, fork: 56, summary: 200, name: 160 } +/** Past the last stage and fold, the item's name and then its summary keep this much before the + * folders give any. */ +export const SQUEEZED_FLOOR = 40 + +/** Middle folders collapsed to one `…`; the first folder and the name always stay. */ +export function shownPathLevels(levels: string[], stage: TrailStage): string[] { + const scopes = levels.slice(0, -1) + if (stage.middleLevels || scopes.length <= 1) return levels + return [scopes[0], '…', levels[levels.length - 1]] +} + +/** Whether a part is on screen at a stage. A natural width of 0 means the page has no such part. */ +export function partVisible( + part: Part, + stage: BarStage, + natural: Record<Part, number>, + summaryNamesItem = true +): boolean { + if (natural[part] <= 0) return false + switch (part) { + case 'summary': + return true + case 'family': + // Outside a fork the family's name is the workspace's: it goes only with the whole part. + return !stage.wsButton && (stage.familyName || natural.fork <= 0) + case 'fork': + return !stage.wsButton && stage.forkName + case 'name': + return stage.path || natural.summary <= 0 || !summaryNamesItem + } +} + +export type BarMeasure = { + barWidth: number + /** The bar's padding and the sidebar handle: what is there at every stage. */ + chrome: number + /** Per stage: the breadcrumb with each name at its floor. */ + trail: number[] + /** Per stage: the summary at its floor with the separator before it, 0 where there is none. */ + summary: number[] + /** Per fold level: the actions with the gap before them, undefined for a level not yet seen. */ + actions: (number | undefined)[] + /** How many levels past the full row the page's actions can fold through. */ + folds: number + /** How many of those levels fold before the breadcrumb drops anything: buttons that are there + * only while there is room for everything. */ + earlyFolds?: number + natural: Record<Part, number> + /** The summary is the item's own text, not a placeholder offering to add one: only then does it + * name the item well enough for the path to go. */ + summaryNamesItem?: boolean +} + +export type BarFit = { + stage: number + fold: number + /** Max widths for the parts that give width, in the order they give it. */ + caps: Partial<Record<Part, number>> + /** Even the name at its squeezed floor does not fit: the folders above it truncate too. */ + scopesGive: boolean +} + +/** + * Flex shrinks every part in proportion, so however lopsided the factors, the name gives a few + * pixels while the summary still has room, and a few pixels are an ellipsis. The parts are rigid + * instead and the deficit is taken from them in a strict order, each down to its floor. + */ +export function fitBar(m: BarMeasure): BarFit { + // A level not yet seen is assumed as narrow as the next one folded further: trying it is how it + // gets measured, and once it has been, the bar never picks it again unless it fits. + const actionsAt = (fold: number) => { + for (let f = fold; f < m.actions.length; f++) + if (m.actions[f] !== undefined) return m.actions[f]! + return 0 + } + const last = BAR_STAGES.length - 1 + const floorWidth = (s: number, f: number) => + m.chrome + (m.trail[s] ?? 0) + (m.summary[s] ?? 0) + actionsAt(f) + + const early = Math.min(m.earlyFolds ?? 0, m.folds) + let stage = last + let fold = m.folds + choose: { + for (let f = 0; f < early; f++) { + if (floorWidth(0, f) <= m.barWidth) { + stage = 0 + fold = f + break choose + } + } + for (let s = 0; s <= last; s++) { + if (floorWidth(s, early) <= m.barWidth) { + stage = s + fold = early + break choose + } + } + // The other levels fold only once the breadcrumb has given all it can, so a narrowing bar + // only ever loses things: the parts it dropped do not come back when the buttons fold. + for (let f = early + 1; f <= m.folds; f++) { + if (floorWidth(last, f) <= m.barWidth) { + fold = f + break choose + } + } + } + + const at = BAR_STAGES[stage] + // The summary gives last: it is what a person calls the item, so the path's name goes first. + const parts = (['family', 'fork', 'name', 'summary'] as Part[]).filter((p) => + partVisible(p, at, m.natural, m.summaryNamesItem ?? true) + ) + const slack = (p: Part) => Math.max(0, m.natural[p] - Math.min(m.natural[p], FLOOR[p])) + // The stage was measured with its parts at their floors; this is its width with them whole. + let deficit = floorWidth(stage, fold) + parts.reduce((s, p) => s + slack(p), 0) - m.barWidth + const caps: Partial<Record<Part, number>> = {} + const take = (p: Part, floor: number) => { + if (deficit <= 0 || !parts.includes(p)) return + const current = caps[p] ?? m.natural[p] + const give = Math.min(deficit, Math.max(0, current - Math.min(m.natural[p], floor))) + if (give > 0) caps[p] = current - give + deficit -= give + } + for (const p of parts) take(p, FLOOR[p]) + take('name', SQUEEZED_FLOOR) + take('summary', SQUEEZED_FLOOR) + return { stage, fold, caps, scopesGive: deficit > 0 } +} diff --git a/frontend/src/lib/components/preview/FlowPreviewStatus.svelte b/frontend/src/lib/components/preview/FlowPreviewStatus.svelte index 68587fbf24..9d794828d8 100644 --- a/frontend/src/lib/components/preview/FlowPreviewStatus.svelte +++ b/frontend/src/lib/components/preview/FlowPreviewStatus.svelte @@ -1,6 +1,5 @@ <script lang="ts"> import type { CompletedJob, QueuedJob } from '$lib/gen' - import { base } from '$lib/base' import JobStatus from '../JobStatus.svelte' import { ExternalLinkIcon } from 'lucide-svelte' @@ -32,7 +31,7 @@ <a rel="noreferrer" target="_blank" - href="{base}/run/{job?.id}?workspace={job?.workspace_id}" + href="/run/{job?.id}?workspace={job?.workspace_id}" > {truncateRev(job?.id, 8)} <ExternalLinkIcon size={14} class="inline mb-1 ml-1" /> diff --git a/frontend/src/lib/components/raw_apps/RawAppBackgroundRunner.svelte b/frontend/src/lib/components/raw_apps/RawAppBackgroundRunner.svelte index 9f675664b1..487da15f1f 100644 --- a/frontend/src/lib/components/raw_apps/RawAppBackgroundRunner.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppBackgroundRunner.svelte @@ -5,7 +5,7 @@ import type { JobById } from '../apps/types' import { JobService } from '$lib/gen' import type { Runnable } from './rawAppPolicy' - import { RAW_APP_PREVIEW_RELAY } from './utils' + import { RAW_APP_PREVIEW_RELAY, rawAppPreviewModules } from './utils' import { undefinedIfEmpty } from '$lib/utils' interface Props { @@ -16,6 +16,8 @@ jobsById?: Record<string, JobById> editor: boolean workspace: string + /** Editor only: identity the previewed runnables run as (see `appPreviewOnBehalfOf`). */ + previewOnBehalfOf?: string /** * Restrict waitJob/getJob/streamJob to job ids launched by this app * instance (WIN-2006): a SANDBOXED bundle must not read arbitrary @@ -45,6 +47,7 @@ jobsById = $bindable({}), editor, workspace, + previewOnBehalfOf, gateJobIds = true, extraSourceWindow }: Props = $props() @@ -155,9 +158,13 @@ ) ) : undefined, - force_viewer_delete_after_secs: editor ? runnable?.delete_after_secs : undefined + force_viewer_delete_after_secs: editor ? runnable?.delete_after_secs : undefined, + on_behalf_of: editor ? previewOnBehalfOf : undefined, + viewer_data_access: editor ? runnable?.viewer_data_access || undefined : undefined }, - undefined + undefined, + undefined, + editor ? rawAppPreviewModules(runnables, runnable_id) : undefined ) launchedJobs.add(uuid) let job: JobById = { component: runnable_id, created_at: Date.now(), job: uuid } diff --git a/frontend/src/lib/components/raw_apps/RawAppDataTableDrawer.svelte b/frontend/src/lib/components/raw_apps/RawAppDataTableDrawer.svelte index af0af7ed5b..0ebb67094b 100644 --- a/frontend/src/lib/components/raw_apps/RawAppDataTableDrawer.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppDataTableDrawer.svelte @@ -14,6 +14,7 @@ ADMIN_DATATABLE_ROLE, datatableNameTakesRole, defaultMigrationRole, + namedDefaultRole, type DbInput } from '../dbTypes' import type { PendingRowAction, SelectedTable } from '../DBManager.svelte' @@ -173,15 +174,15 @@ return rolesOfCurrent?.permissioned ? selectedRole : undefined } const entry = datatableTree.current.find((t) => t.datatable_name === datatable) - return entry?.permissioned ? entry.default_role : undefined + return entry?.permissioned ? namedDefaultRole(entry.default_role) : undefined } function defaultRoleOf(datatable: string): string | undefined { if (datatable === selectedDatatable && rolesOfCurrent?.permissioned) { - return rolesOfCurrent.default_role + return namedDefaultRole(rolesOfCurrent.default_role) } const entry = datatableTree.current.find((t) => t.datatable_name === datatable) - return entry?.permissioned ? entry.default_role : undefined + return entry?.permissioned ? namedDefaultRole(entry.default_role) : undefined } const tableDatatable = (t: SelectedTable) => t.datatable ?? selectedDatatable diff --git a/frontend/src/lib/components/raw_apps/RawAppEditor.svelte b/frontend/src/lib/components/raw_apps/RawAppEditor.svelte index d0d1b40de1..2006aef442 100644 --- a/frontend/src/lib/components/raw_apps/RawAppEditor.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppEditor.svelte @@ -21,6 +21,7 @@ genWmillTs, normalizeRawAppRuntimeLogs, createRawAppBuildTracker, + RAW_APP_BUILD_WAIT_MS, type Runnable, type RawAppRuntimeLogEntry, type RawAppRuntimeLogRequester, @@ -51,6 +52,8 @@ import { captureScale, MAX_IMAGE_EDGE } from '../copilot/chat/imageUtils' import { rawAppLintStore } from './lintStore' import { dbSchemas, userStore } from '$lib/stores' + import { useActingUser } from '$lib/actingUser.svelte' + import { appPreviewOnBehalfOf } from '$lib/utils/previewOnBehalfOf' import RawAppSdkConsent from './RawAppSdkConsent.svelte' import { hasStoredSdkConsent, @@ -87,8 +90,11 @@ import { randomSecret, randomUUID } from '$lib/utils/uuid' import { editorFontSize } from '$lib/editorFontSize.svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + import { useOperatorBuilderApps } from '$lib/operatorWriteRights' + import { conformBuilderAppPolicy } from './builderAppPolicy' const operatingWorkspace = useOperatingWorkspace() + const operatorBuilderApps = useOperatorBuilderApps() interface Props { files?: Record<string, string> @@ -254,6 +260,8 @@ const opWorkspace = $derived(autosaveWorkspace ?? $operatingWorkspace) // Everything under the editor acts on it too (see operatingWorkspace.svelte.ts). setOperatingWorkspace(() => opWorkspace) + const operatingUser = useActingUser(() => opWorkspace) + let previewOnBehalfOf = $derived(appPreviewOnBehalfOf(operatingUser.current, policy)) // The path autosaves land on, which is what the session preview loads the app by. const draftStoragePath = $derived(autosavePath ?? liveEditorDraftStoragePath) @@ -412,6 +420,11 @@ if (url) URL.revokeObjectURL(url) } }) + // The deploy panel cannot switch Viewer mode off, nor drop the identity an app another user + // deployed carries, so the editor conforms the policy as soon as it opens. + $effect(() => { + if ($operatorBuilderApps && policy) conformBuilderAppPolicy(policy, $userStore) + }) // An app with sandbox isolation previews the way it runs once deployed: in the // served, opaque-origin shell, framed with the deployed wrapper's flags. The nonce // in its URL authenticates its `windmill:ready`, as in `RawAppPreview`. @@ -451,7 +464,7 @@ addEventListener('message', function (e) { n.hidden = !e.data.text } else if (e.source === opener) frame.postMessage(e.data, '*') }) -<\/script></head><body><div id="n" hidden></div><iframe src="${window.location.origin}${sandboxedShellUrl}" sandbox="${RAW_APP_SANDBOX_FLAGS}" referrerpolicy="no-referrer"></iframe></body></html>` +<\/script></head><body><div id="n" hidden></div><iframe src="${window.location.origin}${sandboxedShellUrl}" sandbox="${RAW_APP_SANDBOX_FLAGS}" allow="clipboard-read; clipboard-write; fullscreen" referrerpolicy="no-referrer"></iframe></body></html>` ], { type: 'text/html' } ) @@ -488,6 +501,19 @@ addEventListener('message', function (e) { // Latest UI Builder error; cleared on next successful build. let buildError = $state<string | undefined>(undefined) const buildTracker = createRawAppBuildTracker() + // The preview shell can be ready before the UI Builder has the files, so a fresh + // editor counts as building: reads made then would see an empty page. + buildTracker.start() + const BUILD_PENDING_TEXT = `The app is still building (or its build never started, e.g. no index entrypoint file): no build result arrived within ${RAW_APP_BUILD_WAIT_MS / 1000} seconds, so the preview shows an older build or nothing yet. Call get_app_runtime_logs to check the build, then retry.` + // A failed build never reaches the preview, which keeps the last good one, if any. + const buildFailedText = (error: string) => + `The latest build failed, so the preview does not include the latest edits (it shows the last build that succeeded, or nothing if none has). Fix the build first. Build error:\n${error}` + const SDK_CONSENT_PENDING_TEXT = + 'The preview is waiting for the user to approve the permissions the app declares in policy.frontend_sdk_scopes, so the app code is not running and the page is empty. This is not a bug in the app: do not change the code. Ask the user to approve the permissions in the preview, then retry.' + const SDK_STARTING_TEXT = + 'The preview is still loading the permissions the app declares in policy.frontend_sdk_scopes, so the app code has not started yet. Retry in a moment.' + const VIEWER_PENDING_TEXT = + 'The preview is still looking up the viewer the app receives in window.ctx, so the app code has not started yet. This is not a bug in the app: do not change the code. Retry in a moment.' const PREVIEW_SETTLE_MS = 1000 let editorDestroyed = false // Latest uncaught runtime error thrown by the rendered app; cleared on next build. @@ -496,7 +522,7 @@ addEventListener('message', function (e) { // entrypoint defines a component without ever mounting it. Cleared on next build. let emptyRender = $state(false) // The repair hint above has to match the app's framework: only React apps have - // an `index.tsx` and `createRoot`; Svelte and Vue mount from `index.ts`. Keyed + // an `index.tsx` and `createRoot`; Svelte mounts from `index.ts`. Keyed // off file extensions rather than exact template filenames, which users rename. let mountHint = $derived.by(() => { const paths = Object.keys(files ?? {}).map((p) => p.replace(/^\//, '')) @@ -507,9 +533,6 @@ addEventListener('message', function (e) { call: "mount(App, { target: document.getElementById('root')! })" } } - if (paths.some((p) => p.endsWith('.vue'))) { - return { entrypoint: entrypoint ?? 'index.ts', call: "createApp(App).mount('#root')" } - } return { entrypoint: entrypoint ?? 'index.tsx', call: "createRoot(document.getElementById('root')!).render(<App />)" @@ -880,6 +903,7 @@ addEventListener('message', function (e) { content: runnable.inlineScript.content ?? '' } } + if (runnable.viewer_data_access) backendRunnable.viewerDataAccess = true } else if (isRunnableByPath(runnable)) { // Determine type based on runType if (runnable.runType === 'flow') { @@ -1183,6 +1207,9 @@ addEventListener('message', function (e) { content: runnable.inlineScript.content, language: runnable.inlineScript.language }, + ...((runnable.viewerDataAccess ?? runnables[key]?.viewer_data_access) && { + viewer_data_access: true + }), fields: runnable.staticInputs ? Object.fromEntries( Object.entries(runnable.staticInputs).map(([k, v]) => [ @@ -1792,12 +1819,13 @@ addEventListener('message', function (e) { } function syncExternalPreview() { - if (previewSdkPending || !externalPreviewReady) return + if (previewSdkPending || previewUserPending || !externalPreviewReady) return if (lastBuild) { postToExternalPreview({ type: 'preview', css: lastBuild.css, js: lastBuild.js, + ctx: previewCtx(), sdk: previewSdk, storage: previewStorage() }) @@ -1811,18 +1839,41 @@ addEventListener('message', function (e) { // Between dropping a credential and settling its replacement the shell stays // blank; whichever settles last — the mint or the shell's own `load` — starts // the app. Same for a shell still reloading: it replays once ready. - if (previewSdkPending || !previewIframeLoaded) return + if (previewSdkPending || previewUserPending || !previewIframeLoaded) return runtimeError = undefined emptyRender = false postToPreview({ type: 'preview', css: build.css, js: build.js, + ctx: previewCtx(), sdk: previewSdk, storage: previewStorage() }) } + // The deployed app's `window.ctx`: the viewer's membership in the app's workspace. + function previewCtx() { + return $state.snapshot({ ctx: operatingUser.current, workspace: opWorkspace }) + } + + // A build fed before the viewer is known keeps that viewer until the next one. Outside + // the navigation workspace the viewer is looked up; in it, `$userStore` still holds the + // previous workspace's membership right after a switch. A failed lookup also settles + // this: the app then runs with no viewer, as we don't know who it is. + const previewUserPending = $derived( + !!opWorkspace && + (!operatingUser.resolved(opWorkspace) || + (!!operatingUser.current && operatingUser.current.workspace_id !== opWorkspace)) + ) + $effect(() => { + if (previewUserPending) return + untrack(() => { + if (lastBuild) feedPreviewIframe(lastBuild) + syncExternalPreview() + }) + }) + // The shell seeds a fresh document's storage shim from this; unsandboxed // previews use real storage and get none. function previewStorage() { @@ -1839,13 +1890,15 @@ addEventListener('message', function (e) { syncExternalPreview() } - onDestroy(() => { - // Don't leave a detached preview behind when the editor unmounts: it - // would stop receiving builds and, once refreshed, has no opener to - // re-feed it — a permanently blank orphan. + // Don't leave a detached preview behind when the editor goes away, by + // unmounting or by its tab reloading or closing (`pagehide`, which skips + // `onDestroy`): it would stop receiving builds, and its document is a blob + // URL owned by this page, so refreshing it gives "not found". + function closeExternalPreview() { if (externalPreviewWindow && !externalPreviewWindow.closed) externalPreviewWindow.close() externalPreviewWindow = null - }) + } + onDestroy(closeExternalPreview) function openExternalPreview() { // Reuse an already-open window instead of spawning duplicates. @@ -1977,6 +2030,19 @@ addEventListener('message', function (e) { // Live DOM inspection for the session chat. The element is re-read on every call, // so the model always sees the current render. const requestDomQuery: RawAppDomRequester = async (query: RawAppDomQuery) => { + await buildTracker.wait() + if (editorDestroyed) return undefined + if (buildTracker.pending) return { text: BUILD_PENDING_TEXT } + if (sdkPrompt) return { text: SDK_CONSENT_PENDING_TEXT } + if (previewSdkPending) return { text: SDK_STARTING_TEXT } + if (previewUserPending) return { text: VIEWER_PENDING_TEXT } + const res = await readPreviewDom(query) + return res && buildError !== undefined + ? { text: `${buildFailedText(buildError)}\n\n${res.text}` } + : res + } + + const readPreviewDom: RawAppDomRequester = async (query: RawAppDomQuery) => { const selector = query.selector?.trim() const res = await requestFromPreview('domRead', { selector }) if (!res) return undefined @@ -2143,6 +2209,13 @@ addEventListener('message', function (e) { // reconstructs the DOM into an SVG foreignObject, and a WebGL canvas is only // captured when its context was created with preserveDrawingBuffer. const captureScreenshot: RawAppScreenshotRequester = async () => { + await buildTracker.wait() + if (editorDestroyed) throw new Error('The app preview was closed') + if (buildTracker.pending) throw new Error(BUILD_PENDING_TEXT) + if (sdkPrompt) throw new Error(SDK_CONSENT_PENDING_TEXT) + if (previewSdkPending) throw new Error(SDK_STARTING_TEXT) + if (previewUserPending) throw new Error(VIEWER_PENDING_TEXT) + if (buildError !== undefined) throw new Error(buildFailedText(buildError)) const body = await requestFromPreview('elementRect', { selector: 'body' }) if (!body?.rect) throw new Error('App preview is not ready') const { width, height } = body.rect @@ -2512,7 +2585,7 @@ addEventListener('message', function (e) { } </script> -<svelte:window onmessage={listener} onkeydown={handleKeydown} /> +<svelte:window onmessage={listener} onkeydown={handleKeydown} onpagehide={closeExternalPreview} /> <DarkModeObserver bind:darkMode on:change={() => { @@ -2528,6 +2601,7 @@ addEventListener('message', function (e) { bind:jobsById {runnables} {path} + {previewOnBehalfOf} gateJobIds={sandboxed} extraSourceWindow={() => externalPreviewWindow} /> @@ -2735,6 +2809,7 @@ addEventListener('message', function (e) { {#if selectedRunnable !== undefined} <RawAppInlineScriptsPanel appPath={path} + {previewOnBehalfOf} {selectedRunnable} bind:runnables onSelectionChange={(selection) => { @@ -2819,6 +2894,8 @@ addEventListener('message', function (e) { title="Replay the last build into the preview" aria-label="Rebuild" onClick={() => { + // Retries a viewer lookup that failed; the hold replays the build once it answers. + operatingUser.forgetFailures() if (lastBuild) { feedPreviewIframe(lastBuild) } @@ -2860,6 +2937,7 @@ addEventListener('message', function (e) { title="App preview" src={previewShellUrl} sandbox={sandboxed ? RAW_APP_SANDBOX_FLAGS : undefined} + allow="clipboard-read; clipboard-write; fullscreen" referrerpolicy={sandboxed ? 'no-referrer' : undefined} class="w-full flex-1 block" ></iframe> diff --git a/frontend/src/lib/components/raw_apps/RawAppEditorHeader.svelte b/frontend/src/lib/components/raw_apps/RawAppEditorHeader.svelte index c8e9106943..b7ce8d7684 100644 --- a/frontend/src/lib/components/raw_apps/RawAppEditorHeader.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppEditorHeader.svelte @@ -1,6 +1,5 @@ <script lang="ts"> import { Drawer, DrawerContent } from '$lib/components/common' - import { base } from '$lib/base' import RawAppRecordSession from '$lib/components/workspaceSettings/RawAppRecordSession.svelte' import Button from '$lib/components/common/button/Button.svelte' import { isMac, userPathPrefix, emptyString } from '$lib/utils' @@ -81,7 +80,7 @@ useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' import PageHeaderContent from '$lib/components/PageHeaderContent.svelte' - import { pageHeader, PHONE_BAR } from '$lib/components/pageHeaderRegistry.svelte' + import { pageHeader } from '$lib/components/pageHeaderRegistry.svelte' import PathEditPopover from '$lib/components/PathEditPopover.svelte' const operatingWorkspace = useOperatingWorkspace() @@ -207,7 +206,7 @@ let { summary = $bindable(), - policy = $bindable(), + policy, diffDrawer = undefined, savedApp = $bindable(undefined), version = $bindable(undefined), @@ -319,20 +318,15 @@ // Top-bar responsive collapse — container width, not viewport. let topbarWidth = $state(0) - // In the page header the buttons share the row with the breadcrumb, so they collapse sooner: - // the trail and the summary take ~430px of the same row, and the whole group — the menu, Diff, - // Jobs, Export, AI and Deploy — is ~560px. - const compactBelow = $derived(ownsPageHeader ? 1350 : 720) - const compactTopbar = $derived.by(() => { - const w = ownsPageHeader ? pageHeader.barWidth : topbarWidth - return w > 0 && w < compactBelow - }) - // A phone's bar keeps the trail, the file sidebar's toggle, Diff and Deploy. AI stands down — - // the sidebar's own Ask AI is the way in at that width — while Jobs and the export are already - // in the menu, Jobs from `compactTopbar` (true at any phone width) and the export always. - const phoneTopbar = $derived( - ownsPageHeader && pageHeader.barWidth > 0 && pageHeader.barWidth < PHONE_BAR + // In the page header the bar folds the buttons (`actionFolds` below), once its breadcrumb has + // given all it can; anywhere else this editor's own top bar is theirs alone. + const compactTopbar = $derived( + ownsPageHeader ? pageHeader.actionFold >= 1 : topbarWidth > 0 && topbarWidth < 720 ) + // The second fold keeps the trail, the file sidebar's toggle, Diff and Deploy. AI stands down — + // the sidebar's own Ask AI is the way in at that width — while Jobs and the export are already + // in the menu, Jobs from `compactTopbar` (true at the second fold too) and the export always. + const phoneTopbar = $derived(ownsPageHeader && pageHeader.actionFold >= 2) // Top-bar button size + bar height. Condensed (session preview) uses the // smallest well-supported unified size (`sm`) so the bar is thinner. @@ -352,8 +346,12 @@ saveDrawerOpen = false } - async function computeTriggerables() { - policy = await updateRawAppPolicy(runnables, policy) + // Returns a copy: `policy` is the editor's own object, which the Deploy panel's + // instant toggles mutate in place. Reassigning it would detach the panel from the + // editor, so later toggles would never reach the preview. After a successful save, + // copy only `triggerables_v2` back so the editor's value matches what was deployed. + function policyWithTriggerables() { + return updateRawAppPolicy(runnables, policy) } async function createApp(path: string) { @@ -364,9 +362,9 @@ if (!policy.execution_mode) { policy.execution_mode = 'publisher' } - await computeTriggerables() try { const { js, css } = await getBundle() + const deployedPolicy = await policyWithTriggerables() await AppService.createAppRaw({ workspace: opWorkspace!, formData: { @@ -374,7 +372,7 @@ value: app, path, summary: summary, - policy, + policy: deployedPolicy, deployment_message: deploymentMsg, custom_path: customPath, preserve_on_behalf_of: preserveOnBehalfOf || undefined, @@ -384,6 +382,7 @@ css } }) + policy.triggerables_v2 = deployedPolicy.triggerables_v2 // New path now exists server-side — drop the autocomplete cache so // it shows up immediately instead of after the 60s TTL. invalidateWorkspacePaths(opWorkspace!) @@ -391,7 +390,7 @@ summary: summary, value: structuredClone(stateSnapshot(app)), path: path, - policy: policy, + policy: deployedPolicy, custom_path: customPath, labels: $state.snapshot(labels) } @@ -589,10 +588,10 @@ return } const { js, css } = await getBundle() - await computeTriggerables() if (!policy.execution_mode) { policy.execution_mode = 'publisher' } + const deployedPolicy = await policyWithTriggerables() const deployed = await AppService.updateAppRaw({ workspace: opWorkspace!, path: appPath!, @@ -600,7 +599,7 @@ app: { value: app!, summary: summary, - policy, + policy: deployedPolicy, path: npath, deployment_message: deploymentMsg, preserve_on_behalf_of: preserveOnBehalfOf || undefined, @@ -614,12 +613,13 @@ css } }) + policy.triggerables_v2 = deployedPolicy.triggerables_v2 invalidateWorkspacePaths(opWorkspace!) savedApp = { summary: summary, value: structuredClone(stateSnapshot(app)), path: npath, - policy, + policy: deployedPolicy, custom_path: customPath, labels: $state.snapshot(labels) } @@ -655,12 +655,13 @@ } async function setPublishState(message?: string) { - await computeTriggerables() + const nextPolicy = await policyWithTriggerables() await AppService.updateApp({ workspace: opWorkspace!, path: appPath, - requestBody: { policy } + requestBody: { policy: nextPolicy } }) + policy.triggerables_v2 = nextPolicy.triggerables_v2 if (message) { sendUserToast(message) } else if (policy.execution_mode == 'anonymous') { @@ -903,13 +904,13 @@ </span> <span> Stop recording, then <b>Download</b> the JSON. It is self-contained: open it on - <a href="{base}/replay" target="_blank" rel="noreferrer" class="text-blue-500 underline"> - {base}/replay + <a href="/replay" target="_blank" rel="noreferrer" class="text-blue-500 underline"> + /replay </a> — a public page that needs no login and can be embedded in an iframe. Host the JSON anywhere it can be fetched (S3, GitHub raw, your docs site) and link - <span class="font-mono">{base}/replay?src=<url></span> to have it load itself. Windmill - keeps no copy. + <span class="font-mono">/replay?src=<url></span> to have it load itself. Windmill keeps + no copy. </span> </div> <div class="flex-1 min-h-0"> @@ -950,10 +951,12 @@ // rename popover is open so the trail holds still as the user types. kind: 'app', path: pathSnapshot ?? (newEditedPath || appPath || newPath || undefined), + summary, summaryContent: appSummary, pathTrigger: rawAppPathTrigger }} actions={rawAppHeaderActions} + actionFolds={2} contexts={headerContexts} separator="none" /> diff --git a/frontend/src/lib/components/raw_apps/RawAppInlineScriptEditor.svelte b/frontend/src/lib/components/raw_apps/RawAppInlineScriptEditor.svelte index d7ae7b2245..844a447d51 100644 --- a/frontend/src/lib/components/raw_apps/RawAppInlineScriptEditor.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppInlineScriptEditor.svelte @@ -5,7 +5,8 @@ import Button from '$lib/components/common/button/Button.svelte' import type { Preview, ScriptLang } from '$lib/gen' import { createEventDispatcher, onDestroy, onMount, untrack } from 'svelte' - import { Trash2, Bug, Terminal } from 'lucide-svelte' + import { Trash2, Bug, Terminal, Paintbrush } from 'lucide-svelte' + import { getModifierKey } from '$lib/utils' import { inferArgs, inferAssets } from '$lib/infer' import type { Schema } from '$lib/common' import Editor from '$lib/components/Editor.svelte' @@ -17,6 +18,7 @@ import CacheTtlPopup from '../apps/editor/inlineScriptsPanel/CacheTtlPopup.svelte' import TagPopup from '../apps/editor/inlineScriptsPanel/TagPopup.svelte' import DeleteAfterUsePopup from './DeleteAfterUsePopup.svelte' + import ViewerDataAccessPopup from './ViewerDataAccessPopup.svelte' import { computeFields } from '../apps/editor/inlineScriptsPanel/utils' import EditorBar, { EDITOR_BAR_HELPERS_INLINE_THRESHOLD } from '../EditorBar.svelte' import { LanguageIcon } from '../common/languageIcons' @@ -52,6 +54,7 @@ editor?: any | undefined lastDeployedCode?: string | undefined delete_after_secs?: number | undefined + viewer_data_access?: boolean | undefined /** Called when code is selected in the editor */ onSelectionChange?: ( selection: { @@ -74,9 +77,17 @@ editor = $bindable(undefined), lastDeployedCode, onSelectionChange, - delete_after_secs = $bindable() + delete_after_secs = $bindable(), + viewer_data_access = $bindable() }: Props = $props() + // The asset parser misses a chained `wmill.datatable('x')`...``, so the source is matched too. + const readsData = $derived( + (inlineScript?.assets?.some((a) => ['datatable', 'ducklake', 's3object'].includes(a.kind)) ?? + false) || + /datatable\s*\(|datatable:\/\/|s3:\/\/|s3_?file|S3Object/i.test(inlineScript?.content ?? '') + ) + const operatingWorkspace = useOperatingWorkspace() let opWs = $derived($operatingWorkspace) @@ -620,6 +631,9 @@ /> {/if} <div class="flex w-full flex-row gap-2 items-center justify-end"> + {#if readsData || viewer_data_access} + <ViewerDataAccessPopup bind:viewer_data_access /> + {/if} {#if inlineScript} <TagPopup bind:tag={inlineScript.tag} /> <CacheTtlPopup bind:cache_ttl={inlineScript.cache_ttl} /> @@ -627,14 +641,16 @@ <DeleteAfterUsePopup bind:delete_after_secs /> <Button - variant="default" + title={`Format (${getModifierKey()}S)`} + aria-label="Format" + variant="subtle" unifiedSize="sm" on:click={async () => { editor?.format() }} - > - Format - </Button> + endIcon={{ icon: Paintbrush }} + iconOnly + /> </div> </div> diff --git a/frontend/src/lib/components/raw_apps/RawAppInlineScriptRunnable.svelte b/frontend/src/lib/components/raw_apps/RawAppInlineScriptRunnable.svelte index 200e76d85b..86b2ea57ed 100644 --- a/frontend/src/lib/components/raw_apps/RawAppInlineScriptRunnable.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppInlineScriptRunnable.svelte @@ -15,20 +15,22 @@ import { Pane, Splitpanes } from 'svelte-splitpanes' import Tabs from '../common/tabs/Tabs.svelte' import { Tab } from '../common' + import { SQL_LANGUAGES } from '$lib/infer' import RawAppInputsSpecEditor from './RawAppInputsSpecEditor.svelte' import SplitPanesWrapper from '../splitPanes/SplitPanesWrapper.svelte' import SchemaForm from '../SchemaForm.svelte' import RunnableJobPanelInner from '../apps/editor/RunnableJobPanelInner.svelte' import JobLoader from '../JobLoader.svelte' - import type { Job, OpenFlow, ScriptLang } from '$lib/gen' + import { FlowService, type Job, type OpenFlow, type ScriptLang } from '$lib/gen' + import { getScriptByPath } from '$lib/scripts' import { slide } from 'svelte/transition' import { DebugToolbar, DebugPanel, debugState } from '$lib/components/debug' import LogViewer from '$lib/components/LogViewer.svelte' import DisplayResult from '$lib/components/DisplayResult.svelte' import RunButton from '$lib/components/RunButton.svelte' - import { userStore } from '$lib/stores' import { isHubFlowPath } from '$lib/utils' import { sendUserToast } from '$lib/toast' + import { rawAppPreviewModules } from './utils' import { useOperatingUser, useOperatingWorkspace @@ -42,12 +44,17 @@ type RunnableWithInlineScript = RunnableWithFields & { inlineScript?: InlineScript & { language: ScriptLang } delete_after_secs?: number + viewer_data_access?: boolean } export type Runnable = RunnableWithInlineScript | undefined interface Props { runnable: Runnable id: string appPath: string + /** All of the app's runnables, which a test run ships as modules for `./<id>` imports */ + runnables?: Record<string, Runnable> + /** Identity the test runs as instead of the user (see `appPreviewOnBehalfOf`). */ + previewOnBehalfOf?: string lastDeployedCode?: string | undefined /** Called when code is selected in the editor */ onSelectionChange?: ( @@ -61,7 +68,14 @@ ) => void } - let { runnable = $bindable(), id, appPath, onSelectionChange }: Props = $props() + let { + runnable = $bindable(), + id, + appPath, + runnables, + previewOnBehalfOf, + onSelectionChange + }: Props = $props() const dispatch = createEventDispatcher() @@ -80,6 +94,13 @@ } } + // A SQL argument named after a viewer property is most often a per-viewer filter, + // which only a ctx field protects. `wmill app lint` warns on the same names. + const VIEWER_IDENTITY_ARGS = ['username', 'email', 'groups'] + let isSql = $derived( + isRunnableByName(runnable) && SQL_LANGUAGES.includes(runnable.inlineScript?.language ?? '') + ) + let selectedTab = $state('test') let args = $state({}) let hubFlowPreview: OpenFlow | undefined = $state(undefined) @@ -134,15 +155,15 @@ function getCtxValue(expr: string): any { switch (expr) { case 'username': - return $userStore?.username ?? '' + return actingUser?.username ?? '' case 'email': - return $userStore?.email ?? '' + return actingUser?.email ?? '' case 'groups': return actingUser?.groups ?? [] case 'workspace': return opWs ?? '' case 'author': - return $userStore?.email ?? '' // In editor, author is the current user + return actingUser?.email ?? '' // In editor, author is the current user default: return '' } @@ -170,7 +191,15 @@ runnable.inlineScript?.content ?? '', runnable.inlineScript?.language, args, - undefined + undefined, + undefined, + undefined, + undefined, + undefined, + runnables ? rawAppPreviewModules(runnables, id) : undefined, + undefined, + undefined, + { onBehalfOf: previewOnBehalfOf, viewerDataAccess: runnable.viewer_data_access } ) } else if (isRunnableByPath(runnable)) { if (jobLoader && isRunnableByPath(runnable)) { @@ -180,12 +209,42 @@ sendUserToast('Hub flow preview is still loading', true) return } - await jobLoader.runFlowPreview(args, hubFlowPreview, undefined, runnable.path) + await jobLoader.runFlowPreview( + args, + hubFlowPreview, + undefined, + runnable.path, + previewOnBehalfOf + ) + } else if (previewOnBehalfOf) { + // The deployed app runs a path runnable as the app's identity, which a run + // by path cannot ask for: preview the deployed definition instead. + const flow = await FlowService.getFlowByPath({ workspace: opWs!, path: runnable.path }) + await jobLoader.runFlowPreview(args, flow, undefined, runnable.path, previewOnBehalfOf) } else { await jobLoader.runFlowByPath(runnable.path, args) } } else if (runnable.runType == 'script' || runnable.runType == 'hubscript') { - await jobLoader.runScriptByPath(runnable.path, args) + if (previewOnBehalfOf) { + const script = await getScriptByPath(runnable.path, opWs) + await jobLoader.runPreview( + runnable.path, + script.content, + script.language, + args, + script.tag, + script.lock, + script.hash, + undefined, + undefined, + undefined, + undefined, + undefined, + { onBehalfOf: previewOnBehalfOf } + ) + } else { + await jobLoader.runScriptByPath(runnable.path, args) + } } } } @@ -216,6 +275,7 @@ bind:name={runnable.name} bind:fields={runnable.fields} bind:delete_after_secs={runnable.delete_after_secs} + bind:viewer_data_access={runnable.viewer_data_access} onRun={testPreview} on:delete path={appPath} @@ -266,6 +326,7 @@ documentationLink={meta?.['documentationLink']} allowTypeChange={meta?.['allowTypeChange']} displayType + suggestCtx={isSql && VIEWER_IDENTITY_ARGS.includes(k)} /> {/each} </div> diff --git a/frontend/src/lib/components/raw_apps/RawAppInlineScriptsPanel.svelte b/frontend/src/lib/components/raw_apps/RawAppInlineScriptsPanel.svelte index 891fcfa7c8..5a2399457f 100644 --- a/frontend/src/lib/components/raw_apps/RawAppInlineScriptsPanel.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppInlineScriptsPanel.svelte @@ -10,6 +10,7 @@ runnables: Record<string, Runnable> selectedRunnable: string | undefined appPath: string + previewOnBehalfOf?: string /** Called when code is selected in the editor */ onSelectionChange?: ( selection: { @@ -26,6 +27,7 @@ runnables = $bindable(), selectedRunnable = $bindable(), appPath, + previewOnBehalfOf, onSelectionChange }: Props = $props() </script> @@ -38,6 +40,8 @@ {#key selectedRunnable} <RawAppInlineScripRunnable {appPath} + {runnables} + {previewOnBehalfOf} on:createScriptFromInlineScript={(e) => { createScriptFromInlineScript(selectedRunnable ?? '', e.detail, opWs ?? '', appPath) }} diff --git a/frontend/src/lib/components/raw_apps/RawAppInputsSpecEditor.svelte b/frontend/src/lib/components/raw_apps/RawAppInputsSpecEditor.svelte index 67ead38501..859a693ca9 100644 --- a/frontend/src/lib/components/raw_apps/RawAppInputsSpecEditor.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppInputsSpecEditor.svelte @@ -13,6 +13,7 @@ import { fieldTypeToTsType } from '../apps/utils' import type { InputType } from '../apps/inputType' import Select from '$lib/components/select/Select.svelte' + import { Alert } from '$lib/components/common' import { userStore } from '$lib/stores' import { useOperatingUser, @@ -67,6 +68,8 @@ allowTypeChange?: boolean loading?: boolean documentationLink?: string | undefined + /** Warn that this input, left as a frontend input, is open to any value a viewer sends. */ + suggestCtx?: boolean } let { @@ -85,7 +88,8 @@ displayType = false, allowTypeChange = true, loading = false, - documentationLink = undefined + documentationLink = undefined, + suggestCtx = false }: Props = $props() run(() => { @@ -193,6 +197,11 @@ </div> {:else if componentInput?.type === 'user' || componentInput?.type == undefined} <span class="text-2xs italic text-primary">Field's value is a frontend input</span> + {#if suggestCtx} + <Alert type="warning" size="xs" title="A viewer can send any value"> + If this identifies the viewer, switch it to context so the server fills it. + </Alert> + {/if} {/if} {#if componentInput?.type === 'user' && ((fieldType == 'object' && format?.startsWith('resource-') && format !== 'resource-s3_object') || fieldType == 'resource')} <div class="flex flex-row items-center"> diff --git a/frontend/src/lib/components/raw_apps/RawAppPreview.svelte b/frontend/src/lib/components/raw_apps/RawAppPreview.svelte index 9eced2d0e6..36c3fb360c 100644 --- a/frontend/src/lib/components/raw_apps/RawAppPreview.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppPreview.svelte @@ -27,9 +27,10 @@ * (publish flow) needs it to read the app's DOM, which is only possible on * the unsandboxed path. */ oniframe?: (iframe: HTMLIFrameElement | undefined) => void - /** Mirror the app's own route into the page URL's hash, and start from it. Off where - * the app is embedded in a page that is not its own — an AI session preview tab — - * since there the hash belongs to that page and to whichever app was opened first. */ + /** Mirror the app's own route into the page URL's hash, and start from it, and its + * `document.title` into the page's. Off where the app is embedded in a page that is + * not its own — an AI session preview tab — since there the hash and title belong to + * that page and to whichever app was opened first. */ syncHashToUrl?: boolean } @@ -241,6 +242,19 @@ } }) + // The page's own title, put back when the app clears its title or unmounts. Only + // while the tab still shows the app's: anything else is the page's newer title. + let pageTitle = '' + let appTitle: string | undefined = undefined + function setAppTitle(title: string) { + if (document.title !== appTitle) pageTitle = document.title + appTitle = title.trim().slice(0, 200) || pageTitle + document.title = appTitle + } + onMount(() => () => { + if (appTitle !== undefined && document.title === appTitle) document.title = pageTitle + }) + $effect(() => { function handleMessage(event: MessageEvent) { const data = event.data @@ -287,6 +301,8 @@ if (syncHashToUrl && window.location.hash !== newHash) { history.replaceState(null, '', newHash || window.location.pathname) } + } else if (data?.type === 'windmill:title') { + if (syncHashToUrl) setAppTitle(typeof data.title === 'string' ? data.title : '') } else if (runnerFailed) { refuseRequest(event) } else if (!runner) { @@ -335,6 +351,7 @@ title="raw-app" src={iframeSrc} sandbox={sandboxAttr} + allow="clipboard-read; clipboard-write; fullscreen" referrerpolicy={unsandboxed ? undefined : 'no-referrer'} onload={() => (loadedSrc = iframeSrc)} style="display: block; width: 100%; height: 100%; border: none" diff --git a/frontend/src/lib/components/raw_apps/RawAppSdkConsent.svelte b/frontend/src/lib/components/raw_apps/RawAppSdkConsent.svelte index 28940eb02a..babe0b8c85 100644 --- a/frontend/src/lib/components/raw_apps/RawAppSdkConsent.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppSdkConsent.svelte @@ -2,7 +2,7 @@ import { Button } from '$lib/components/common' import Toggle from '$lib/components/Toggle.svelte' import { ShieldCheck } from 'lucide-svelte' - import { sdkScopeDescription, sdkScopeLabel } from './sdkScopes' + import { sdkScopeDescription, sdkScopeLabel, sdkScopesToConfirm } from './sdkScopes' let { scopes, @@ -35,7 +35,7 @@ The app's code will be able to call the Windmill API on your behalf, restricted to: </p> <ul class="flex flex-col gap-2"> - {#each scopes as scope (scope)} + {#each sdkScopesToConfirm(scopes) as scope (scope)} <li class="text-sm"> <span class="font-medium">{sdkScopeLabel(scope)}</span >{#if sdkScopeDescription(scope)}<span class="text-tertiary" diff --git a/frontend/src/lib/components/raw_apps/RawAppTemplatePicker.svelte b/frontend/src/lib/components/raw_apps/RawAppTemplatePicker.svelte index 0928ddce7a..e56ef4bff6 100644 --- a/frontend/src/lib/components/raw_apps/RawAppTemplatePicker.svelte +++ b/frontend/src/lib/components/raw_apps/RawAppTemplatePicker.svelte @@ -14,7 +14,6 @@ import MissingWorkerTagAlert from '$lib/components/jobs/MissingWorkerTagAlert.svelte' import { hasWorkerForTag, queuedWithoutWorkerMessage } from '$lib/components/jobs/missingWorker' import { superadmin, userStore } from '$lib/stores' - import { base } from '$lib/base' import { sendUserToast } from '$lib/toast' import Modal from '$lib/components/common/modal/Modal.svelte' import Button from '$lib/components/common/button/Button.svelte' @@ -25,7 +24,8 @@ import { Alert, Badge } from '$lib/components/common' import { copilotInfo, copilotWorkspace } from '$lib/aiStore' import { loadCopilot } from '$lib/components/copilot/loadCopilot' - import { react18Template, react19Template, svelte5Template } from './templates' + import { BUILDER_FRAMEWORK_TEMPLATES, FRAMEWORK_TEMPLATES } from './templates' + import { conformBuilderAppPolicy } from './builderAppPolicy' import type { Runnable } from './rawAppPolicy' import { type DataTableRef, @@ -46,6 +46,8 @@ import RawAppDataTableDrawer from './RawAppDataTableDrawer.svelte' import FileEditorIcon from './FileEditorIcon.svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + import { useOperatorBuilderApps } from '$lib/operatorWriteRights' + import { prefersSessionHandoff } from '$lib/components/copilot/chat/global/gate' export type RawAppTemplatePickerResult = { files: Record<string, string> @@ -65,11 +67,14 @@ onStart: (result: RawAppTemplatePickerResult, mode: RawAppBuildMode) => void } = $props() - const templates = [ - { name: 'React 19', icon: 'tsx', files: react19Template, recommended: true }, - { name: 'React 18', icon: 'tsx', files: react18Template }, - { name: 'Svelte 5', icon: 'svelte', files: svelte5Template } - ] + const templates = $derived.by(() => { + const files = $operatorBuilderApps ? BUILDER_FRAMEWORK_TEMPLATES : FRAMEWORK_TEMPLATES + return [ + { name: 'React 19', icon: 'tsx', files: files.react19, recommended: true }, + { name: 'React 18', icon: 'tsx', files: files.react18 }, + { name: 'Svelte 5', icon: 'svelte', files: files.svelte5 } + ] + }) let selectedTemplateIndex = $state(0) let selectedDatatable = $state<string | undefined>(undefined) @@ -82,6 +87,7 @@ let dataTableDrawer: RawAppDataTableDrawer | undefined = $state() const operatingWorkspace = useOperatingWorkspace() + const operatorBuilderApps = useOperatorBuilderApps() let opWs = $derived($operatingWorkspace) const datatables = createDatatablesResource(() => opWs) @@ -275,21 +281,28 @@ } }) - // With AI turned off for the workspace there is nothing to choose between. - const aiOffered = $derived(!$copilotInfo.workspaceDisabled) + // With AI turned off for the workspace there is nothing to choose between. A builder is + // offered AI only through a session: the docked app mode writes inline code they cannot save. + const aiOffered = $derived( + !$copilotInfo.workspaceDisabled && + (!$operatorBuilderApps || prefersSessionHandoff($userStore?.operator)) + ) const canStart = $derived( !!templates[selectedTemplateIndex] && !newSchemaAlreadyExists && rolesSettled && accessSettled ) function appPolicy(): Policy { - return { + const policy: Policy = { on_behalf_of: $userStore?.username.includes('@') ? $userStore?.username : `u/${$userStore?.username}`, on_behalf_of_email: $userStore?.email, - execution_mode: 'publisher' + execution_mode: 'publisher', + sandbox: true } + if ($operatorBuilderApps) conformBuilderAppPolicy(policy, $userStore) + return policy } const startCardClasses = @@ -621,7 +634,7 @@ {#if $userStore?.is_admin} Configure AI in <a - href="{base}/workspace_settings?tab=ai" + href="/workspace_settings?tab=ai" target="_blank" class="inline-flex items-center gap-1 font-semibold" >workspace settings <ExternalLinkIcon size={16} /> @@ -629,7 +642,7 @@ {#if $superadmin} or <a - href="{base}/?workspace=admins#superadmin-settings" + href="/?workspace=admins#superadmin-settings" target="_blank" class="inline-flex items-center gap-1 font-semibold" >instance settings <ExternalLinkIcon size={16} /> @@ -638,7 +651,7 @@ {:else if $superadmin} Configure AI in <a - href="{base}/?workspace=admins#superadmin-settings" + href="/?workspace=admins#superadmin-settings" target="_blank" class="inline-flex items-center gap-1 font-semibold" >instance settings <ExternalLinkIcon size={16} /> diff --git a/frontend/src/lib/components/raw_apps/ViewerDataAccessPopup.svelte b/frontend/src/lib/components/raw_apps/ViewerDataAccessPopup.svelte new file mode 100644 index 0000000000..df0215c459 --- /dev/null +++ b/frontend/src/lib/components/raw_apps/ViewerDataAccessPopup.svelte @@ -0,0 +1,86 @@ +<script lang="ts"> + import Toggle from '$lib/components/Toggle.svelte' + import { Button } from '$lib/components/common' + import { AppWindow, UserRound } from 'lucide-svelte' + import Popover from '$lib/components/meltComponents/Popover.svelte' + import { autoPlacement } from '@floating-ui/core' + import { enterpriseLicense } from '$lib/stores' + import { isCloudHosted } from '$lib/cloud' + + interface Props { + viewer_data_access: boolean | undefined + } + + let { viewer_data_access = $bindable() }: Props = $props() + + // It only changes what data table roles and object storage permission rules decide, both + // Enterprise Edition. + const unavailable = $derived( + !$enterpriseLicense + ? 'Data table roles and object storage permission rules are Enterprise Edition features.' + : undefined + ) +</script> + +<Popover + floatingConfig={{ + middleware: [ + autoPlacement({ + allowedPlacements: ['bottom-start', 'bottom-end', 'top-start', 'top-end', 'top', 'bottom'] + }) + ] + }} + closeButton + contentClasses="block text-primary p-4 max-w-sm" +> + {#snippet trigger()} + <Button + nonCaptureEvent={true} + variant={viewer_data_access ? 'accent-secondary' : 'default'} + unifiedSize="sm" + startIcon={{ icon: viewer_data_access ? UserRound : AppWindow }} + iconOnly + title={(viewer_data_access + ? 'Reads data tables and object storage as the viewer' + : 'Reads data tables and object storage as the app') + + (unavailable ? ' (Enterprise Edition)' : '')} + /> + {/snippet} + {#snippet content()} + <Toggle + checked={viewer_data_access ?? false} + disabled={unavailable !== undefined && !viewer_data_access} + eeOnly + on:change={() => { + viewer_data_access = viewer_data_access ? undefined : true + }} + options={{ + right: 'Read data as the viewer', + rightTooltip: + 'Data table roles map who may use a data table to Postgres roles, so grants and row-level security decide what a connection sees. Object storage permission rules decide which paths an identity may list, read and write.', + rightDocumentationLink: + 'https://www.windmill.dev/docs/core_concepts/persistent_storage/data_tables' + }} + /> + <div class="mt-3 flex flex-col gap-2 text-xs text-secondary"> + {#if unavailable} + <p class="text-primary">{unavailable}</p> + {/if} + <p> + By default this runnable reads as the identity the app runs as, the publisher in publisher + mode, for every viewer: a data table connection that names no role holds that identity's + roles, and object storage permission rules are checked against it. + </p> + <p> + Turn this on to read as the person viewing the app instead, so row-level security and + per-user storage paths answer per viewer. Anonymous viewers are refused. Resources, + variables and everything else stay the app's. + </p> + <p> + A data table connection that names a role is that role alone either way, and one whose + default role is admin stays admin, which bypasses row-level security. + {#if isCloudHosted()}Data table roles are only available on self-hosted instances.{/if} + </p> + </div> + {/snippet} +</Popover> diff --git a/frontend/src/lib/components/raw_apps/builderAppPolicy.test.ts b/frontend/src/lib/components/raw_apps/builderAppPolicy.test.ts new file mode 100644 index 0000000000..b24f319240 --- /dev/null +++ b/frontend/src/lib/components/raw_apps/builderAppPolicy.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from 'vitest' +import { conformBuilderAppPolicy } from './builderAppPolicy' + +const builder = { username: 'op', email: 'op@x.dev' } + +describe('conformBuilderAppPolicy', () => { + it('conforms a policy loaded from an app someone else deployed', () => { + const policy: Record<string, any> = { + sandbox: false, + execution_mode: 'viewer', + on_behalf_of: 'u/admin', + on_behalf_of_email: 'admin@x.dev' + } + conformBuilderAppPolicy(policy, builder) + expect(policy).toEqual({ sandbox: true, execution_mode: 'publisher' }) + }) + + it("keeps the builder's own identity", () => { + const policy: Record<string, any> = { + sandbox: true, + on_behalf_of: 'u/op', + on_behalf_of_email: 'op@x.dev' + } + conformBuilderAppPolicy(policy, builder) + expect(policy).toEqual({ sandbox: true, on_behalf_of: 'u/op', on_behalf_of_email: 'op@x.dev' }) + }) +}) diff --git a/frontend/src/lib/components/raw_apps/builderAppPolicy.ts b/frontend/src/lib/components/raw_apps/builderAppPolicy.ts new file mode 100644 index 0000000000..967b56f971 --- /dev/null +++ b/frontend/src/lib/components/raw_apps/builderAppPolicy.ts @@ -0,0 +1,23 @@ +/** + * Brings a raw-app policy in line with what the backend requires of a draft from an operator with + * builder rights (see `docs/operator-builder-rights.md`): sandboxed, never in Viewer mode, and + * running as nobody but its builder. A policy loaded from an app someone else deployed carries + * their identity and may carry either of the other two, so every builder draft writer goes + * through this before saving. Writes only what differs, so it is safe inside an `$effect`. + */ +export function conformBuilderAppPolicy( + policy: Record<string, any>, + user: { username?: string; email?: string } | undefined +): void { + if (policy.sandbox !== true) policy.sandbox = true + if (policy.execution_mode === 'viewer') policy.execution_mode = 'publisher' + const username = user?.username + const self = username?.includes('@') ? username : `u/${username}` + if ( + (policy.on_behalf_of != undefined && policy.on_behalf_of !== self) || + (policy.on_behalf_of_email != undefined && policy.on_behalf_of_email !== user?.email) + ) { + delete policy.on_behalf_of + delete policy.on_behalf_of_email + } +} diff --git a/frontend/src/lib/components/raw_apps/rawAppPolicy.ts b/frontend/src/lib/components/raw_apps/rawAppPolicy.ts index ca84b39a4b..c3ddc5f1a0 100644 --- a/frontend/src/lib/components/raw_apps/rawAppPolicy.ts +++ b/frontend/src/lib/components/raw_apps/rawAppPolicy.ts @@ -29,14 +29,15 @@ export async function updateRawAppPolicy( type RunnableWithInlineScript = RunnableWithFields & { inlineScript?: InlineScript & { language: ScriptLang } delete_after_secs?: number + viewer_data_access?: boolean } export type Runnable = RunnableWithInlineScript | undefined function extraFields( runnable: RunnableWithInlineScript, fields: Record<string, any> -): Partial<Pick<TriggerableV2, 'delete_after_secs' | 'sensitive_inputs' | 'tag'>> { - const out: Partial<Pick<TriggerableV2, 'delete_after_secs' | 'sensitive_inputs' | 'tag'>> = {} +): Partial<TriggerableV2> { + const out: Partial<TriggerableV2> = {} if (typeof runnable.delete_after_secs === 'number' && runnable.delete_after_secs >= 0) out.delete_after_secs = runnable.delete_after_secs const sensitive_inputs = Object.entries(fields) @@ -44,6 +45,9 @@ function extraFields( .filter(Boolean) as string[] if (sensitive_inputs.length > 0) out.sensitive_inputs = sensitive_inputs if (runnable.inlineScript?.tag) out.tag = runnable.inlineScript.tag + // The server honors it on inline runnables only, whose code is deployed with the app. + if (runnable.viewer_data_access === true && isRunnableByName(runnable)) + out.viewer_data_access = true return out } diff --git a/frontend/src/lib/components/raw_apps/sdkScopes.test.ts b/frontend/src/lib/components/raw_apps/sdkScopes.test.ts index f72918e311..c1db89272f 100644 --- a/frontend/src/lib/components/raw_apps/sdkScopes.test.ts +++ b/frontend/src/lib/components/raw_apps/sdkScopes.test.ts @@ -6,33 +6,41 @@ describe('stored frontend SDK consent', () => { beforeEach(() => localStorage.clear()) it('only covers scopes the viewer actually approved', () => { - storeSdkConsent('a@w.dev', 'ws', 'u/a/app', ['users:read']) - expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/app', ['users:read'])).toBe(true) + storeSdkConsent('a@w.dev', 'ws', 'u/a/app', ['jobs:read']) + expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/app', ['jobs:read'])).toBe(true) // The app added a scope after the viewer consented: it must ask again // rather than silently minting a broader token. - expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/app', ['users:read', 'jobs:run'])).toBe(false) + expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/app', ['jobs:read', 'jobs:run'])).toBe(false) }) it('does not leak one viewer or app to another', () => { - storeSdkConsent('a@w.dev', 'ws', 'u/a/app', ['users:read']) - expect(hasStoredSdkConsent('b@w.dev', 'ws', 'u/a/app', ['users:read'])).toBe(false) - expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/other', ['users:read'])).toBe(false) - expect(hasStoredSdkConsent('a@w.dev', 'other', 'u/a/app', ['users:read'])).toBe(false) + storeSdkConsent('a@w.dev', 'ws', 'u/a/app', ['jobs:read']) + expect(hasStoredSdkConsent('b@w.dev', 'ws', 'u/a/app', ['jobs:read'])).toBe(false) + expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/other', ['jobs:read'])).toBe(false) + expect(hasStoredSdkConsent('a@w.dev', 'other', 'u/a/app', ['jobs:read'])).toBe(false) }) it('keeps the editor preview and the deployed app apart, and moves preview consent', () => { - storeSdkConsent('a@w.dev', 'ws', 'u/a/app', ['users:read']) - expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/app', ['users:read'], true)).toBe(false) - storeSdkConsent('a@w.dev', 'ws', 'u/a/draft_1', ['users:read'], true) - expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/draft_1', ['users:read'])).toBe(false) + storeSdkConsent('a@w.dev', 'ws', 'u/a/app', ['jobs:read']) + expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/app', ['jobs:read'], true)).toBe(false) + storeSdkConsent('a@w.dev', 'ws', 'u/a/draft_1', ['jobs:read'], true) + expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/draft_1', ['jobs:read'])).toBe(false) movePreviewSdkConsent('a@w.dev', 'ws', 'u/a/draft_1', 'u/a/real') - expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/real', ['users:read'], true)).toBe(true) - expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/draft_1', ['users:read'], true)).toBe(false) + expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/real', ['jobs:read'], true)).toBe(true) + expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/draft_1', ['jobs:read'], true)).toBe(false) + }) + + it('never asks for the identity scope every token carries', () => { + expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/app', ['users:read'])).toBe(true) + storeSdkConsent('a@w.dev', 'ws', 'u/a/app', ['jobs:read']) + expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/app', ['jobs:read', 'users:read'])).toBe(true) }) it('treats unreadable storage as no consent', () => { localStorage.setItem('wm_sdk_consent:a@w.dev:ws:u/a/app', 'not json') - expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/app', ['users:read'])).toBe(false) + expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/app', ['jobs:read'])).toBe(false) + // Nothing to ask for: storage must not turn that into an empty prompt. + expect(hasStoredSdkConsent('a@w.dev', 'ws', 'u/a/app', ['users:read'])).toBe(true) }) }) diff --git a/frontend/src/lib/components/raw_apps/sdkScopes.ts b/frontend/src/lib/components/raw_apps/sdkScopes.ts index 238f1b7278..a4600979ba 100644 --- a/frontend/src/lib/components/raw_apps/sdkScopes.ts +++ b/frontend/src/lib/components/raw_apps/sdkScopes.ts @@ -1,7 +1,12 @@ // Frontend-SDK permissions for raw apps: the curated scopes an app author may // declare in `policy.frontend_sdk_scopes` (mirrors FRONTEND_SDK_ALLOWED_SCOPES -// in the backend `apps.rs` — both lists must stay in sync), plus the viewer-side -// consent persistence for the permission banner. +// in the backend `apps.rs` — both lists must stay in sync, except for the +// implicit scope below), plus the viewer-side consent persistence for the +// permission banner. + +/** Never toggled nor asked for: every SDK token reaches whoami without it, and whoami + * returns what the bundle already gets in `window.ctx`. */ +export const IMPLICIT_SDK_SCOPE = 'users:read' export const FRONTEND_SDK_SCOPES: { value: string; label: string; description: string }[] = [ { @@ -14,11 +19,6 @@ export const FRONTEND_SDK_SCOPES: { value: string; label: string; description: s label: 'Read jobs and results', description: 'Read jobs and their results, and list the runs the viewer can see' }, - { - value: 'users:read', - label: 'Read your identity', - description: 'Call whoami (Read the viewer username, email, groups, is_super_admin...)' - }, { value: 'resources:read', label: 'Read resources', @@ -59,10 +59,18 @@ function sdkConsentKey(viewer: string, workspace: string, path: string, preview: return `wm_sdk_consent:${preview ? 'p:' : ''}${viewer}:${workspace}:${path}` } +/** The declared scopes the viewer is asked to approve. */ +export function sdkScopesToConfirm(scopes: string[]): string[] { + return scopes.filter((s) => s !== IMPLICIT_SDK_SCOPE) +} + /** True when `approved` (a consent the viewer gave) covers every scope the app now * declares. Fewer scopes need no new consent; one more does. */ export function sdkConsentCovers(approved: unknown, scopes: string[]): boolean { - return Array.isArray(approved) && scopes.every((s) => approved.includes(s)) + const needed = sdkScopesToConfirm(scopes) + return ( + needed.length === 0 || (Array.isArray(approved) && needed.every((s) => approved.includes(s))) + ) } /** True when a previously stored "do not ask again" consent covers every @@ -80,7 +88,7 @@ export function hasStoredSdkConsent( ) return sdkConsentCovers(stored, scopes) } catch (_) { - return false + return sdkConsentCovers(null, scopes) } } diff --git a/frontend/src/lib/components/raw_apps/templates.ts b/frontend/src/lib/components/raw_apps/templates.ts index d6df109262..e54f89fdfa 100644 --- a/frontend/src/lib/components/raw_apps/templates.ts +++ b/frontend/src/lib/components/raw_apps/templates.ts @@ -1,5 +1,5 @@ // The starter app is a tour of what a raw app can do: each card calls one of the -// STARTER_RUNNABLES below through a different `./wmill` export. The three framework +// STARTER_RUNNABLES below through a different `./wmill` export. The framework // variants share `indexCss` and must stay in step with each other and with the runnables. const reactIndex = ` @@ -13,7 +13,7 @@ root.render(<App/>); ` const STATS_SAMPLE_TEXT = - 'Windmill turns scripts into apps. Write the frontend in React, Svelte or Vue, and the backend in TypeScript, Python or any other supported language. Scripts run on workers, and the app calls them like functions.' + 'Windmill turns scripts into apps. Write the frontend in React or Svelte, and the backend in TypeScript, Python or any other supported language. Scripts run on workers, and the app calls them like functions.' const appTsx = `import React, { useState } from 'react' import { backend, backendAsync, getJob, streamJob } from './wmill' @@ -516,230 +516,6 @@ const app = mount(App, { target: document.getElementById("root")! }); export default app; ` -const appVue = `<template> - <main class="app"> - <header class="hero"> - <span class="eyebrow">Windmill app{{ ctx.workspace ? ' · ' + ctx.workspace : '' }}</span> - <h1>{{ firstName ? 'Welcome, ' + firstName : 'Welcome' }}</h1> - <p class="muted"> - A Vue frontend wired to backend runnables. Each card shows one thing an app can do. - Edit App.vue and the runnables to make it yours, or ask the AI to build on it. - </p> - </header> - - <div class="grid"> - <section class="card"> - <div class="card-header"> - <span class="card-step">1</span> - <div> - <h2>Call a backend runnable</h2> - <p class="muted">Runnables are scripts that run on Windmill workers. Call them like async functions; context fields add who is calling.</p> - </div> - </div> - <div class="card-body"> - <form class="row" @submit.prevent="greet"> - <input v-model="name" placeholder="Your name" /> - <button type="submit" :disabled="greetLoading">{{ greetLoading ? 'Running...' : 'Run' }}</button> - </form> - <div class="output"> - <span v-if="greetError" class="error">{{ greetError }}</span> - <template v-else-if="greeting"> - <strong>{{ greeting.message }}</strong> - <span class="muted"> Ran at {{ new Date(greeting.ran_at).toLocaleTimeString() }}</span> - </template> - <span v-else class="muted">The result shows up here.</span> - </div> - </div> - <pre class="snippet"><code>const res = await backend.greet({ name })</code></pre> - </section> - - <section class="card"> - <div class="card-header"> - <span class="card-step">2</span> - <div> - <h2>Use any language</h2> - <p class="muted">Each runnable picks its own language. This one is Python, called the same way.</p> - </div> - </div> - <div class="card-body"> - <textarea rows="4" v-model="text"></textarea> - <div class="row"> - <button @click="analyze" :disabled="statsLoading"> - {{ statsLoading ? 'Analyzing...' : 'Analyze with Python' }} - </button> - </div> - <div v-if="statsError" class="output error">{{ statsError }}</div> - <div v-if="stats" class="stats"> - <div><strong>{{ stats.words }}</strong><span class="muted">words</span></div> - <div><strong>{{ stats.sentences }}</strong><span class="muted">sentences</span></div> - <div><strong>{{ stats.characters }}</strong><span class="muted">characters</span></div> - <div class="tags"> - <span v-for="word in stats.top_words" :key="word" class="tag">{{ word }}</span> - </div> - </div> - </div> - <pre class="snippet"><code>const stats = await backend.word_stats({ text })</code></pre> - </section> - - <section class="card"> - <div class="card-header"> - <span class="card-step">3</span> - <div> - <h2>Run jobs in the background</h2> - <p class="muted">Start long jobs without blocking the UI, then poll their status. Start several at once.</p> - </div> - </div> - <div class="card-body"> - <div class="row"> - <button @click="startJob">Start a job</button> - </div> - <div v-if="jobsError" class="output error">{{ jobsError }}</div> - <ul class="jobs"> - <li v-if="jobs.length === 0" class="muted">No jobs yet.</li> - <li v-for="job in jobs" :key="job.id"> - <span :class="['pill', job.status]">{{ job.status }}</span> - <code :title="job.id">{{ job.id.slice(-8) }}</code> - <span class="muted">{{ job.seconds }}s</span> - <div class="bar"> - <div :class="['bar-fill', job.status]" :style="{ animationDuration: job.seconds + 's' }"></div> - </div> - </li> - </ul> - </div> - <pre class="snippet"><code>const id = await backendAsync.slow_task({ seconds }) -const job = await getJob(id)</code></pre> - </section> - - <section class="card"> - <div class="card-header"> - <span class="card-step">4</span> - <div> - <h2>Stream results</h2> - <p class="muted">A runnable can yield its output bit by bit. Render it as it arrives, like an LLM answer.</p> - </div> - </div> - <div class="card-body"> - <div class="row"> - <button @click="stream" :disabled="streaming">{{ streaming ? 'Streaming...' : 'Start streaming' }}</button> - </div> - <div class="output stream"> - <span v-if="streamError" class="error">{{ streamError }}</span> - <template v-else-if="streamed || streaming"> - {{ streamed }}<span v-if="streaming" class="caret"></span> - </template> - <span v-else class="muted">Streamed text shows up here.</span> - </div> - </div> - <pre class="snippet"><code>await streamJob(id, (u) => append(u.new_result_stream))</code></pre> - </section> - </div> - </main> -</template> - -<script setup> -import { ref } from 'vue' -import { backend, backendAsync, getJob, streamJob } from './wmill' - -// Windmill injects the viewer (absent for anonymous visitors) and the workspace. -const ctx = window.ctx ?? {} -const firstName = (ctx.ctx?.name || ctx.ctx?.username || '').split(' ')[0] - -const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) - -function errorMessage(e) { - return e?.message ?? (typeof e === 'string' ? e : JSON.stringify(e)) -} - -// 1. Call a backend runnable -const name = ref(firstName || 'world') -const greeting = ref() -const greetError = ref() -const greetLoading = ref(false) - -async function greet() { - greetLoading.value = true - greetError.value = undefined - try { - greeting.value = await backend.greet({ name: name.value }) - } catch (e) { - greetError.value = errorMessage(e) - } - greetLoading.value = false -} - -// 2. Use any language -const text = ref(${JSON.stringify(STATS_SAMPLE_TEXT)}) -const stats = ref() -const statsError = ref() -const statsLoading = ref(false) - -async function analyze() { - statsLoading.value = true - statsError.value = undefined - try { - stats.value = await backend.word_stats({ text: text.value }) - } catch (e) { - statsError.value = errorMessage(e) - } - statsLoading.value = false -} - -// 3. Run jobs in the background -const jobs = ref([]) -const jobsError = ref() - -function setStatus(id, status) { - const row = jobs.value.find((r) => r.id === id) - if (row) row.status = status -} - -async function startJob() { - jobsError.value = undefined - try { - const seconds = 2 + Math.floor(Math.random() * 4) - const id = await backendAsync.slow_task({ seconds }) - jobs.value = [{ id, seconds, status: 'queued' }, ...jobs.value].slice(0, 4) - while (true) { - await sleep(500) - const job = await getJob(id) - if (job.type === 'CompletedJob') { - setStatus(id, job.success ? 'success' : 'failure') - return - } - setStatus(id, job.started_at ? 'running' : 'queued') - } - } catch (e) { - jobsError.value = errorMessage(e) - } -} - -// 4. Stream results -const streamed = ref('') -const streamError = ref() -const streaming = ref(false) - -async function stream() { - streamed.value = '' - streamError.value = undefined - streaming.value = true - try { - const id = await backendAsync.stream_text({}) - await streamJob(id, (update) => { - if (update.new_result_stream) streamed.value += update.new_result_stream - }) - } catch (e) { - streamError.value = errorMessage(e) - } - streaming.value = false -} -</script>` - -const indexVue = `import { createApp } from 'vue' -import App from './App.vue' -import "./index.css"; - -createApp(App).mount('#root')` - const indexCss = `/* The app renders inside an iframe whose host page has its own theme the iframe cannot read, so paint an opaque surface here: without one the host's background shows through and dark text lands on it unreadable. */ @@ -1158,27 +934,269 @@ export const svelte5Template = { }` } -export const vueTemplate = { - '/index.ts': indexVue, - '/App.vue': appVue, - '/index.css': indexCss, - '/package.json': `{ - "dependencies": { - "core-js": "3.26.1", - "vue": "3.5.13" - } -}` -} - export const FRAMEWORK_TEMPLATES = { react19: react19Template, react18: react18Template, - svelte5: svelte5Template, - vue: vueTemplate + svelte5: svelte5Template } export type FrameworkKey = keyof typeof FRAMEWORK_TEMPLATES +// An operator with builder rights gets no STARTER_RUNNABLES (they are inline code), so their +// starter calls nothing and explains how to wire runnables already deployed in the workspace. +const BUILDER_USES = [ + { + title: 'Forms for your scripts', + text: 'Give a script a simple form, so anyone can run it without learning Windmill.' + }, + { + title: 'Dashboards', + text: 'Show what a script or flow returns as a table or a chart, fresh every time the app opens.' + }, + { + title: 'Self-service tools', + text: 'Share the app with your team or by link. It runs its scripts as you, so viewers need no access to them.' + } +] + +const BUILDER_SAFETY = + 'Your app can only run scripts and flows already deployed in this workspace, and it runs isolated from each viewer’s session.' + +const BUILDER_STEPS = [ + { + title: 'Pick what it runs', + description: 'Choose a script or flow already deployed in this workspace.', + path: ['Backend panel', '+', 'Select a script or flow'], + note: 'You only see the ones you can read. Each one gets an id, such as a.' + }, + { + title: 'Show it on the page', + description: 'Each runnable becomes a function the page can call by its id.', + note: 'Working with an AI assistant? Tell it the id and what to show. This is the line it writes.', + code: "import { backend } from './wmill'\n\nconst res = await backend.a({ name: 'world' })" + }, + { + title: 'Run long jobs in the background', + description: 'backendAsync starts a job without making the page wait.', + note: 'Check on it with getJob, or follow its output as it runs with streamJob.', + code: "import { backendAsync, getJob } from './wmill'\n\nconst id = await backendAsync.a({ name: 'world' })\nconst job = await getJob(id)" + } +] + +const BUILDER_CONTEXT_CODE = 'const ctx = (window as any).ctx\n\nctx.workspace, ctx.ctx?.username' + +const builderAppTsx = `import React from 'react' +import './index.css' + +// Windmill injects the viewer (absent for anonymous visitors) and the workspace. +const ctx = (window as any).ctx ?? {} +const viewer: { name?: string; username?: string } | undefined = ctx.ctx +const firstName = (viewer?.name || viewer?.username || '').split(' ')[0] + +type Step = { title: string; description: string; note: string; path?: string[]; code?: string } + +const uses: { title: string; text: string }[] = ${JSON.stringify(BUILDER_USES, null, 2)} + +const steps: Step[] = ${JSON.stringify(BUILDER_STEPS, null, 2)} + +const sectionTitle: React.CSSProperties = { + margin: '32px 0 12px', + fontSize: 12, + fontWeight: 600, + letterSpacing: '0.06em', + textTransform: 'uppercase', + color: 'var(--muted)' +} + +function Card(props: { step: number; title: string; description: string; code?: string; children: React.ReactNode }) { + return ( + <section className="card"> + <div className="card-header"> + <span className="card-step">{props.step}</span> + <div> + <h2>{props.title}</h2> + <p className="muted">{props.description}</p> + </div> + </div> + <div className="card-body">{props.children}</div> + {props.code && ( + <pre className="snippet"> + <code>{props.code}</code> + </pre> + )} + </section> + ) +} + +const App = () => { + return ( + <main className="app"> + <header className="hero"> + <span className="eyebrow">Windmill app{ctx.workspace ? ' · ' + ctx.workspace : ''}</span> + <h1>{firstName ? 'Welcome, ' + firstName : 'Welcome'}</h1> + <p className="muted"> + Turn the scripts and flows deployed in this workspace into a tool anyone can use. Edit + App.tsx to make it yours. + </p> + </header> + <h2 style={sectionTitle}>What you can build</h2> + <div className="grid" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(min(100%, 240px), 1fr))' }}> + {uses.map((use) => ( + <section className="card" key={use.title} style={{ padding: 18, gap: 4 }}> + <h2 style={{ fontSize: 15 }}>{use.title}</h2> + <p className="muted" style={{ margin: 0 }}>{use.text}</p> + </section> + ))} + </div> + <p style={{ margin: '12px 0 0', padding: '10px 14px', borderRadius: 8, background: 'var(--accent-soft)', color: 'var(--fg-strong)' }}> + {${JSON.stringify(BUILDER_SAFETY)}} + </p> + <h2 style={sectionTitle}>How it works</h2> + <div className="grid"> + {steps.map((step, i) => ( + <Card key={step.title} step={i + 1} title={step.title} description={step.description} code={step.code}> + {step.path && ( + <div className="row" style={{ alignItems: 'center', flexWrap: 'wrap' }}> + {step.path.map((label, j) => ( + <React.Fragment key={label}> + {j > 0 && <span className="muted">→</span>} + <span className="eyebrow">{label}</span> + </React.Fragment> + ))} + </div> + )} + <span className="muted">{step.note}</span> + </Card> + ))} + <Card + step={steps.length + 1} + title="Know who is viewing" + description="Windmill passes the workspace and the viewer to the app." + code={${JSON.stringify(BUILDER_CONTEXT_CODE)}} + > + <div> + <span className="muted">Workspace </span> + <strong>{ctx.workspace}</strong> + </div> + <div> + <span className="muted">Viewer </span> + <strong>{viewer ? viewer.name || viewer.username : 'Anonymous visitor'}</strong> + </div> + </Card> + </div> + </main> + ) +} + +export default App +` + +const builderAppSvelte = `<script lang="ts"> + // Windmill injects the viewer (absent for anonymous visitors) and the workspace. + const ctx = (window as any).ctx ?? {} + const viewer: { name?: string; username?: string } | undefined = ctx.ctx + const firstName = (viewer?.name || viewer?.username || '').split(' ')[0] + + type Step = { title: string; description: string; note: string; path?: string[]; code?: string } + + const uses: { title: string; text: string }[] = ${JSON.stringify(BUILDER_USES, null, 2)} + const steps: Step[] = ${JSON.stringify(BUILDER_STEPS, null, 2)} + const contextCode = ${JSON.stringify(BUILDER_CONTEXT_CODE)} +</script> + +{#snippet header(step: number, title: string, description: string)} + <div class="card-header"> + <span class="card-step">{step}</span> + <div> + <h2>{title}</h2> + <p class="muted">{description}</p> + </div> + </div> +{/snippet} + +<main class="app"> + <header class="hero"> + <span class="eyebrow">Windmill app{ctx.workspace ? ' · ' + ctx.workspace : ''}</span> + <h1>{firstName ? 'Welcome, ' + firstName : 'Welcome'}</h1> + <p class="muted"> + Turn the scripts and flows deployed in this workspace into a tool anyone can use. Edit + App.svelte to make it yours. + </p> + </header> + + <h2 class="section-title">What you can build</h2> + <div class="grid" style="grid-template-columns: repeat(auto-fit, minmax(min(100%, 240px), 1fr))"> + {#each uses as use (use.title)} + <section class="card" style="padding: 18px; gap: 4px"> + <h2 style="font-size: 15px">{use.title}</h2> + <p class="muted" style="margin: 0">{use.text}</p> + </section> + {/each} + </div> + <p class="safety">{${JSON.stringify(BUILDER_SAFETY)}}</p> + + <h2 class="section-title">How it works</h2> + <div class="grid"> + {#each steps as step, i (step.title)} + <section class="card"> + {@render header(i + 1, step.title, step.description)} + <div class="card-body"> + {#if step.path} + <div class="row" style="align-items: center; flex-wrap: wrap"> + {#each step.path as label, j (label)} + {#if j > 0}<span class="muted">→</span>{/if} + <span class="eyebrow">{label}</span> + {/each} + </div> + {/if} + <span class="muted">{step.note}</span> + </div> + {#if step.code} + <pre class="snippet"><code>{step.code}</code></pre> + {/if} + </section> + {/each} + + <section class="card"> + {@render header(steps.length + 1, 'Know who is viewing', 'Windmill passes the workspace and the viewer to the app.')} + <div class="card-body"> + <div><span class="muted">Workspace </span><strong>{ctx.workspace}</strong></div> + <div> + <span class="muted">Viewer </span> + <strong>{viewer ? viewer.name || viewer.username : 'Anonymous visitor'}</strong> + </div> + </div> + <pre class="snippet"><code>{contextCode}</code></pre> + </section> + </div> +</main> + +<style> + .section-title { + margin: 32px 0 12px; + font-size: 12px; + font-weight: 600; + letter-spacing: 0.06em; + text-transform: uppercase; + color: var(--muted); + } + + .safety { + margin: 12px 0 0; + padding: 10px 14px; + border-radius: 8px; + background: var(--accent-soft); + color: var(--fg-strong); + } +</style> +` + +export const BUILDER_FRAMEWORK_TEMPLATES = { + react19: { ...react19Template, '/App.tsx': builderAppTsx }, + react18: { ...react18Template, '/App.tsx': builderAppTsx }, + svelte5: { ...svelte5Template, '/App.svelte': builderAppSvelte } +} + type StarterArg = { type: 'string' | 'number' } function inlineRunnable( @@ -1286,171 +1304,6 @@ export async function main() { } } -export const appVueRouter = ` -<template> - <div class="container"> - <!-- Navigation tabs --> - <nav class="tabs"> - <button - v-for="tab in tabs" - :key="tab.id" - :class="{ active: currentTab === tab.id }" - @click="changeTab(tab.id)" - > - {{ tab.name }} - </button> - </nav> - - <!-- Content sections --> - <div class="content"> - <div v-if="currentTab === 'home'" class="tab-content"> - <h2>Home</h2> - <p>Welcome to the home tab!</p> - <!-- Nested navigation example --> - <div class="sub-nav"> - <button - v-for="subItem in ['latest', 'popular']" - :key="subItem" - :class="{ active: currentSort === subItem }" - @click="changeSort(subItem)" - > - {{ subItem }} - </button> - </div> - </div> - - <div v-else-if="currentTab === 'about'" class="tab-content"> - <h2>About</h2> - <p>This is the about section</p> - </div> - - <div v-else-if="currentTab === 'contact'" class="tab-content"> - <h2>Contact</h2> - <p>Contact information here</p> - </div> - </div> - - <!-- Debug info --> - <div class="debug"> - <p>Current Tab: {{ currentTab }}</p> - <p>Current Sort: {{ currentSort }}</p> - <p>Current Hash: {{ currentHash }}</p> - </div> - </div> -</template> - -<script setup> -import { ref, onMounted, onUnmounted } from 'vue'; - -// Available tabs -const tabs = [ - { id: 'home', name: 'Home' }, - { id: 'about', name: 'About' }, - { id: 'contact', name: 'Contact' } -]; - -const currentTab = ref('home'); -const currentSort = ref('latest'); -const currentHash = ref(''); - -// Navigation functions -function changeTab(tabId) { - currentTab.value = tabId; - updateHash(); -} - -function changeSort(sort) { - currentSort.value = sort; - updateHash(); -} - -function updateHash() { - const params = new URLSearchParams(); - params.set('tab', currentTab.value); - if (currentSort.value !== 'latest') { - params.set('sort', currentSort.value); - } - window.location.hash = params.toString(); - currentHash.value = window.location.hash; -} - -function parseHash() { - const params = new URLSearchParams(window.location.hash.slice(1)); - currentTab.value = params.get('tab') || 'home'; - currentSort.value = params.get('sort') || 'latest'; - currentHash.value = window.location.hash; -} - -// Hash change handler -function handleHashChange() { - parseHash(); -} - -onMounted(() => { - if (window.location.hash) { - parseHash(); - } else { - updateHash(); - } - window.addEventListener('hashchange', handleHashChange); -}); - -onUnmounted(() => { - window.removeEventListener('hashchange', handleHashChange); -}); -</script> - -<style scoped> -.container { - max-width: 800px; - margin: 0 auto; - padding: 20px; -} - -.tabs { - display: flex; - gap: 10px; - margin-bottom: 20px; -} - -button { - padding: 8px 16px; - border: 1px solid #ddd; - background: #fff; - border-radius: 4px; - cursor: pointer; -} - -button.active { - background: #4CAF50; - color: white; - border-color: #4CAF50; -} - -.content { - padding: 20px; - border: 1px solid #ddd; - border-radius: 4px; -} - -.tab-content { - margin-bottom: 20px; -} - -.sub-nav { - margin-top: 10px; -} - -.debug { - margin-top: 20px; - padding: 10px; - background: #f5f5f5; - border-radius: 4px; - font-size: 0.9em; - color: #666; -} -</style>` - export const appSvelteRouter = ` <script> import { onMount, onDestroy } from 'svelte'; diff --git a/frontend/src/lib/components/raw_apps/utils.test.ts b/frontend/src/lib/components/raw_apps/utils.test.ts index 74a5c4c097..36b187b6a9 100644 --- a/frontend/src/lib/components/raw_apps/utils.test.ts +++ b/frontend/src/lib/components/raw_apps/utils.test.ts @@ -7,10 +7,37 @@ import { formatRuntimeLogsForChat, genWmillTs, normalizeRawAppRuntimeLogs, + rawAppPreviewModules, stripRawAppDiffNoise, type Runnable } from './utils' +describe('rawAppPreviewModules', () => { + const inline = (language: 'bun' | 'python3', content: string) => + ({ type: 'inline', inlineScript: { language, content } }) as unknown as Runnable + + it('ships only the same-language runnables reached through imports', () => { + const runnables = { + get: inline('bun', "import { a } from './a'\nimport { p } from './py'"), + a: inline('bun', 'import { b } from "./b.ts"'), + b: inline('bun', "import { g } from './get'\nexport const b = 1"), + unused: inline('bun', 'export const u = 1'), + main: inline('bun', 'export const m = 1'), + py: inline('python3', 'from .helpers import x') + } + // `get` itself ships too once the cycle through `b` reaches it, as deploy does. + expect(Object.keys(rawAppPreviewModules(runnables, 'get') ?? {}).sort()).toEqual([ + 'a.ts', + 'b.ts', + 'get.ts' + ]) + expect(rawAppPreviewModules(runnables, 'unused')).toBeUndefined() + expect( + rawAppPreviewModules({ ...runnables, helpers: inline('python3', 'x = 1') }, 'py') + ).toEqual({ 'helpers.py': { language: 'python3', content: 'x = 1' } }) + }) +}) + const flowSchema = { $schema: 'https://json-schema.org/draft/2020-12/schema', type: 'object', diff --git a/frontend/src/lib/components/raw_apps/utils.ts b/frontend/src/lib/components/raw_apps/utils.ts index 3070572785..f87f014d8e 100644 --- a/frontend/src/lib/components/raw_apps/utils.ts +++ b/frontend/src/lib/components/raw_apps/utils.ts @@ -1,4 +1,4 @@ -import type { ScriptLang } from '../../gen/types.gen' +import type { ScriptLang, ScriptModule } from '../../gen/types.gen' import type { Schema } from '../../common' import { schemaToTsType } from '../../schema' import { isRunnableByName, isRunnableByPath, type RunnableWithFields } from '../apps/inputType' @@ -10,6 +10,7 @@ import { appSourceToDraftValue, normalizeRawAppData } from './rawAppDraftValue' type RunnableWithInlineScript = RunnableWithFields & { inlineScript?: InlineScript & { language: ScriptLang } + viewer_data_access?: boolean } export type Runnable = RunnableWithInlineScript | undefined @@ -17,6 +18,49 @@ export type RawApp = { files: string[] } +function moduleExtension(language: ScriptLang | undefined): string | undefined { + if (language === 'bun' || language === 'bunnative') return 'ts' + if (language === 'python3') return 'py' + return undefined +} + +/** Ids of the sibling runnables `content` imports as `./<id>` (TS) or `.<id>` (Python). */ +function siblingImports(content: string, ext: string): string[] { + const pattern = + ext === 'ts' + ? /(?:from|import)\s*['"]\.\/([^'"/]+?)(?:\.ts)?['"]/g + : /^\s*from\s+\.([A-Za-z_]\w*)\s+import\b/gm + return Array.from(content.matchAll(pattern), (m) => m[1]) +} + +/** + * The app's other inline runnables that runnable `id` imports, directly or through one + * another, as the modules its preview ships with so those imports resolve to the + * editor's code. Deploy stores the same set on the runnable. + */ +export function rawAppPreviewModules( + runnables: Record<string, Runnable>, + id: string +): Record<string, ScriptModule> | undefined { + const own = runnables[id]?.inlineScript + const ext = moduleExtension(own?.language) + if (!own || !ext) return undefined + const modules: Record<string, ScriptModule> = {} + const queue = siblingImports(own.content, ext) + while (queue.length > 0) { + const siblingId = queue.pop()! + const key = `${siblingId}.${ext}` + const inlineScript = runnables[siblingId]?.inlineScript + // `main.ts` is the Bun entrypoint's own file, so no module may take that name. The + // runnable itself is kept when a cycle reaches it: the entrypoint is not under its id. + if (key in modules || key === 'main.ts') continue + if (!inlineScript || moduleExtension(inlineScript.language) !== ext) continue + modules[key] = { content: inlineScript.content, language: inlineScript.language } + queue.push(...siblingImports(inlineScript.content, ext)) + } + return Object.keys(modules).length > 0 ? modules : undefined +} + // Server-managed columns the deployed app row (getAppByPath) carries but the // editor's current value never does — leaving them in renders as spurious diff. const RAW_APP_DEPLOYED_METADATA_KEYS = [ @@ -293,7 +337,6 @@ export function unsandboxedRawAppHtml( <html> <head> <meta charset="UTF-8" /> - <title>App @@ -318,6 +361,21 @@ export function unsandboxedRawAppHtml( history.pushState = function () { _ps.apply(this, arguments); notifyParent(); }; history.replaceState = function () { _rs.apply(this, arguments); notifyParent(); }; setTimeout(notifyParent, 0); + + // The parent shows the app's document.title in its tab. This document has no + // of its own: document.title reads the first one, so a placeholder would + // shadow the one a framework (React 19, react-helmet) appends. + var lastTitle = ''; + new MutationObserver(function () { + var t = document.title; + if (t === lastTitle) return; + lastTitle = t; + try { + if (window.parent !== window) { + window.parent.postMessage({ type: 'windmill:title', title: t }, '*'); + } + } catch (_) {} + }).observe(document.head, { childList: true, subtree: true, characterData: true }); })(); </script> </head> diff --git a/frontend/src/lib/components/resources/ResourcesList.svelte b/frontend/src/lib/components/resources/ResourcesList.svelte index 687682fd4f..2b0cc5eb1e 100644 --- a/frontend/src/lib/components/resources/ResourcesList.svelte +++ b/frontend/src/lib/components/resources/ResourcesList.svelte @@ -44,8 +44,8 @@ import { OauthService, ResourceService, WorkspaceService, type ListableResource } from '$lib/gen' import { enterpriseLicense, userWorkspaces } from '$lib/stores' import { sendUserToast } from '$lib/toast' + import { useEditRights } from '$lib/operatorWriteRights' import { - canWrite, classNames, debounce, emptySchema, @@ -96,6 +96,7 @@ const operatingWorkspace = useOperatingWorkspace() const operatingUser = useOperatingUser() + const editRights = useEditRights() const hosted = useHostedPage() type ResourceW = ListableResource & { canWrite: boolean; marked?: string } @@ -334,7 +335,7 @@ const result = (await ResourceService.listResource(apiParams)).map((x) => { return { canWrite: - canWrite(x.path, x.extra_perms!, operatingUser.current) && + editRights.canEditItem('resource', x.path, x.extra_perms) && $operatingWorkspace! == x.workspace_id, ...x } diff --git a/frontend/src/lib/components/runs/BatchReRunOptionsPane.svelte b/frontend/src/lib/components/runs/BatchReRunOptionsPane.svelte index 3124333e4b..929fc7a59e 100644 --- a/frontend/src/lib/components/runs/BatchReRunOptionsPane.svelte +++ b/frontend/src/lib/components/runs/BatchReRunOptionsPane.svelte @@ -13,7 +13,7 @@ import { Pane, Splitpanes } from 'svelte-splitpanes' import PanelSection from '../apps/editor/settingsPanel/common/PanelSection.svelte' import { JobService, type InputTransform, type ListSelectedJobGroupsResponse } from '$lib/gen' - import { workspaceStore } from '$lib/stores' + import { useOperatingWorkspace } from '../operatingWorkspace.svelte' import type { Schema } from '$lib/common' import InputTransformForm from '../InputTransformForm.svelte' import type { FlowPropPickerConfig, PropPickerContext } from '../prop_picker' @@ -43,6 +43,8 @@ onConfirm: (options: BatchReRunOptions) => void } = $props() + const operatingWorkspace = useOperatingWorkspace() + let selected: JobGroup | undefined = $state() let options: BatchReRunOptions = $state({ flow: {}, script: {} }) watch( @@ -65,7 +67,7 @@ const listSelectedJobsSchemaCache = new Map<string, JobGroup>() async function fetchJobGroups(): Promise<JobGroup[]> { - if (!$workspaceStore) return [] + if (!$operatingWorkspace) return [] const cachedSelectedIds = selectedIds.filter((id) => listSelectedJobsSchemaCache.has(id)) const nonCachedSelectedIds = selectedIds.filter((id) => !listSelectedJobsSchemaCache.has(id)) @@ -75,7 +77,7 @@ ) const newJobGroups = nonCachedSelectedIds.length ? await JobService.listSelectedJobGroups({ - workspace: $workspaceStore, + workspace: $operatingWorkspace, requestBody: nonCachedSelectedIds }) : [] diff --git a/frontend/src/lib/components/runs/DispatchEventsTable.svelte b/frontend/src/lib/components/runs/DispatchEventsTable.svelte index 828437fee6..144a2d52e1 100644 --- a/frontend/src/lib/components/runs/DispatchEventsTable.svelte +++ b/frontend/src/lib/components/runs/DispatchEventsTable.svelte @@ -1,5 +1,4 @@ <script lang="ts"> - import { base } from '$lib/base' import type { ListDispatchEventsResponse } from '$lib/gen' import { ExternalLink, Check, Hourglass, MinusCircle } from 'lucide-svelte' @@ -66,7 +65,7 @@ {#if ev.outcome === 'dispatched' && ev.child_job_id} <a class="inline-flex items-center gap-1" - href={`${base}/run/${ev.child_job_id}?workspace=${workspace}`} + href={`/run/${ev.child_job_id}?workspace=${workspace}`} target="_blank" rel="noopener noreferrer" > diff --git a/frontend/src/lib/components/runs/JobDetailHeader.svelte b/frontend/src/lib/components/runs/JobDetailHeader.svelte index fb7a8890fc..5783deaf53 100644 --- a/frontend/src/lib/components/runs/JobDetailHeader.svelte +++ b/frontend/src/lib/components/runs/JobDetailHeader.svelte @@ -1,6 +1,5 @@ <script lang="ts"> import { JobService, type Job } from '$lib/gen' - import { base } from '$lib/base' import { displayDate, truncateRev, @@ -260,14 +259,14 @@ <Tooltip> {#snippet text()} This job was run on worker: - <a href={`${base}/runs/?job_kinds=all&worker=${job?.worker}`}> + <a href={`/runs/?job_kinds=all&worker=${job?.worker}`}> {job?.worker} </a> <br /> <WorkerHostname worker={job.worker!} minTs={job?.['created_at']} /> {/snippet} <a - href={`${base}/runs/?job_kinds=all&worker=${job?.worker}`} + href={`/runs/?job_kinds=all&worker=${job?.worker}`} target="_blank" rel="noopener noreferrer" class="flex items-center gap-1 text-primary" @@ -304,7 +303,7 @@ Triggered by {/if} <a - href={`${base}/run/${job.parent_job}?workspace=${$operatingWorkspace}`} + href={`/run/${job.parent_job}?workspace=${$operatingWorkspace}`} target="_blank" rel="noopener noreferrer" class="flex items-center gap-1" @@ -324,7 +323,7 @@ icon: Link, action: () => navigator.clipboard.writeText( - `${window.location.origin}${base}/run/${job.id}?workspace=${job.workspace_id}` + `${window.location.origin}/run/${job.id}?workspace=${job.workspace_id}` ) }, { @@ -385,7 +384,7 @@ <span class="text-secondary flex-shrink-0">Job ID</span> <span class="text-primary"> <a - href={`${base}/run/${job.id}?workspace=${job.workspace_id}`} + href={`/run/${job.id}?workspace=${job.workspace_id}`} target="_blank" rel="noopener noreferrer" class="flex items-center gap-1 min-w-0" @@ -476,7 +475,7 @@ {@const stem = job.job_kind === 'script' ? 'scripts' : 'flows'} {@const isScript = job.job_kind === 'script'} {@const viewHref = isScript - ? `${base}/${stem}/get/${job?.script_hash}` + ? `/${stem}/get/${job?.script_hash}` : flowPathToHref(job?.script_path ?? '')} <a href={viewHref} @@ -515,7 +514,7 @@ variant="subtle" disabled={togglingResolution} onClick={() => setResolution(false)} - title="Show this run as a failure again" + title="Show this run as unhandled again" > Unresolve </Button> @@ -526,7 +525,7 @@ size="xs2" variant="subtle" nonCaptureEvent - title="Mark this failure as handled" + title="Mark this run as handled" > Mark resolved </Button> @@ -534,8 +533,7 @@ {#snippet content({ close })} <div class="p-3 flex flex-col gap-2 w-80"> <p class="text-xs text-secondary"> - Resolving keeps the run a failure but stops it showing as one in the runs - list. + Resolving keeps the run's status but marks it as handled in the runs list. </p> <TextInput bind:value={resolutionNote} @@ -632,7 +630,7 @@ <span class="text-secondary flex-shrink-0">Job ID</span> <span class="text-primary"> <a - href={`${base}/run/${job.id}?workspace=${job.workspace_id}`} + href={`/run/${job.id}?workspace=${job.workspace_id}`} target="_blank" rel="noopener noreferrer" class="flex items-center gap-1 min-w-0" diff --git a/frontend/src/lib/components/runs/JobRunsPreview.svelte b/frontend/src/lib/components/runs/JobRunsPreview.svelte index ae61ca2d8e..9c5144166e 100644 --- a/frontend/src/lib/components/runs/JobRunsPreview.svelte +++ b/frontend/src/lib/components/runs/JobRunsPreview.svelte @@ -7,7 +7,7 @@ import { Skeleton, Tab, Tabs } from '../common' import HighlightCode from '../HighlightCode.svelte' import FlowStatusViewer from '../FlowStatusViewer.svelte' - import { workspaceStore } from '$lib/stores' + import { useOperatingWorkspace } from '../operatingWorkspace.svelte' import WorkflowTimeline from '../WorkflowTimeline.svelte' import { isFlowPreview, isScriptPreview, type StateStore } from '$lib/utils' import { setContext, untrack, createEventDispatcher } from 'svelte' @@ -26,6 +26,7 @@ let { id, workspace, onResolutionChanged }: Props = $props() const dispatch = createEventDispatcher() + const operatingWorkspace = useOperatingWorkspace() let job: (Job & { result_stream?: string }) | undefined = $state(undefined) @@ -185,7 +186,7 @@ <div class="text-xs text-emphasis font-semibold mb-1">Inputs</div> <JobArgs id={job?.id} - workspace={job?.workspace_id ?? $workspaceStore ?? 'no_w'} + workspace={job?.workspace_id ?? $operatingWorkspace ?? 'no_w'} args={job?.args} /> </div> diff --git a/frontend/src/lib/components/runs/JobStatusIcon.svelte b/frontend/src/lib/components/runs/JobStatusIcon.svelte index 5f93f8b6dd..358ab1edeb 100644 --- a/frontend/src/lib/components/runs/JobStatusIcon.svelte +++ b/frontend/src/lib/components/runs/JobStatusIcon.svelte @@ -29,7 +29,12 @@ <ShieldQuestion size={14} /> </Badge> {:else if job.canceled && 'success' in job} - <Badge color="gray" {roundedFull} baseClass={roundedFull ? '' : '!px-1.5'} title="Canceled"> + <Badge + color="gray" + {roundedFull} + baseClass={roundedFull ? '' : '!px-1.5'} + title={job.resolved ? 'Canceled, marked as resolved' : 'Canceled'} + > <Ban size={14} /> </Badge> {:else if 'success' in job && job.success} diff --git a/frontend/src/lib/components/runs/NoWorkerWithTagWarning.svelte b/frontend/src/lib/components/runs/NoWorkerWithTagWarning.svelte index 5ff51c9c04..2a4d0a8de6 100644 --- a/frontend/src/lib/components/runs/NoWorkerWithTagWarning.svelte +++ b/frontend/src/lib/components/runs/NoWorkerWithTagWarning.svelte @@ -4,6 +4,7 @@ import Popover from '../Popover.svelte' import { onDestroy, untrack } from 'svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + import { devWorkspaceTagSuffix, loadDevWorkspaceTagSuffix } from '$lib/devWorkspaceTags' const operatingWorkspace = useOperatingWorkspace() interface Props { @@ -28,6 +29,13 @@ return tag }) + loadDevWorkspaceTagSuffix() + let devSuffix = $derived( + $devWorkspaceTagSuffix && customTag?.endsWith($devWorkspaceTagSuffix) + ? $devWorkspaceTagSuffix + : undefined + ) + async function lookForTag(): Promise<void> { try { if (!customTag) return @@ -50,7 +58,10 @@ $effect(() => { customTag - untrack(() => timeout && setTimeout(() => lookForTag(), 2500)) + untrack(() => { + clearTimeout(timeout) + timeout = setTimeout(() => lookForTag(), 2500) + }) }) onDestroy(() => { @@ -66,6 +77,10 @@ <AlertTriangle size={16} class="text-yellow-500" /> {#snippet text()} No worker with {tagLabel ?? 'tag'} <b>{customTag}</b> is currently running. + {#if devSuffix} + <br />It carries the <code>{devSuffix}</code> suffix of dev workspace and fork jobs: only worker + groups flagged as serving dev workspaces listen to it. An admin can flag one on the Workers page. + {/if} {/snippet} </Popover> {/if} diff --git a/frontend/src/lib/components/runs/RunBadges.svelte b/frontend/src/lib/components/runs/RunBadges.svelte index 668521b429..a04b6e646a 100644 --- a/frontend/src/lib/components/runs/RunBadges.svelte +++ b/frontend/src/lib/components/runs/RunBadges.svelte @@ -2,15 +2,22 @@ import Tooltip from '$lib/components/meltComponents/Tooltip.svelte' import PreprocessedArgsDisplay from '$lib/components/runs/PreprocessedArgsDisplay.svelte' import { getJobKindDisplayLabel, truncateHash } from '$lib/utils' - import { base } from '$lib/base' import { truncateRev } from '$lib/utils' import Badge from '$lib/components/common/badge/Badge.svelte' import Button from '$lib/components/common/button/Button.svelte' import { ListFilter, Tag } from 'lucide-svelte' import type { Job } from '$lib/gen' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' + import { userWorkspaces } from '$lib/stores' + import { + devWorkspaceTagSuffix, + devWorkspaceSkipNonDevForks, + isIsolatedWorkspaceId, + loadDevWorkspaceTagSuffix + } from '$lib/devWorkspaceTags' const operatingWorkspace = useOperatingWorkspace() + loadDevWorkspaceTagSuffix() interface Props { job: Job @@ -35,7 +42,7 @@ {#if job.script_hash && showScriptHash && job.job_kind !== 'aiagent'} {#if job.job_kind == 'script'} - <a href="{base}/scripts/get/{job.script_hash}?workspace={$operatingWorkspace}" + <a href="/scripts/get/{job.script_hash}?workspace={$operatingWorkspace}" ><Badge color="gray" title={`Script hash: ${job.script_hash}`} {large} >{truncateHash(job.script_hash)} </Badge></a @@ -68,7 +75,17 @@ {#if job.tag != undefined} <!-- for related places search: ADD_NEW_LANG --> <div> - <Badge color="indigo" {large}>Tag: {job.tag}</Badge> + <Badge color="indigo" {large}> + Tag: {job.tag} + {#if $devWorkspaceTagSuffix && job.tag.endsWith($devWorkspaceTagSuffix) && isIsolatedWorkspaceId(job.workspace_id, $userWorkspaces, $devWorkspaceSkipNonDevForks)} + <Tooltip> + {#snippet text()} + Suffixed with <code>{$devWorkspaceTagSuffix}</code> because this workspace is a dev workspace + or a fork: its jobs run only on worker groups serving dev workspaces. + {/snippet} + </Tooltip> + {/if} + </Badge> </div> {/if} {#if !job.visible_to_owner} @@ -108,9 +125,7 @@ <ListFilter class="inline-block" size={10} /> </Button> {:else} - <a - href={`${base}/runs/?job_kinds=all&graph=ConcurrencyChart&concurrency_key=${concurrencyKey}`} - > + <a href={`/runs/?job_kinds=all&graph=ConcurrencyChart&concurrency_key=${concurrencyKey}`}> {concurrencyKey} </a> {/if} @@ -120,9 +135,7 @@ <Badge {large}>Concurrency: {truncateRev(concurrencyKey, 20)}</Badge> </button> {:else} - <a - href={`${base}/runs/?job_kinds=all&graph=ConcurrencyChart&concurrency_key=${concurrencyKey}`} - > + <a href={`/runs/?job_kinds=all&graph=ConcurrencyChart&concurrency_key=${concurrencyKey}`}> <Badge {large}>Concurrency: {truncateRev(concurrencyKey, 20)}</Badge> </a> {/if} diff --git a/frontend/src/lib/components/runs/RunDetail.svelte b/frontend/src/lib/components/runs/RunDetail.svelte new file mode 100644 index 0000000000..d372d5d540 --- /dev/null +++ b/frontend/src/lib/components/runs/RunDetail.svelte @@ -0,0 +1,1652 @@ +<script lang="ts"> + import { + JobService, + type Job, + ScriptService, + type Script, + type WorkflowStatus, + type NewScript, + ConcurrencyGroupsService, + MetricsService, + WorkerService, + type ScriptArgs + } from '$lib/gen' + import { + computeSharableHash, + copyToClipboard, + encodeState, + findMatchingCustomTag, + getHubFlowIdFromPath, + isHubFlowPath, + isFlowPreview, + isNotFlow, + isScriptPreview, + type Item + } from '$lib/utils' + import BarsStaggered from '$lib/components/icons/BarsStaggered.svelte' + + import { + Activity, + Calendar, + List, + Pen, + RefreshCw, + TimerOff, + Trash, + Code2, + ClipboardCopy, + GitBranch, + EllipsisVertical, + Share2, + Globe, + Users, + Play, + SearchX, + ArrowRight + } from 'lucide-svelte' + import WorkspaceIcon from '$lib/components/workspace/WorkspaceIcon.svelte' + import { forLater } from '$lib/forLater' + + import { isJobResolvable } from '$lib/utils' + import { + claimRerunOrigin, + offerToResolveOriginal, + rememberRerunOrigin + } from '$lib/components/runs/rerunResolution.svelte' + import DisplayResult from '$lib/components/DisplayResult.svelte' + import DbtRunGraph from '$lib/components/dbt/DbtRunGraph.svelte' + import DispatchEventsPanel from '$lib/components/runs/DispatchEventsPanel.svelte' + import UpstreamSnapshotsPanel from '$lib/components/runs/UpstreamSnapshotsPanel.svelte' + import { enterpriseLicense, initialArgsStore, superadmin, userWorkspaces } from '$lib/stores' + import FlowStatusViewer from '$lib/components/FlowStatusViewer.svelte' + import HighlightCode from '$lib/components/HighlightCode.svelte' + import JobLoader from '$lib/components/JobLoader.svelte' + import LogViewer from '$lib/components/LogViewer.svelte' + import { Button, Skeleton, Tab, Alert, DrawerContent } from '$lib/components/common' + import PageHeaderContent from '$lib/components/PageHeaderContent.svelte' + import { pageHeader } from '$lib/components/pageHeaderRegistry.svelte' + import JobDetailHeader from '$lib/components/runs/JobDetailHeader.svelte' + import ScriptRetryChain from '$lib/components/runs/ScriptRetryChain.svelte' + import FlowExecutionStatus from '$lib/components/runs/FlowExecutionStatus.svelte' + import JobArgs from '$lib/components/JobArgs.svelte' + import FlowProgressBar from '$lib/components/flows/FlowProgressBar.svelte' + import JobProgressBar from '$lib/components/jobs/JobProgressBar.svelte' + import Tabs from '$lib/components/common/tabs/TabsV2.svelte' + import { goto } from '$lib/navigation' + import { sendUserToast } from '$lib/toast' + import Dropdown from '$lib/components/DropdownV2.svelte' + import PersistentScriptDrawer from '$lib/components/PersistentScriptDrawer.svelte' + import Portal from '$lib/components/Portal.svelte' + + import MemoryFootprintViewer from '$lib/components/MemoryFootprintViewer.svelte' + import Drawer from '$lib/components/common/drawer/Drawer.svelte' + import { Highlight } from 'svelte-highlight' + import { json } from 'svelte-highlight/languages' + import Toggle from '$lib/components/Toggle.svelte' + import WorkflowTimeline from '$lib/components/WorkflowTimeline.svelte' + + import HighlightTheme from '$lib/components/HighlightTheme.svelte' + + import ExecutionDuration from '$lib/components/ExecutionDuration.svelte' + import { isWindmillTooBigObject } from '$lib/components/job_args' + import ScheduleEditor from '$lib/components/triggers/schedules/ScheduleEditor.svelte' + import OpenInSessionButton from '$lib/components/sessions/OpenInSessionButton.svelte' + import { onDestroy, setContext, untrack } from 'svelte' + import { getJobStatusKind, resetFavicon, setStatusFavicon } from '$lib/favicon' + + import FlowAssetsHandler, { + initFlowGraphAssetsCtx + } from '$lib/components/flows/FlowAssetsHandler.svelte' + import JobAssetsViewer from '$lib/components/assets/JobAssetsViewer.svelte' + import { setViewToken } from '$lib/viewToken' + import { twMerge } from 'tailwind-merge' + import FlowRestartButton from '$lib/components/FlowRestartButton.svelte' + import { useNestedRestartState } from '$lib/components/useNestedRestartState.svelte' + import JobOtelTraces from '$lib/components/JobOtelTraces.svelte' + import { + canUserBypassRuleKindInRulesets, + fetchProtectionRulesForWorkspace, + isRuleActiveInRulesets, + protectionRulesState + } from '$lib/workspaceProtectionRules.svelte' + import { + buildForkEditUrl, + editInForkAllowed, + editInForkLabel, + onEditInForkClick, + openEditInFork + } from '$lib/utils/editInFork' + import { resource } from 'runed' + import { + setOperatingWorkspace, + useOperatingUser + } from '$lib/components/operatingWorkspace.svelte' + import { isCloudHosted } from '$lib/cloud' + import { useEditRights } from '$lib/operatorWriteRights' + import { AGENT_STEP_ID } from '$lib/components/flows/conversations/agentEditorChat' + + let { + id: runId, + workspace: workspaceId, + viewToken, + onNavigate = goto, + embedded = false + }: { + /** The `[...run]` route segment: the job's id. */ + id: string + workspace: string | undefined + /** Share-link token of the URL this run was opened at (`view_token`). */ + viewToken?: string + onNavigate?: (url: string) => void | Promise<void> + /** Rendered inside a page that is not the run's own (an AI session preview tab): the + * layout's header, the favicon and the request-wide view token all belong to that page. */ + embedded?: boolean + } = $props() + + // Fixed for the component's life: a host mounts it embedded or it is the route's page. + const ownsPage = untrack(() => !embedded) + + // Every workspace-scoped call below and in the panels this page mounts targets `workspace`, + // not the nav store: a session views a run in its own workspace. + setOperatingWorkspace(() => workspaceId) + // Roles are per-workspace, so every gate below asks about `workspace` rather than about the + // one the browser is navigated to. + const operatingUser = useOperatingUser() + const actingUser = $derived(operatingUser.current) + const editRights = useEditRights() + + // Protection rules are only kept loaded for the navigation workspace. + const foreignRulesets = resource( + () => (workspaceId !== protectionRulesState.workspace ? workspaceId : undefined), + async (ws) => (ws ? await fetchProtectionRulesForWorkspace(ws) : undefined) + ) + const rulesets = $derived( + workspaceId === protectionRulesState.workspace + ? protectionRulesState.rulesets + : foreignRulesets.current + ) + + let job: (Job & { result?: any; result_stream?: string }) | undefined = $state() + let jobUpdateLastFetch: Date | undefined = $state() + + // A re-run launched from a failed run offers to resolve that failure once it succeeds. + // The claim happens here rather than at init because SvelteKit reuses this component + // across /run/<id> navigations, so init only runs for the first run viewed. + // Only ever an offer: a re-run is a fresh execution, not proof the old failure was handled. + let offeredForJobId: string | undefined = $state(undefined) + $effect(() => { + if (!job || offeredForJobId === job.id) return + if ('success' in job && job.success) { + const origin = claimRerunOrigin(job.id) + if (origin) { + offeredForJobId = job.id + offerToResolveOriginal(origin) + } + } + }) + + let scriptProgress: number | undefined = $state(undefined) + let currentJobIsLongRunning: boolean = $state(false) + + let viewTab: 'logs' | 'code' | 'stats' | 'assets' | 'traces' = $state('logs') + let selectedJobStep: string | undefined = $state(undefined) + + // Mirror of the graph's per-module display state (selected iteration of each + // ForLoop, etc.). Drives both the iteration pre-fill and the iteration-count + // selectors in the restart popup. + let graphModuleStates: Record<string, import('$lib/components/graph').GraphModuleState> = $state( + {} + ) + let expandedSubflows: Record< + string, + { modules: import('$lib/gen').FlowModule[]; groups?: any[] } + > = $state({}) + const selectedRestart = useNestedRestartState({ + selectedJobStep: () => selectedJobStep, + job: () => job, + graphModuleStates: () => graphModuleStates, + expandedSubflows: () => expandedSubflows + }) + // When the selection can't be restarted from (nothing clicked, Input/Result, + // a step inside a parallel loop), the button targets the top-level step that + // failed the run, so it is visible without hunting for it in a large graph. + // A continue-on-error step keeps its `Failure` status on a run that succeeds, + // so only a failed run counts, and its last `Failure` is the one that ended it. + const failedTopLevelStep = $derived.by(() => { + if (job?.type !== 'CompletedJob' || job.success !== false || job.canceled) return undefined + const failures = job.flow_status?.modules?.filter((m) => m.type === 'Failure') ?? [] + return failures[failures.length - 1]?.id + }) + const failedRestart = useNestedRestartState({ + selectedJobStep: () => failedTopLevelStep, + job: () => job, + graphModuleStates: () => graphModuleStates, + expandedSubflows: () => expandedSubflows + }) + const selectionRestartable = $derived( + selectedJobStep !== undefined && + (selectedRestart.topLevelRestartable || selectedRestart.nestedRestartSupported) + ) + const restartStep = $derived(selectionRestartable ? selectedJobStep : failedTopLevelStep) + const restart = $derived(selectionRestartable ? selectedRestart : failedRestart) + function canRestart(state: ReturnType<typeof useNestedRestartState>) { + return ( + job?.type === 'CompletedJob' && + job.job_kind === 'flow' && + (state.topLevelRestartable || state.nestedRestartSupported) + ) + } + + let testIsLoading = $state(false) + let jobLoader: JobLoader | undefined = $state(undefined) + let loadError: { status?: number; message?: string } | undefined = $state(undefined) + + // Flow execution status state + let suspendStatus: import('$lib/utils').StateStore<Record<string, { job: Job; nb: number }>> = + $state({ val: {} }) + let isOwner: boolean = $state(false) + + let persistentScriptDrawer: PersistentScriptDrawer | undefined = $state(undefined) + + let showExplicitProgressTip: boolean = $state( + (localStorage.getItem('hideExplicitProgressTip') ?? 'false') == 'false' + ) + + let lastJobId: string | undefined = $state(undefined) + let concurrencyKey: string | undefined = $state(undefined) + + setContext( + 'FlowGraphAssetContext', + initFlowGraphAssetsCtx({ getModules: () => job?.raw_flow?.modules ?? [] }) + ) + + async function getConcurrencyKey(job: Job | undefined) { + if (!job) return + lastJobId = job.id + concurrencyKey = await ConcurrencyGroupsService.getConcurrencyKey({ id: job.id }) + } + + // Share read link: if the URL carries a `view_token`, install it so every job + // read on this page (incl. flow steps, args, logs, SSE) is authorized by it. + // Set eagerly at init (before JobLoader mounts and fires its first fetch), and + // reactively keep it in sync across client-side navigation. + // The token rides on every request the window makes, so only the run's own page installs + // one: embedded, it would authorize the host's requests too and clear another run's token. + if (ownsPage) { + setViewToken(untrack(() => viewToken)) + $effect(() => { + setViewToken(viewToken) + }) + onDestroy(() => setViewToken(undefined)) + } + + async function shareReadLink(id: string): Promise<void> { + try { + const workspace = workspaceId! + const token = (await JobService.getJobViewToken({ workspace, id })).trim() + // Pin the workspace in the link: the token is signed with this workspace's + // key, and the logged layout only switches `$workspaceStore` when the URL + // carries `workspace=`. Without it a recipient whose active workspace + // differs would open the run (and validate the token) against the wrong one. + const url = `${window.location.origin}/run/${id}?workspace=${encodeURIComponent( + workspace + )}&view_token=${encodeURIComponent(token)}` + copyToClipboard(url) + sendUserToast('Read-only share link copied to clipboard') + } catch (e) { + sendUserToast(`Failed to create share link: ${e}`, true) + } + } + + async function sharePublicLink(id: string): Promise<void> { + try { + const workspace = workspaceId! + const token = (await JobService.getJobPublicViewToken({ workspace, id })).trim() + // The workspace is a path segment here: the public run page is outside the + // logged layout and has no workspace store to fall back on. + const url = `${window.location.origin}/public_run/${encodeURIComponent( + workspace + )}/${id}?view_token=${encodeURIComponent(token)}` + copyToClipboard(url) + sendUserToast('Public link copied to clipboard — anyone with it can view this run') + } catch (e) { + sendUserToast(`Failed to create public link: ${e}`, true) + } + } + + async function deleteCompletedJob(id: string): Promise<void> { + await JobService.deleteCompletedJob({ workspace: workspaceId!, id }) + getJob() + } + + async function cancelJob(id: string) { + try { + if (forceCancel) { + await JobService.forceCancelQueuedJob({ workspace: workspaceId!, id, requestBody: {} }) + setTimeout(getJob, 5000) + } else { + await JobService.cancelQueuedJob({ workspace: workspaceId!, id, requestBody: {} }) + } + sendUserToast(`job ${id} canceled`) + } catch (err) { + sendUserToast('could not cancel job', true) + } + } + + // A schedule's upcoming tick sits on a whole second and the backend refuses it; a tick + // deferred by a concurrency limit lands on a sub-second instant and can still start now. + let canRunNow = $derived( + job?.type === 'QueuedJob' && + !job.running && + !job.suspend && + !!job.scheduled_for && + forLater(job.scheduled_for) && + !(job.schedule_path && new Date(job.scheduled_for).getMilliseconds() === 0) + ) + + async function runJobNow(id: string) { + try { + await JobService.runQueuedJobNow({ workspace: workspaceId!, id }) + sendUserToast(`job ${id} will start as soon as a worker is available`) + getJob() + } catch (err) { + sendUserToast(`could not start job now: ${err?.body ?? err}`, true) + } + } + + // Initialize view tab to logs since result is now outside tabs + function initView(): void { + // Result is now displayed outside tabs, so always default to logs + viewTab = 'logs' + } + + async function getJob() { + await jobLoader?.watchJob(runId ?? '', { + change(job: Job & { result_stream?: string }) { + // Result is now displayed outside tabs, no need to switch tabs + }, + done(job) { + // Result is now displayed outside tabs, no need to switch tabs + } + }) + initView() + } + + let persistentScriptDefinition: Script | undefined = $state(undefined) + + async function onJobLoaded() { + // We want to set up scriptProgress once job is loaded + // We need this to show progress bar if job has progress and is finished + if ( + job && + job.type == 'CompletedJob' && + (job.job_kind == 'script' || isScriptPreview(job.job_kind)) + ) { + // If error occurred and job is completed + // than we fetch progress from server to display on what progress did it fail + // Could be displayed after run or as a historical page + // If opening page without running job (e.g. reloading page after run) progress will be displayed instantly + MetricsService.getJobProgress({ + workspace: job.workspace_id ?? 'NO_WORKSPACE', + id: job.id + }).then((progress) => { + // Returned progress is not always 100%, could be 65%, 33%, anything + // Its ok if its a failure and we want to keep that value + // But we want progress to be 100% if job has been succeeded + scriptProgress = progress + }) + } + + if ( + job && + job.job_kind === 'script' && + job.script_hash && + persistentScriptDefinition === undefined + ) { + const script = await ScriptService.getScriptByHash({ + workspace: workspaceId!, + hash: job.script_hash + }) + if (script.restart_unless_cancelled ?? false) { + persistentScriptDefinition = script + } + } + } + + function onRunsPageChangeWithLoader() { + forceCancel = false + getJob() + } + + function onRunsPageChange() { + job = undefined + persistentScriptDefinition = undefined + } + + let notfound = $state(false) + let forceCancel = $state(false) + + let debugViewer: Drawer | undefined = $state(undefined) + let debugContent: any = $state(undefined) + async function debugInfo() { + if (job?.id) { + debugContent = await JobService.getFlowDebugInfo({ workspace: workspaceId!, id: job?.id }) + debugViewer?.openDrawer() + } else { + sendUserToast('Job has no id', true) + } + } + + function removeSensitiveInfos( + jobs: { [job: string]: { args: any; result: any; logs: string } }, + redactSensitive: boolean + ) { + if (!redactSensitive) { + return jobs + } + if (jobs === undefined || typeof jobs !== 'object') { + return [] + } + return Object.fromEntries( + Object.entries(jobs).map(([k, job]) => { + return [ + k, + { + ...job, + args: '[redacted]', + result: '[redacted]', + logs: '[redacted]' + } + ] + }) + ) + } + + let redactSensitive = $state(false) + + function asWorkflowStatus(x: any): Record<string, WorkflowStatus> { + if (!x || typeof x !== 'object') return {} + const result: Record<string, WorkflowStatus> = {} + for (const [k, v] of Object.entries(x)) { + if (!k.startsWith('_') || k.startsWith('_step/')) result[k] = v as WorkflowStatus + } + return result + } + + function getStepResults(x: any): Record<string, any> { + return x?._checkpoint?.completed_steps ?? {} + } + + function forkPreview() { + if (isFlowPreview(job?.job_kind)) { + if (isHubFlowPath(job?.script_path)) { + const hubFlowId = getHubFlowIdFromPath(job?.script_path) + if (hubFlowId === undefined) { + sendUserToast('Could not determine the hub flow to fork', true) + return + } + $initialArgsStore = job?.args + window.open(`/flows/add?hub=${hubFlowId}`) + return + } + + const state = { + flow: { value: job?.raw_flow }, + path: job?.script_path + '_fork', + initialArgs: job?.args + } + try { + localStorage.setItem('fork_flow', JSON.stringify(state)) + } catch { + // Flow too large for localStorage, pass via window reference + ;(window as any).__forkPreviewData = state + } + window.open('/flows/add?fork=true') + } else { + $initialArgsStore = job?.args + let n: NewScript = { + path: job?.script_path + '_fork', + summary: 'Fork of preview of ' + job?.script_path, + language: job?.language as NewScript['language'], + description: '', + content: job?.raw_code ?? '', + kind: 'script' + } + const encodedArgs = encodeState(job?.args) + window.open(`/scripts/add?initial_args=${encodedArgs}#${encodeState(n)}`) + } + } + + let scheduleEditor: ScheduleEditor | undefined = $state(undefined) + + // A job's stored tag is usually backend-derived (language/flow default, possibly + // workspace-suffixed) and would be rejected by the CUSTOM_TAGS check if passed back + // explicitly. Only carry it into a re-run when it maps back to a custom-tag entry — + // the set the override dropdown offers — using the raw (possibly templated) entry. + // Pass the run's args if already fetched; template matching needs the full args + // (job.args may be truncated for large runs) and fetches them itself otherwise. + let customTags: { workspace: string; tags: string[] } | undefined = undefined + async function getRerunTagOverride( + args: Record<string, any> | undefined + ): Promise<string | undefined> { + const tag = job?.tag + const workspace = workspaceId! + if (!tag) { + return undefined + } + try { + if (customTags?.workspace !== workspace) { + customTags = { + workspace, + tags: await WorkerService.getCustomTagsForWorkspace({ workspace }) + } + } + } catch (e) { + console.error('Could not load custom tags, not carrying tag over for re-run', e) + return undefined + } + if (customTags.tags.includes(tag)) { + return tag + } + if (isWindmillTooBigObject(args)) { + try { + args = (await JobService.getJobArgs({ workspace, id: job?.id! })) as Record<string, any> + } catch (e) { + console.error('Could not load full args, not carrying tag over for re-run', e) + return undefined + } + } + return findMatchingCustomTag(tag, customTags.tags, workspace, args) + } + + let runImmediatelyLoading = $state(false) + // An override may be a function, because the arguments it merges into are not + // known until they are here: a `WINDMILL_TOO_BIG` payload is a placeholder + // until fetched, and merging over that one drops what the fetch was for. + async function runImmediately(argsOverride?: ScriptArgs | ((args: ScriptArgs) => ScriptArgs)) { + runImmediatelyLoading = true + try { + let args = job?.args as ScriptArgs + if (isWindmillTooBigObject(args)) { + args = (await JobService.getJobArgs({ + workspace: workspaceId!, + id: job?.id! + })) as ScriptArgs + } + args = + typeof argsOverride === 'function' + ? argsOverride(args ?? {}) + : { ...args, ...(argsOverride ?? {}) } + + const commonArgs = { + workspace: workspaceId!, + requestBody: args, + tag: await getRerunTagOverride(args) + } + if (job?.job_kind == 'script' || job?.job_kind == 'script_hub' || job?.job_kind == 'flow') { + let id + + if (job?.job_kind == 'script') { + id = await JobService.runScriptByHash({ + ...commonArgs, + hash: job.script_hash!, + skipPreprocessor: true + }) + } else if (job?.job_kind == 'script_hub') { + id = await JobService.runScriptByPath({ + ...commonArgs, + path: job.script_path!, + skipPreprocessor: true + }) + } else { + id = await JobService.runFlowByPath({ + ...commonArgs, + path: job.script_path!, + skipPreprocessor: true + }) + } + + // Offer to resolve this failure once the re-run succeeds. Captured here because the + // new job carries no back-pointer to the run it supersedes. An already-resolved + // failure needs no offer, and its note must not be restated as a supersession. + if (job && isJobResolvable(job) && !job.resolved && !actingUser?.operator) { + rememberRerunOrigin({ originalId: job.id, rerunId: id, workspace: workspaceId! }) + } + await onNavigate('/run/' + id + '?workspace=' + workspaceId) + } else { + sendUserToast('Cannot run this job immediately', true) + } + } catch (err) { + // A refusal is the interesting case here: the worker rejects a `dbt + // retry` whose run is no longer the saved one, and a caller who saw + // nothing happen would just click again. + sendUserToast(`Could not create job: ${err}`, true) + } finally { + runImmediatelyLoading = false + } + } + + // Whether a `dbt retry` submitted from here would resume THIS run: only the + // latest failure of a script is kept per principal, so a later run of it — or + // one that failed with nothing to rebuild — leaves this page's retry refused. + // Both entry points to it, the dropdown item and the graph's banner, ask. + let dbtResumable = $state(false) + $effect(() => { + const ws = workspaceId + const id = job?.id + const failed = job?.language === 'dbt' && job?.type === 'CompletedJob' && !job?.success + dbtResumable = false + if (!ws || !id || !failed) return + JobService.getDbtResumable({ workspace: ws, id }) + .then((held) => { + // The page may have moved on, or the workspace changed, in flight. + if (job?.id === id && workspaceId === ws) dbtResumable = held === id + }) + .catch(() => {}) + }) + + // The retry goes through `runImmediately` so it carries the run's own arguments + // and resolved tag: worker tags, debounce and concurrency keys interpolate from + // the submitted arguments at enqueue, while the ones being resumed are restored + // later, inside the worker. + async function resumeDbtRun() { + // Merged INTO the run's own block, not put in its place: those fields are + // what a `$args[command.vars.tenant]` tag or concurrency key interpolates + // from at enqueue. The worker ignores them for a retry — it rebuilds with + // the arguments the failed run had — but the queue has already read them. + await runImmediately((args) => ({ + ...args, + command: { + ...((args?.['command'] as Record<string, any> | undefined) ?? {}), + label: 'retry', + dbt_retry_job: job?.id + } + })) + } + + let showEditButton = $derived(!isRuleActiveInRulesets(rulesets ?? [], 'DisableDirectDeployment')) + + // Admins always pass the backend gate. Everyone else fails closed while the rulesets + // are still loading, so the item is never briefly offered to a restricted user. + let canSharePublicly = $derived( + !!actingUser?.is_admin || + !!actingUser?.is_super_admin || + (rulesets !== undefined && + canUserBypassRuleKindInRulesets( + rulesets, + 'RestrictPublicRunSharing', + actingUser ?? undefined + )) + ) + + // The dev workspace's editor is not one the session panel can host, so from a preview tab + // it opens in a new browser tab, as the session editors' own entry does. + function editInFork(e: Event | undefined, kind: 'script' | 'flow', itemPath: string) { + if (!embedded) { + return onEditInForkClick(e, kind, itemPath, { hasHref: true, prodWorkspace: workspaceId }) + } + const m = e as MouseEvent | undefined + if (m && (m.metaKey || m.ctrlKey || m.shiftKey || m.altKey || (m.button ?? 0) !== 0)) return + e?.preventDefault() + return openEditInFork(kind, itemPath, workspaceId) + } + + $effect(() => { + job?.id && lastJobId !== job.id && untrack(() => getConcurrencyKey(job)) + }) + $effect(() => { + workspaceId && runId && untrack(() => onRunsPageChange()) + }) + $effect(() => { + workspaceId && runId && jobLoader && untrack(() => onRunsPageChangeWithLoader()) + }) + $effect(() => { + job && untrack(() => onJobLoaded()) + }) + if (ownsPage) { + $effect(() => { + const status = getJobStatusKind(job) + if (status) { + setStatusFavicon(status) + } else { + resetFavicon() + } + }) + onDestroy(resetFavicon) + } + + // The bar folds these (`actionFolds` below) once its breadcrumb has given all it can: first the + // buttons drop their labels, then the plain actions go into one menu. Embedded, the buttons + // have a row of their own that wraps. + const compactBar = $derived(!embedded && pageHeader.actionFold >= 1) + const actionsInMenu = $derived(!embedded && pageHeader.actionFold >= 2) + + const isScriptJob = $derived(job?.job_kind === 'script') + const isRunnableJob = $derived( + job?.job_kind === 'script' || job?.job_kind === 'script_hub' || job?.job_kind === 'flow' + ) + const isHubFlowPreview = $derived(isFlowPreview(job?.job_kind) && isHubFlowPath(job?.script_path)) + const runsHref = $derived(`/runs/${job?.script_path}${!isScriptJob ? '?jobKind=flow' : ''}`) + const stem = $derived(job?.job_kind === 'script_hub' ? '/scripts' : `/${job?.job_kind}s`) + // A script is addressed by the hash this run executed. Embedded, that goes in the query: the + // host's tabs are keyed by an item's path, and a hash there would be a tab on no item. + const viewHref = $derived( + isScriptJob && embedded + ? `/scripts/get/${job?.script_path}?version=${job?.script_hash}` + : `${stem}/get/${isScriptJob ? job?.script_hash : job?.script_path}` + ) + const editHref = $derived(`${stem}/edit/${job?.script_path}?workspace=${workspaceId}`) + const forkPreviewLabel = $derived( + isHubFlowPreview + ? 'Fork flow into workspace' + : `Fork ${isFlowPreview(job?.job_kind) ? 'flow' : 'code'} preview` + ) + const viewLabel = $derived(`View ${job?.job_kind === 'script_hub' ? 'script' : job?.job_kind}`) + const canDelete = $derived( + !!job && 'deleted' in job && !job?.deleted && ($superadmin || (actingUser?.is_admin ?? false)) + ) + const canCancel = $derived( + !!job && job?.type != 'CompletedJob' && (!job?.schedule_path || job?.['running'] == true) + ) + const canDebug = $derived( + (job?.job_kind == 'flow' || isFlowPreview(job?.job_kind)) && + !!job?.['running'] && + job?.parent_job == undefined + ) + const canEdit = $derived( + (job?.job_kind === 'script' || job?.job_kind === 'flow') && + !actingUser?.operator && + editRights.canEditItem(isScriptJob ? 'script' : 'flow', job?.script_path ?? '', {}) + ) + const canEditInFork = $derived( + (job?.job_kind === 'script' || job?.job_kind === 'flow') && + !actingUser?.operator && + !showEditButton && + !isCloudHosted() && + editInForkAllowed(workspaceId, $userWorkspaces) + ) + /** Which actions the row has: they come and go as the job runs and completes, often while the + * row is folded into the menu, where the bar cannot see them change (`actionsVersion`). */ + const actionsVersion = $derived( + [ + canDelete, + canCancel, + forceCancel, + canDebug, + canRunNow, + canEdit, + canEditInFork, + dbtResumable, + !!job?.schedule_path, + persistentScriptDefinition !== undefined, + restartStep !== undefined && canRestart(restart) + ] + .map(Number) + .join('') + ) + + async function runAgain() { + // The form this lands on rebuilds the whole project. When resuming THIS run is the cheaper + // thing to do, name it so the form can offer that in one click rather than leaving the + // reader to know. + const from = dbtResumable + ? `${viewHref.includes('?') ? '&' : '?'}dbt_retry_from=${job?.id}` + : '' + onNavigate( + viewHref + from + `#${computeSharableHash(job?.args, await getRerunTagOverride(job?.args))}` + ) + } + + function cancel() { + if (!job?.id) return + cancelJob(job.id) + // The first cancel asks the job to stop; if it has not after three seconds, the same + // control offers to force it. + if (!forceCancel) setTimeout(() => (forceCancel = true), 3001) + } + + // The same actions as the row, most used first; the restart and session controls stay beside + // the menu, since each opens a popover of its own that a menu row cannot hold. + const menuItems = $derived.by((): Item[] => { + if (!job) return [] + const kind = isScriptJob ? 'script' : 'flow' + return [ + { displayName: viewLabel, icon: Code2, href: viewHref, hide: !isRunnableJob }, + { displayName: 'Run again', icon: RefreshCw, action: runAgain, hide: !isRunnableJob }, + { + displayName: 'dbt retry with same args', + icon: RefreshCw, + action: resumeDbtRun, + hide: !isRunnableJob || !dbtResumable + }, + { + displayName: 'Run immediately with same args', + icon: RefreshCw, + action: () => runImmediately(), + hide: !isRunnableJob + }, + { + displayName: 'Edit', + icon: Pen, + href: editHref, + action: () => ($initialArgsStore = job?.args), + disabled: !showEditButton, + hide: !canEdit + }, + { + displayName: editInForkLabel(workspaceId, $userWorkspaces), + icon: Pen, + href: buildForkEditUrl(kind, job.script_path ?? '', workspaceId), + action: (e) => editInFork(e, kind, job?.script_path ?? ''), + hide: !canEditInFork + }, + { + displayName: 'Run now', + icon: Play, + action: () => job?.id && runJobNow(job.id), + hide: !canRunNow + }, + { + displayName: 'Edit schedule', + icon: Calendar, + action: () => + job?.schedule_path && scheduleEditor?.openEdit(job.schedule_path, job.job_kind == 'flow'), + hide: !job.schedule_path + }, + { + displayName: forkPreviewLabel, + icon: GitBranch, + action: forkPreview, + hide: !(isFlowPreview(job.job_kind) || isScriptPreview(job.job_kind)) + }, + { + displayName: 'Current runs', + icon: Activity, + action: () => persistentScriptDrawer?.open?.(persistentScriptDefinition), + hide: persistentScriptDefinition === undefined + }, + { + displayName: 'View runs', + icon: List, + href: runsHref, + hide: !canDelete || !(job.job_kind === 'script' || job.job_kind === 'flow') + }, + { + displayName: 'Copy link for members', + icon: Users, + action: () => job && shareReadLink(job.id), + separatorTop: true + }, + { + displayName: 'Copy public link', + icon: Globe, + disabled: !canSharePublicly, + action: () => job && sharePublicLink(job.id) + }, + { + displayName: 'Show flow debug info', + icon: EllipsisVertical, + action: debugInfo, + hide: !canDebug + }, + { + displayName: forceCancel ? 'Force cancel' : 'Cancel', + icon: TimerOff, + type: 'delete', + action: cancel, + hide: !canCancel, + separatorTop: true + }, + { + displayName: 'Delete result, logs and args (admin only)', + icon: Trash, + type: 'delete', + action: () => job?.id && deleteCompletedJob(job.id), + hide: !canDelete + } + ] + }) +</script> + +<HighlightTheme /> + +<ScheduleEditor bind:this={scheduleEditor} /> + +{#if (job?.job_kind == 'flow' || isFlowPreview(job?.job_kind)) && job?.['running'] && job?.parent_job == undefined} + <Drawer bind:this={debugViewer} size="800px"> + <DrawerContent title="Debug Detail" on:close={debugViewer.closeDrawer}> + {#snippet actions()} + <div class="flex items-center gap-1"> + <div class="w-60 pt-2"> + <Toggle bind:checked={redactSensitive} options={{ right: 'Redact args/result/logs' }} /> + </div> + <Button + on:click={() => + copyToClipboard( + JSON.stringify(removeSensitiveInfos(debugContent, redactSensitive), null, 4) + )} + unifiedSize="md" + variant="subtle" + > + <div class="flex gap-2 items-center">Copy <ClipboardCopy /> </div> + </Button> + </div> + {/snippet} + <pre + ><code class="text-2xs p-2"> + <Highlight + language={json} + code={JSON.stringify(removeSensitiveInfos(debugContent, redactSensitive), null, 4)} + /> + </code></pre + > + </DrawerContent> + </Drawer> +{/if} +{#if !job || (job?.job_kind != 'flow' && job?.job_kind != 'flownode' && job?.job_kind != 'flowpreview')} + <JobLoader + bind:scriptProgress + bind:this={jobLoader} + bind:isLoading={testIsLoading} + bind:job + bind:jobUpdateLastFetch + workspaceOverride={workspaceId} + bind:notfound + bind:loadError + /> +{/if} + +{#snippet flowRestartButton( + state: ReturnType<typeof useNestedRestartState>, + step: string, + triggerStyle: 'button' | 'link' +)} + {#if job} + <FlowRestartButton + jobId={job.id} + selectedJobStep={step} + selectedJobStepType={state.selectedJobStepType} + restartBranchNames={state.restartBranchNames} + nestedPath={state.nestedRestartSupported ? state.nestedRestartPath : undefined} + nestedTopStepId={state.nestedRestartTopStepId} + nestedTopBranchOrIterationN={state.nestedRestartTopBranchOrIterationN} + presetIterationN={state.topLevelLoopIteration} + iterationCounts={state.iterationCounts} + nestedPathIterationCounts={state.nestedPathIterationCounts} + onRestartComplete={(newJobId) => { + onNavigate('/run/' + newJobId + '?workspace=' + workspaceId) + }} + flowPath={job.script_path} + flowVersionId={job.script_hash ? parseInt(job.script_hash, 16) : undefined} + disabled={!$enterpriseLicense} + enterpriseOnly={!$enterpriseLicense} + {triggerStyle} + unifiedSize="sm" + /> + {/if} +{/snippet} + +<Portal name="persistent-run"> + <PersistentScriptDrawer bind:this={persistentScriptDrawer} /> +</Portal> + +{#if loadError?.status === 403} + <div class="max-w-3xl px-4 mx-auto w-full"> + <div class="mt-6"> + <Alert type="warning" title="You don't have access to this run"> + <div class="flex flex-col gap-2"> + <p> + This run exists in <span class="font-semibold">{workspaceId}</span>, but you don't have + permission to view it. + </p> + <p> + Ask a colleague who can see it to open the run and use the + <span class="font-semibold">Share</span> button to send you a read-only link. Opening that + link will grant you access to this run (and its steps). + </p> + </div> + </Alert> + <div class="mt-4"> + <Button href="/runs" unifiedSize="md" variant="accent">Go to runs page</Button> + </div> + </div> + </div> +{:else if notfound || (job?.workspace_id != undefined && workspaceId != undefined && job?.workspace_id != workspaceId)} + {@const currentWorkspace = $userWorkspaces.find((w) => w.id === workspaceId)} + {@const otherWorkspaces = $userWorkspaces.filter((w) => w.id !== workspaceId)} + <div class="max-w-lg px-4 mx-auto w-full py-16"> + <div class="flex flex-col items-center text-center gap-3"> + <div class="rounded-full bg-surface-secondary p-3"> + <SearchX size={24} class="text-secondary" /> + </div> + <h1 class="text-lg font-semibold text-emphasis">Run not found</h1> + <p class="text-xs text-secondary"> + No run with ID + <span class="font-mono text-emphasis break-all">{runId}</span> + exists in + <span class="font-semibold text-emphasis">{currentWorkspace?.name ?? workspaceId}</span>. It + may belong to another workspace, or it may have been deleted. + </p> + </div> + + {#if otherWorkspaces.length > 0} + <div class="mt-8 flex flex-col gap-2"> + <h2 class="text-xs font-semibold text-emphasis">Look in another workspace</h2> + <div + class="flex flex-col rounded-md border border-light bg-surface-tertiary divide-y divide-border-light overflow-hidden" + > + {#each otherWorkspaces as workspace (workspace.id)} + <Button + variant="subtle" + unifiedSize="md" + btnClasses="h-auto justify-start text-left gap-3 px-3 py-2 rounded-none" + endIcon={{ icon: ArrowRight, classes: 'text-hint' }} + onClick={() => onNavigate(`/run/${runId}?workspace=${workspace.id}`)} + > + <WorkspaceIcon workspaceColor={workspace.color} padding="p-1" size={12} /> + <div class="flex flex-col min-w-0 grow"> + <span class="text-xs font-semibold text-emphasis truncate">{workspace.name}</span> + <span class="text-2xs text-secondary truncate">{workspace.id}</span> + </div> + </Button> + {/each} + </div> + </div> + {/if} + + <div class="mt-6 flex justify-center"> + <Button href="/runs" unifiedSize="md" variant="default">Go to runs page</Button> + </div> + </div> +{:else} + <Skeleton + class="max-w-7xl p-4 mx-auto w-full" + loading={!job} + layout={[ + // 1. Job Header + [{ h: 12, w: 100 }], + 1, + // 2. Progress Bar + [{ h: 2, w: 100 }], + 1.5 + ]} + /> + <!-- `section`, not an item: a run is not a workspace item the picker can open, so the trail + ends with its id as a plain name. --> + {#if embedded} + <div class="max-w-7xl mx-auto w-full px-4 pt-4 flex flex-wrap items-center justify-end gap-2"> + {@render runActions()} + </div> + {:else} + <PageHeaderContent + section={{ label: `run/${runId}` }} + actions={runActions} + actionFolds={2} + {actionsVersion} + /> + {/if} + + {#snippet runActions()} + {#if actionsInMenu} + {#if restartStep !== undefined && canRestart(restart)} + {@render flowRestartButton(restart, restartStep, 'button')} + {/if} + {#if canEdit && showEditButton} + <OpenInSessionButton + source={{ + target: { kind: isScriptJob ? 'script' : 'flow', path: job?.script_path ?? '' }, + workspaceId: workspaceId ?? undefined + }} + btnProps={{ unifiedSize: 'sm' }} + /> + {/if} + <Dropdown items={menuItems} customWidth={260}> + {#snippet buttonReplacement()} + <Button + nonCaptureEvent + variant="default" + unifiedSize="sm" + iconOnly + title="Run actions" + startIcon={{ icon: EllipsisVertical }} + /> + {/snippet} + </Dropdown> + {:else} + {@render runActionsRow()} + {/if} + {/snippet} + + {#snippet runActionsRow()} + {#if canDelete} + <Dropdown + items={[ + { + displayName: 'Delete result, logs and args (admin only)', + action: () => { + job?.id && deleteCompletedJob(job.id) + }, + type: 'delete' + } + ]} + > + {#snippet buttonReplacement()} + <Button nonCaptureEvent variant="default" unifiedSize="sm" startIcon={{ icon: Trash }} /> + {/snippet} + </Dropdown> + {#if job?.job_kind === 'script' || job?.job_kind === 'flow'} + <Button + href={runsHref} + variant="default" + unifiedSize="sm" + iconOnly={compactBar} + title="View runs" + startIcon={{ icon: List }} + > + View runs + </Button> + {/if} + {/if} + {#if job} + <Dropdown + customWidth={280} + items={[ + { + displayName: 'Copy link for members', + icon: Users, + tooltip: + 'Read-only link to this run for another member of this workspace. They must be logged in.', + action: () => job && shareReadLink(job.id) + }, + { + displayName: 'Copy public link', + icon: Globe, + disabled: !canSharePublicly, + tooltip: canSharePublicly + ? "Read-only link that anyone on the internet can open, without logging in. It shows a minimal version of this page: this run's inputs, result and logs, and for a flow its graph plus every step's inputs, result, logs and code. The link cannot be revoked." + : 'Sharing a run publicly is restricted in this workspace. Ask an admin to share it, or to grant you a bypass on the ruleset.', + action: () => job && sharePublicLink(job.id) + } + ]} + > + {#snippet buttonReplacement()} + <Button + nonCaptureEvent + variant="default" + unifiedSize="sm" + iconOnly={compactBar} + title="Share" + startIcon={{ icon: Share2 }} + > + Share + </Button> + {/snippet} + </Dropdown> + {/if} + {#if (job?.job_kind == 'flow' || isFlowPreview(job?.job_kind)) && job?.['running'] && job?.parent_job == undefined} + <div class="inline"> + <Dropdown + items={[ + { + displayName: 'Show Flow Debug Info', + action: () => { + debugInfo() + } + } + ]} + class="h-auto" + > + {#snippet buttonReplacement()} + <Button nonCaptureEvent unifiedSize="sm" variant="subtle"> + <div class="flex flex-row items-center"> + <EllipsisVertical size={14} /> + </div> + </Button> + {/snippet} + </Dropdown> + </div> + {/if} + {#if isFlowPreview(job?.job_kind) || isScriptPreview(job?.job_kind)} + <Button + unifiedSize="sm" + variant="default" + iconOnly={compactBar} + title={isHubFlowPreview + ? 'Fork flow into workspace' + : `Fork ${isFlowPreview(job?.job_kind) ? 'flow' : 'code'} preview`} + startIcon={{ icon: GitBranch }} + on:click={forkPreview} + > + {isHubFlowPreview + ? 'Fork flow into workspace' + : `Fork ${isFlowPreview(job?.job_kind) ? 'flow' : 'code'} preview`} + </Button> + {/if} + {#if persistentScriptDefinition !== undefined} + <Button + unifiedSize="sm" + variant="default" + iconOnly={compactBar} + title="Current runs" + startIcon={{ icon: Activity }} + on:click={() => { + persistentScriptDrawer?.open?.(persistentScriptDefinition) + }} + > + Current runs + </Button> + {/if} + {#if canRunNow} + <Button + unifiedSize="md" + variant="default" + startIcon={{ icon: Play }} + on:click={() => job?.id && runJobNow(job.id)} + title="Start this job now instead of at its scheduled time, skipping any remaining delay or sleep. It keeps the same id, and a concurrency limit is still enforced." + > + Run now + </Button> + {/if} + {#if job && job?.type != 'CompletedJob' && (!job?.schedule_path || job?.['running'] == true)} + {#if !forceCancel} + <Button + unifiedSize="sm" + variant="accent" + destructive + startIcon={{ icon: TimerOff }} + on:click|once={() => { + if (job?.id) { + cancelJob(job?.id) + setTimeout(() => { + forceCancel = true + }, 3001) + } + }} + title={`Cancel the ${job?.job_kind === 'script' ? 'script' : job?.job_kind === 'flow' ? 'flow' : 'job'}`} + > + Cancel + </Button> + {:else} + <Button + unifiedSize="sm" + variant="accent" + destructive + startIcon={{ icon: TimerOff }} + on:click|once={() => { + if (job?.id) { + cancelJob(job?.id) + } + }} + > + Force Cancel + </Button> + {/if} + {/if} + {#if job?.schedule_path} + <Button + unifiedSize="sm" + variant="default" + on:click={() => { + if (!job || !job.schedule_path) { + return + } + scheduleEditor?.openEdit(job.schedule_path, job.job_kind == 'flow') + }} + startIcon={{ icon: Calendar }}>Edit schedule</Button + > + {/if} + {#if restartStep !== undefined && canRestart(restart)} + {@render flowRestartButton(restart, restartStep, 'button')} + {/if} + {#if job?.job_kind === 'script' || job?.job_kind === 'script_hub' || job?.job_kind === 'flow'} + <Button + on:click={runAgain} + unifiedSize="sm" + variant="default" + iconOnly={compactBar} + title="Run again" + startIcon={{ icon: RefreshCw }} + loading={runImmediatelyLoading} + dropdownItems={[ + // A failed dbt run's cheap next step is resuming its failed and skipped + // nodes rather than rebuilding the project, and `dbt_command` is the + // only argument that differs. Offered first, and only while the saved + // failure is still this run — which is what `dbtResumable` answers. + ...(dbtResumable ? [{ label: 'dbt retry with same args', onClick: resumeDbtRun }] : []), + { + label: 'Run immediately with same args', + onClick: () => runImmediately() + } + ]} + > + Run again + </Button> + {/if} + {#if job?.job_kind === 'script' || job?.job_kind === 'flow'} + {#if !actingUser?.operator} + {#if editRights.canEditItem(isScriptJob ? 'script' : 'flow', job?.script_path ?? '', {})} + <Button + href={`${stem}/edit/${job?.script_path}?workspace=${workspaceId}`} + on:click={() => { + $initialArgsStore = job?.args + }} + unifiedSize="sm" + variant="default" + disabled={!showEditButton} + iconOnly={compactBar} + title="Edit" + startIcon={{ icon: Pen }}>Edit</Button + > + {#if showEditButton} + <!-- Opens the deployed runnable at this job's path, like Edit — unlike + "View script", which pins the hash this run executed. Same gate as + Edit: where direct deployment is off, the way in is "Edit in fork". --> + <OpenInSessionButton + source={{ + target: { kind: isScriptJob ? 'script' : 'flow', path: job?.script_path ?? '' }, + workspaceId: workspaceId ?? undefined + }} + btnProps={{ unifiedSize: 'sm' }} + /> + {/if} + {/if} + {#if !showEditButton && !isCloudHosted() && editInForkAllowed(workspaceId, $userWorkspaces)} + <Button + href={buildForkEditUrl( + isScriptJob ? 'script' : 'flow', + job?.script_path ?? '', + workspaceId + )} + onClick={(e) => editInFork(e, isScriptJob ? 'script' : 'flow', job?.script_path ?? '')} + unifiedSize="sm" + variant="default" + iconOnly={compactBar} + title={editInForkLabel(workspaceId, $userWorkspaces)} + startIcon={{ icon: Pen }}>{editInForkLabel(workspaceId, $userWorkspaces)}</Button + > + {/if} + {/if} + {/if} + {#if job?.job_kind === 'script' || job?.job_kind === 'script_hub' || job?.job_kind === 'flow'} + <Button + href={viewHref} + unifiedSize="sm" + variant="accent" + iconOnly={compactBar} + title="View {job?.job_kind === 'script_hub' ? 'script' : job?.job_kind}" + startIcon={{ + icon: + job?.job_kind === 'script' || job?.job_kind === 'script_hub' + ? Code2 + : job?.job_kind === 'flow' + ? BarsStaggered + : Code2 + }} + > + View {job?.job_kind === 'script_hub' ? 'script' : job?.job_kind} + </Button> + {/if} + {/snippet} + <div class={twMerge('w-full', isNotFlow(job?.job_kind) && 'pb-8')}> + <!-- Flow Detail Header Card --> + <div class="max-w-7xl mx-auto px-4 pt-4"> + <Skeleton loading={!job} layout={[[24]]} /> + {#if job} + <JobDetailHeader + {job} + {scheduleEditor} + displayPersistentScriptDefinition={!!persistentScriptDefinition} + openPersistentScriptDrawer={() => { + persistentScriptDrawer?.open?.(persistentScriptDefinition) + }} + {concurrencyKey} + /> + {/if} + </div> + {#if job?.['deleted']} + <div class="max-w-7xl mx-auto w-full px-4 mt-6"> + <Alert type="error" title="Deleted"> + The content of this run was deleted (by an admin, no less) + </Alert> + </div> + <div class="my-4"></div> + {/if} + + <!-- Flow Progress Bar (for flows only) --> + {#if job?.job_kind === 'flow' || job?.job_kind === 'flowpreview'} + <div class="max-w-7xl mx-auto w-full px-4 flex flex-col gap-4 mt-2"> + <FlowProgressBar + {job} + bind:currentSubJobProgress={scriptProgress} + class="w-full" + textPosition="bottom" + slim + showStepId + > + {#snippet errorAction()} + <!-- A saved agent's run is its one step: naming it adds nothing. --> + {#if failedTopLevelStep && failedTopLevelStep !== AGENT_STEP_ID} + <span>at step {failedTopLevelStep}</span> + {#if $enterpriseLicense && canRestart(failedRestart)} + <span>·</span> + {@render flowRestartButton(failedRestart, failedTopLevelStep, 'link')} + <span>on this flow version, or on a new one after you fix it</span> + {/if} + {/if} + {/snippet} + </FlowProgressBar> + {#if suspendStatus} + <FlowExecutionStatus + {job} + {isOwner} + {suspendStatus} + innerModules={job?.flow_status?.modules} + /> + {/if} + </div> + {/if} + + <!-- Arguments and actions --> + <div class="max-w-7xl mx-auto w-full px-4 mt-12"> + <div class="text-xs text-emphasis font-semibold mb-1">Inputs</div> + <div class="flex flex-col gap-y-6"> + <JobArgs + workspace={job?.workspace_id ?? workspaceId ?? 'no_w'} + id={job?.id} + args={job?.args} + /> + {#if job && currentJobIsLongRunning && showExplicitProgressTip && !scriptProgress && 'running' in job} + <Alert + class="p-1 flex flex-row relative text-center" + size="xs" + type="info" + title="tip: Track progress of longer jobs" + tooltip="For better transparency and verbosity, you can try setting progress from within the script." + documentationLink="https://www.windmill.dev/docs/advanced/explicit_progress" + > + <button + type="button" + onclick={() => { + localStorage.setItem('hideExplicitProgressTip', 'true') + showExplicitProgressTip = false + }} + class="absolute m-2 top-0 right-0 inline-flex rounded-md bg-surface-secondary text-primary hover:text-primary focus:outline-none" + > + <span class="sr-only">Close</span> + <svg class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true"> + <path + d="M6.28 5.22a.75.75 0 00-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 101.06 1.06L10 11.06l3.72 3.72a.75.75 0 101.06-1.06L11.06 10l3.72-3.72a.75.75 0 00-1.06-1.06L10 8.94 6.28 5.22z" + /> + </svg> + </button> + </Alert> + {/if} + </div> + </div> + + {#if job} + <ScriptRetryChain {job} {onNavigate} /> + {/if} + + {#if isNotFlow(job?.job_kind)} + {#if ['python3', 'bun', 'deno'].includes(job?.language ?? '') && (job?.job_kind == 'script' || isScriptPreview(job?.job_kind))} + <ExecutionDuration {job} bind:longRunning={currentJobIsLongRunning} /> + {/if} + <div class="max-w-7xl mx-auto w-full px-4 mb-10"> + {#if job?.workflow_as_code_status && job.job_kind !== 'aiagent'} + <div class="mr-2 sm:mr-0 mt-12 mb-6"> + <h3 class="text-xs font-semibold text-emphasis mb-1">Workflow Timeline</h3> + <div class="border rounded-md overflow-hidden"> + <WorkflowTimeline + flow_status={asWorkflowStatus(job.workflow_as_code_status)} + flowDone={job.type == 'CompletedJob'} + stepResults={getStepResults(job.workflow_as_code_status)} + result={job.result} + success={(job as any).success !== false} + jobId={job.id} + /> + </div> + </div> + {/if} + {#if scriptProgress} + <JobProgressBar {job} {scriptProgress} class="py-4" hideStepTitle={true} /> + {/if} + + <!-- The models a dbt run touches, above its result: the run page is + where you land on a running job, and the per-node table below + only exists once the job has produced one. --> + {#if job?.language === 'dbt' && job?.script_path} + <div class="mr-2 sm:mr-0 mt-12"> + <h3 class="text-xs font-semibold text-emphasis mb-1">Models</h3> + <DbtRunGraph + scriptPath={job.script_path} + jobId={job.id} + running={job.type !== 'CompletedJob'} + result={job.type === 'CompletedJob' ? job.result : undefined} + scriptHash={job.script_hash} + runArgs={job.args} + canResume={dbtResumable} + onResume={resumeDbtRun} + /> + </div> + {/if} + + <!-- Result Section (moved outside tabs) --> + {#if job} + <div class="mr-2 sm:mr-0 mt-12 mb-6"> + <h3 class="text-xs font-semibold text-emphasis mb-1">Result</h3> + <div class="border rounded-md bg-surface-tertiary p-4 overflow-auto max-h-screen"> + {#if job.result_stream || (job.type == 'CompletedJob' && job.result !== undefined)} + <DisplayResult + workspaceId={job?.workspace_id} + result_stream={job.result_stream} + jobId={job?.id} + result={job.result} + language={job?.language} + isTest={false} + /> + {:else} + <div class="text-secondary text-sm">No output is available yet</div> + {/if} + </div> + </div> + {#if job.id && job.workspace_id} + <UpstreamSnapshotsPanel args={job.args} /> + <DispatchEventsPanel workspace={job.workspace_id} jobId={job.id} /> + {/if} + {/if} + + <!-- Logs and outputs--> + <div class="mr-2 sm:mr-0 mt-6"> + <Tabs bind:selected={viewTab}> + <Tab value="logs" label="Logs" /> + <Tab value="stats" label="Metrics" /> + <Tab value="traces" label="Traces" /> + <Tab value="assets" label="Assets" /> + {#if isScriptPreview(job?.job_kind)} + <Tab value="code" label="Code" /> + {/if} + </Tabs> + + <Skeleton loading={!job} layout={[[5]]} /> + {#if job} + <div + class={twMerge( + 'flex flex-row border rounded-md p-2 mt-2 overflow-auto min-h-[600px]', + viewTab == 'logs' ? 'bg-surface-secondary' : 'bg-surface-tertiary' + )} + > + {#if viewTab == 'logs'} + <div class="w-full"> + <LogViewer + jobId={job.id} + duration={job?.['duration_ms']} + mem={job?.['mem_peak']} + isLoading={job?.['running'] == false} + content={job?.logs} + tag={job?.tag} + /> + </div> + {:else if viewTab == 'assets'} + <div class="w-full"> + <JobAssetsViewer {job} /> + </div> + {:else if viewTab == 'traces'} + <div class="w-full"> + <JobOtelTraces jobId={job.id} /> + </div> + {:else if viewTab == 'code'} + {#if job && 'raw_code' in job && job.raw_code} + <div class="text-xs"> + <HighlightCode lines language={job.language} code={job.raw_code} /> + </div> + {:else if job} + <span class="text-sm">No code available</span> + {:else} + <Skeleton layout={[[5]]} /> + {/if} + {:else if viewTab == 'stats'} + <div class="w-full"> + <MemoryFootprintViewer jobId={job.id} {jobUpdateLastFetch} /> + </div> + {:else} + <div class="w-full p-4 text-secondary">Select a tab to view content</div> + {/if} + </div> + {/if} + </div> + </div> + {:else if !job?.['deleted']} + <div class="mt-10"></div> + + <div class="w-full mt-10"> + {#if job?.id} + <FlowStatusViewer + jobId={job?.id ?? ''} + onJobsLoaded={({ job: newJob }) => { + job = newJob + }} + onDone={({ job: newJob }) => { + job = newJob + }} + initialJob={job} + {workspaceId} + bind:selectedJobStep + bind:suspendStatus + bind:isOwner + bind:localModuleStates={graphModuleStates} + bind:expandedSubflows + /> + {:else} + <Skeleton layout={[[5]]} /> + {/if} + </div> + {/if} + </div> +{/if} + +<FlowAssetsHandler + modules={job?.raw_flow?.modules ?? []} + enableDbExplore + enablePathScriptAndFlowAssets +/> diff --git a/frontend/src/lib/components/runs/RunRow.svelte b/frontend/src/lib/components/runs/RunRow.svelte index 959ee2fd06..249933f3b4 100644 --- a/frontend/src/lib/components/runs/RunRow.svelte +++ b/frontend/src/lib/components/runs/RunRow.svelte @@ -1,5 +1,4 @@ <script lang="ts"> - import { base } from '$lib/base' import { goto } from '$lib/navigation' import type { Job } from '$lib/gen' import { @@ -22,6 +21,7 @@ import { forLater } from '$lib/forLater' import { twMerge } from 'tailwind-merge' import Portal from '$lib/components/Portal.svelte' + import { useHostedPage } from '../hostedPage' import WaitTimeWarning from '../common/waitTimeWarning/WaitTimeWarning.svelte' import DropdownV2 from '../DropdownV2.svelte' @@ -30,6 +30,7 @@ import './runs-grid.css' const dispatch = createEventDispatcher() + const hosted = useHostedPage() interface Props { job: Job @@ -61,7 +62,10 @@ </script> <Portal name="run-row"> - <ScheduleEditor onUpdate={() => goto('/schedules')} bind:this={scheduleEditor} /> + <ScheduleEditor + onUpdate={() => (hosted ? hosted.openLink('/schedules') : goto('/schedules'))} + bind:this={scheduleEditor} + /> </Portal> <!-- svelte-ignore a11y_click_events_have_key_events --> <!-- svelte-ignore a11y_no_static_element_interactions --> @@ -166,12 +170,12 @@ {/if} {#if job && job.is_flow_step && job.parent_job} <br /> Step of flow - <a href={`${base}/run/${job.parent_job}?workspace=${job.workspace_id}`}> + <a href={`/run/${job.parent_job}?workspace=${job.workspace_id}`}> {truncateRev(job.parent_job, 10)} </a> {:else if job && job.parent_job} <br /> Parent - <a href={`${base}/run/${job.parent_job}?workspace=${job.workspace_id}`}> + <a href={`/run/${job.parent_job}?workspace=${job.workspace_id}`}> {truncateRev(job.parent_job, 10)} </a> {/if} @@ -322,7 +326,7 @@ <div class="flex justify-end pr-2"> <a target="_blank" - href="{base}/run/{job.id}?workspace={job.workspace_id}" + href="/run/{job.id}?workspace={job.workspace_id}" class={twMerge( 'text-right float-right px-2', selected ? 'text-accent' : 'text-secondary hover:text-accent' diff --git a/frontend/src/lib/components/runs/RunsTable.svelte b/frontend/src/lib/components/runs/RunsTable.svelte index 479c785943..be997f1096 100644 --- a/frontend/src/lib/components/runs/RunsTable.svelte +++ b/frontend/src/lib/components/runs/RunsTable.svelte @@ -13,7 +13,6 @@ Wrench } from 'lucide-svelte' import Popover from '../Popover.svelte' - import { userStore, workspaceStore } from '$lib/stores' import './runs-grid.css' import { useKeyPressed } from '$lib/svelte5Utils.svelte' import { twMerge } from 'tailwind-merge' @@ -21,6 +20,9 @@ import DropdownMenu, { type Props as DropdownMenuProps } from '../DropdownMenu.svelte' import { clickOutside, isJobCancelable, isJobReRunnable, isJobResolvable } from '$lib/utils' import { goto } from '$lib/navigation' + import { useHostedPage } from '../hostedPage' + import { useOperatingUser, useOperatingWorkspace } from '../operatingWorkspace.svelte' + import { withWorkspaceParam } from '../sessions/sessionMode.svelte' import BarsStaggered from '../icons/BarsStaggered.svelte' interface Props { @@ -201,6 +203,16 @@ } const dispatch = createEventDispatcher() + const hosted = useHostedPage() + const operatingWorkspace = useOperatingWorkspace() + const operatingUser = useOperatingUser() + + // Under a host the link opens where it decides, in the workspace the run belongs to: the + // document's own router would leave the host for the navigation workspace. + function open(href: string) { + if (!hosted) goto(href) + else hosted.openLink(withWorkspaceParam(href, selectedWorkspace ?? $operatingWorkspace)) + } let scrollToIndex = $state(0) @@ -272,7 +284,7 @@ actions.push({ label: 'Show run details', icon: ExternalLinkIcon, - onClick: () => goto(`/run/${selectedIds[0]}`) + onClick: () => open(`/run/${selectedIds[0]}`) }) const job = flatJobs?.find( (jobOrDate) => jobOrDate.type === 'job' && jobOrDate.job.id === selectedIds[0] @@ -282,14 +294,20 @@ actions.push({ label: 'Go to script page', icon: Code2Icon, - onClick: () => goto(`/scripts/get/${job.job.script_hash}`) + onClick: () => + open( + // A host addresses an item by its path, and pins a version in the query. + hosted + ? `/scripts/get/${job.job.script_path}?version=${job.job.script_hash}` + : `/scripts/get/${job.job.script_hash}` + ) }) } if (job.job.job_kind === 'flow') { actions.push({ label: 'Go to flow page', icon: BarsStaggered, - onClick: () => goto(`/flows/get/${job.job.script_path}`) + onClick: () => open(`/flows/get/${job.job.script_path}`) }) } } @@ -314,7 +332,7 @@ onHover: (hover) => (hoveredDropdownAction = hover ? 'cancel' : null) }) // Operators are rejected by the endpoint, so offering the action would only 403. - const canResolve = !$userStore?.operator + const canResolve = !operatingUser.current?.operator const resolvable = canResolve ? selectedIdsPossibleActions.resolvableJobIds.length : 0 const unresolvable = canResolve ? selectedIdsPossibleActions.unresolvableJobIds.length : 0 if (resolvable) @@ -401,7 +419,7 @@ ? jobCountString(jobs.length + externalJobs.length, lastFetchWentToEnd) : ''}<Tooltip>{externalJobs.length} jobs obscured</Tooltip> </div> - {:else if $workspaceStore !== 'admins' && omittedObscuredJobs} + {:else if $operatingWorkspace !== 'admins' && omittedObscuredJobs} <div class="flex flex-row"> {jobs ? jobCountString(jobs.length, lastFetchWentToEnd) : ''} <Popover> diff --git a/frontend/src/lib/components/runs/ScriptRetryChain.svelte b/frontend/src/lib/components/runs/ScriptRetryChain.svelte index 2b2fc2449b..f7334467da 100644 --- a/frontend/src/lib/components/runs/ScriptRetryChain.svelte +++ b/frontend/src/lib/components/runs/ScriptRetryChain.svelte @@ -6,7 +6,10 @@ import { resource } from 'runed' import { canSkipRetryChainQuery } from './scriptRetryChain' - let { job }: { job: Job } = $props() + let { + job, + onNavigate = goto + }: { job: Job; onNavigate?: (url: string) => void | Promise<void> } = $props() type AttemptColor = 'green' | 'red' | 'blue' | 'gray' type Attempt = { id: string; color: AttemptColor; current: boolean } @@ -141,7 +144,7 @@ size="xs" color="gray" variant="border" - onclick={() => goto(`/run/${self?.handledJob}?workspace=${ws}`)} + onclick={() => onNavigate(`/run/${self?.handledJob}?workspace=${ws}`)} > Handled run </Button> @@ -163,7 +166,7 @@ size="xs" color={attempt.color} variant={attempt.current ? 'contained' : 'border'} - onclick={() => goto(`/run/${attempt.id}?workspace=${ws}`)} + onclick={() => onNavigate(`/run/${attempt.id}?workspace=${ws}`)} > {i === 0 ? 'Original' : `Attempt ${i}`} </Button> @@ -180,7 +183,7 @@ size="xs" color={handler.color} variant="border" - onclick={() => goto(`/run/${handler.id}?workspace=${ws}`)} + onclick={() => onNavigate(`/run/${handler.id}?workspace=${ws}`)} > {HANDLER_LABEL[handler.kind]} </Button> diff --git a/frontend/src/lib/components/runs/rerunResolution.svelte.ts b/frontend/src/lib/components/runs/rerunResolution.svelte.ts index 87911d6c8d..f57d7400c8 100644 --- a/frontend/src/lib/components/runs/rerunResolution.svelte.ts +++ b/frontend/src/lib/components/runs/rerunResolution.svelte.ts @@ -37,7 +37,7 @@ export function offerToResolveOriginal(origin: PendingRerun, onResolved?: () => 'success', [ { - label: 'Resolve the original failure', + label: 'Resolve the original run', callback: async () => { const affected = await JobService.resolveCompletedJobs({ workspace: origin.workspace, @@ -50,10 +50,10 @@ export function offerToResolveOriginal(origin: PendingRerun, onResolved?: () => } }) if (affected.length === 0) { - sendUserToast('Could not resolve the original failure', true) + sendUserToast('Could not resolve the original run', true) return } - sendUserToast('Original failure resolved') + sendUserToast('Original run resolved') onResolved?.() } } diff --git a/frontend/src/lib/components/runs/runsFilter.ts b/frontend/src/lib/components/runs/runsFilter.ts index 3ff8a5e54b..cef8cca6e9 100644 --- a/frontend/src/lib/components/runs/runsFilter.ts +++ b/frontend/src/lib/components/runs/runsFilter.ts @@ -186,7 +186,7 @@ export function buildRunsFilterSearchbarSchema({ ], label: 'Resolution', icon: Wrench, - description: 'Filter by whether a failure has been marked as handled' + description: 'Filter by whether a failed or canceled run has been marked as handled' }, job_trigger_kind: { type: 'oneof' as const, @@ -254,7 +254,7 @@ export const buildRunsFilterPresets = ({ { name: 'Hide schedules', value: 'job_trigger_kind:\\ !schedule' }, { name: 'Hide future jobs', value: 'show_future_jobs:\\ false' }, { name: 'Show skipped', value: 'show_skipped:\\ true' }, - { name: 'Hide resolved failures', value: 'resolved:\\ unresolved' }, + { name: 'Hide resolved runs', value: 'resolved:\\ unresolved' }, ...(isSuperAdminOrDevops && isAdminsWorkspace ? [{ name: 'All workspaces', value: 'all_workspaces:\\ true' }] : []) diff --git a/frontend/src/lib/components/s3TableOps.test.ts b/frontend/src/lib/components/s3TableOps.test.ts new file mode 100644 index 0000000000..f32ce47c56 --- /dev/null +++ b/frontend/src/lib/components/s3TableOps.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from 'vitest' +import { datatypeOf, jsonTableRows, serverTableFormat } from './s3TableOps' +import { dbColumnKind } from './dbTableFilters' + +describe('serverTableFormat', () => { + it('pages delimited text and newline-delimited JSON through the csv reader', () => { + expect(serverTableFormat('a/b.parquet')).toBe('parquet') + for (const key of ['a.csv', 'a.TSV', 'a.jsonl', 'a.ndjson']) { + expect(serverTableFormat(key)).toBe('csv') + } + }) + + it('leaves plain JSON to the browser', () => { + expect(serverTableFormat('a.json')).toBeUndefined() + expect(serverTableFormat('a.txt')).toBeUndefined() + }) +}) + +describe('datatypeOf', () => { + it('maps Arrow types to the kinds the grid filters by', () => { + expect(dbColumnKind(datatypeOf('Int64'))).toBe('number') + expect(dbColumnKind(datatypeOf('UInt8'))).toBe('number') + expect(dbColumnKind(datatypeOf('Float64'))).toBe('number') + expect(dbColumnKind(datatypeOf('Decimal128(21, 1)'))).toBe('number') + expect(dbColumnKind(datatypeOf('Boolean'))).toBe('boolean') + expect(dbColumnKind(datatypeOf('Utf8View'))).toBe('text') + }) + + it('names a nested type without its field list', () => { + expect(datatypeOf('List(Field { name: "item", data_type: Utf8 })')).toBe('list') + expect(datatypeOf('Timestamp(Microsecond, None)')).toBe('timestamp') + }) +}) + +describe('jsonTableRows', () => { + it('keeps objects and wraps other elements in a value column', () => { + expect(jsonTableRows([{ a: 1 }, 2, null])).toEqual([{ a: 1 }, { value: 2 }, { value: null }]) + }) + + it('has no table for an empty array or a non-array', () => { + expect(jsonTableRows([])).toBeUndefined() + expect(jsonTableRows({ a: 1 })).toBeUndefined() + }) +}) diff --git a/frontend/src/lib/components/s3TableOps.ts b/frontend/src/lib/components/s3TableOps.ts new file mode 100644 index 0000000000..f5d7bd758b --- /dev/null +++ b/frontend/src/lib/components/s3TableOps.ts @@ -0,0 +1,170 @@ +import { HelpersService, OpenAPI } from '$lib/gen' +import { getHeaders } from '$lib/gen/core/request' +import { ColumnIdentity, type ColumnDef } from './apps/components/display/dbtable/utils' +import type { IDbTableOps } from './dbOps' + +/** Files the server can page through as a table, without reading them whole. */ +export function serverTableFormat(fileKey: string): 'parquet' | 'csv' | undefined { + const key = fileKey.toLowerCase() + if (key.endsWith('.parquet')) return 'parquet' + if (/\.(csv|tsv|jsonl|ndjson)$/.test(key)) return 'csv' + return undefined +} + +export type S3TableSource = { + workspace: string + fileKey: string + storage?: string + s3ResourcePath?: string + csvSeparator?: string + csvHasHeader?: boolean +} + +type Chunk = { + columns: string[] + column_types?: string[] + rows: Record<string, unknown>[] + csv_separator?: string +} + +/** An Arrow type as the SQL type name the grid filters and formats by. */ +export function datatypeOf(arrowType: string | undefined): string { + const t = arrowType ?? '' + if (/^U?Int\d+$/.test(t)) return 'bigint' + if (/^Float\d+$/.test(t)) return 'double' + if (/^Decimal/.test(t)) return 'decimal' + if (t === 'Boolean') return 'boolean' + if (/^(Large)?Utf8/.test(t)) return 'text' + // A nested type spells out its fields, e.g. `List(Field { name: "item", … })`. + return t.split('(')[0].toLowerCase() || 'text' +} + +/** Read-only table ops over an object storage file, paged, searched, filtered and sorted + * by the server, with the CSV separator it read the file with (guessed when none is given). + */ +export async function s3TableOps( + source: S3TableSource +): Promise<{ ops: IDbTableOps; csvSeparator?: string }> { + const format = serverTableFormat(source.fileKey) + if (!format) throw new Error(`${source.fileKey} cannot be read as a table`) + const common = { + workspace: source.workspace, + path: source.fileKey, + storage: source.storage, + s3ResourcePath: source.s3ResourcePath + } + const csvOptions: { csvSeparator?: string; csvHasHeader?: boolean } = + format === 'csv' ? { csvSeparator: source.csvSeparator, csvHasHeader: source.csvHasHeader } : {} + const filtersParam = (columnFilters: Record<string, unknown> | undefined) => + columnFilters && Object.keys(columnFilters).length ? JSON.stringify(columnFilters) : undefined + const searchParam = (quicksearch: string) => quicksearch.trim() || undefined + + async function loadChunk(params: { + offset: number + limit: number + quicksearch?: string + columnFilters?: Record<string, unknown> + orderBy?: string + isDesc?: boolean + }): Promise<Chunk> { + const data = { + ...common, + ...csvOptions, + offset: params.offset, + limit: params.limit, + searchTerm: searchParam(params.quicksearch ?? ''), + filters: filtersParam(params.columnFilters), + sortCol: params.orderBy, + sortDesc: params.isDesc + } + return (await (format === 'parquet' + ? HelpersService.loadParquetPreview(data) + : HelpersService.loadCsvPreview(data))) as Chunk + } + + const head = await loadChunk({ offset: 0, limit: 0 }) + // Later reads reuse the separator the server guessed, rather than each guessing again. + if (format === 'csv') csvOptions.csvSeparator ??= head.csv_separator + const colDefs: ColumnDef[] = head.columns.map((field, i) => ({ + field, + datatype: datatypeOf(head.column_types?.[i]), + // The server cannot read a struct, map or union as text to filter it. + filterable: !/^(Struct|Map|Union)/.test(head.column_types?.[i] ?? ""), + defaultvalue: '', + isprimarykey: false, + isidentity: ColumnIdentity.No, + isnullable: 'YES', + isenum: false + })) + + const ops: IDbTableOps = { + dbType: 'duckdb', + tableKey: source.fileKey.split('/').pop() ?? source.fileKey, + colDefs, + getCount: async ({ quicksearch, columnFilters }) => { + const res = await HelpersService.loadTableRowCount({ + ...common, + ...csvOptions, + searchTerm: searchParam(quicksearch), + filters: filtersParam(columnFilters) + }) + return res.count ?? 0 + }, + getRows: async ({ + offset, + limit, + quicksearch, + columnFilters, + order_by, + is_desc, + explicitSort + }) => + ( + await loadChunk({ + offset, + limit, + quicksearch, + columnFilters, + // Unsorted, a file keeps its own row order. + orderBy: explicitSort ? order_by : undefined, + isDesc: is_desc + }) + ).rows + } + return { ops, csvSeparator: head.csv_separator } +} + +/** Plain JSON cannot be paged by the server, so only a file this small is read whole into + * the browser to be shown as a table. */ +export const JSON_TABLE_MAX_BYTES = 10 * 1024 * 1024 + +export function isJsonFile(fileKey: string): boolean { + return fileKey.toLowerCase().endsWith('.json') +} + +/** Rows of a JSON array, an element that is not an object becoming a one-column row; + * undefined for anything else. */ +export function jsonTableRows(value: unknown): Record<string, unknown>[] | undefined { + if (!Array.isArray(value) || value.length === 0) return undefined + return value.map((v) => + v !== null && typeof v === 'object' && !Array.isArray(v) + ? (v as Record<string, unknown>) + : { value: v } + ) +} + +export async function fetchJsonTableRows( + source: S3TableSource +): Promise<Record<string, unknown>[] | undefined> { + const query = new URLSearchParams({ file_key: source.fileKey }) + if (source.storage) query.set('storage', source.storage) + if (source.s3ResourcePath) query.set('s3_resource_path', source.s3ResourcePath) + const apiPath = `/w/${source.workspace}/job_helpers/download_s3_file?${query}` + const headers = await getHeaders(OpenAPI, { method: 'GET', url: apiPath }) + const response = await fetch(`${OpenAPI.BASE}${apiPath}`, { + headers, + credentials: OpenAPI.CREDENTIALS + }) + if (!response.ok) throw new Error(`${response.status} ${response.statusText}`) + return jsonTableRows(await response.json()) +} diff --git a/frontend/src/lib/components/schedules/SchedulesList.svelte b/frontend/src/lib/components/schedules/SchedulesList.svelte index c2b81434a7..3d8732e088 100644 --- a/frontend/src/lib/components/schedules/SchedulesList.svelte +++ b/frontend/src/lib/components/schedules/SchedulesList.svelte @@ -7,9 +7,8 @@ WorkspaceService } from '$lib/gen' import { canWrite, displayDate, getLocalSetting, pluralize, storeLocalSetting } from '$lib/utils' - import { useScheduleLock } from '$lib/operatorWriteRights' + import { useEditRights, useScheduleLock } from '$lib/operatorWriteRights' import { withForkConflictRetry } from '$lib/utils/forkConflict' - import { base } from '$app/paths' import CenteredPage from '$lib/components/CenteredPage.svelte' import { Badge, Button, EmptyState, Skeleton } from '$lib/components/common' import Dropdown from '$lib/components/DropdownV2.svelte' @@ -56,7 +55,7 @@ import JobPreview from '$lib/components/jobs/JobPreview.svelte' import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte' import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte' - import { untrack } from 'svelte' + import { onDestroy, untrack } from 'svelte' import { page } from '$app/stores' import { useHostedPage } from '$lib/components/hostedPage' import DeployWorkspaceDrawer from '$lib/components/DeployWorkspaceDrawer.svelte' @@ -68,6 +67,7 @@ useOperatingUser } from '$lib/components/operatingWorkspace.svelte' const scheduleLock = useScheduleLock() + const editRights = useEditRights() const operatingWorkspace = useOperatingWorkspace() const operatingUser = useOperatingUser() @@ -98,7 +98,15 @@ deployUiSettings = settings.deploy_ui ?? ALL_DEPLOYABLE } getDeployUiSettings() + // Bumped by every load and on destroy: a load that resumes from an await under an older + // value was superseded or outlived the page, and must not fetch or write anything more. + let loadGeneration = 0 + onDestroy(() => { + loadGeneration++ + }) + async function loadSchedules(): Promise<void> { + const generation = ++loadGeneration const currentFilters = filters.val // Build API parameters from filters. @@ -139,6 +147,7 @@ const result = (await ScheduleService.listSchedules(apiParams)).map((x) => { return { canWrite: canWrite(x.path, x.extra_perms!, operatingUser.current), ...x } }) + if (generation !== loadGeneration) return // Extract unique values for autocomplete allPaths = Array.from(new Set(result.map((x) => x.path))).sort() @@ -152,23 +161,27 @@ // after the schedule core data has been loaded, load all the job stats // TODO: we could potentially not reload the job stats on every call to loadSchedules, but for now it's // simpler to always call it. Update if performance becomes an issue. - loadSchedulesWithJobStats() + loadSchedulesWithJobStats(generation) } - // Reload schedules when filters change + // One effect for every reason to reload (filters, workspace, user), so that mounting + // issues a single load rather than one per reason. Waits for the user lookup to settle, + // not for a user: a failed lookup still lists, read-only. $effect(() => { filters.val - if ($operatingWorkspace) { + operatingUser.current + if ($operatingWorkspace && operatingUser.resolved($operatingWorkspace)) { untrack(() => loadSchedules()) } }) - async function loadSchedulesWithJobStats(): Promise<void> { + async function loadSchedulesWithJobStats(generation: number): Promise<void> { loadingSchedulesWithJobStats = true let schedulesWithJobsByPath = new Map<string, ScheduleW>() let schedulesWithJobsList = await ScheduleService.listSchedulesWithJobs({ workspace: $operatingWorkspace! }) + if (generation !== loadGeneration) return schedulesWithJobsList.map((x) => { schedulesWithJobsByPath[x.path] = x }) @@ -222,13 +235,6 @@ } } - $effect(() => { - if ($operatingWorkspace && operatingUser.current) { - untrack(() => { - loadSchedules() - }) - } - }) let scheduleEditor: ScheduleEditor | undefined = $state() // Deep link: #<path> opens that schedule's edit drawer. Tracks the last @@ -410,7 +416,7 @@ is_draft } = s} {@const hasDraft = getLocalDraftHint($operatingWorkspace, 'trigger_schedule', path) ?? is_draft} - {@const canEdit = canWrite && !$scheduleLock} + {@const canEdit = editRights.canEditItem('schedule', path, extra_perms)} {@const href = `${is_flow ? '/flows/get' : '/scripts/get'}/${script_path}`} {@const avg_s = jobs ? jobs.reduce((acc, x) => acc + x.duration_ms, 0) / jobs.length : undefined} @@ -545,7 +551,7 @@ }} checked={!draft_only && enabled} on:change={(e) => { - if (canWrite) { + if (canEdit) { setScheduleEnabled(path, e.detail) } else { sendUserToast('not enough permission', true) @@ -562,7 +568,7 @@ </div> <div class="flex gap-2 items-center justify-end"> <Button - href={`${base}/runs/?schedule_path=${path}&job_trigger_kind=schedule&show_future_jobs=true`} + href={`/runs/?schedule_path=${path}&job_trigger_kind=schedule&show_future_jobs=true`} disabled={draft_only} unifiedSize="md" startIcon={{ icon: List }} @@ -585,7 +591,7 @@ displayName: `View ${is_flow ? 'Flow' : 'Script'}`, icon: Eye, action: () => { - if (hosted) hosted.openLink(`${base}${href}`) + if (hosted) hosted.openLink(href) else goto(href) } }, @@ -637,12 +643,12 @@ { displayName: 'View runs', icon: List, - href: `${base}/runs/?schedule_path=${path}&job_trigger_kind=schedule&show_future_jobs=true` + href: `/runs/?schedule_path=${path}&job_trigger_kind=schedule&show_future_jobs=true` }, { displayName: 'Audit logs', icon: Eye, - href: `${base}/audit_logs?resource=${path}` + href: `/audit_logs?resource=${path}` }, { displayName: 'Run now', @@ -675,7 +681,7 @@ {/if} {#each jobs ?? [] as job} {@const h = (avg_s ? job.duration_ms / avg_s : 1) * 7 + 3} - <a href="{base}/run/{job.id}?workspace={$operatingWorkspace}"> + <a href="/run/{job.id}?workspace={$operatingWorkspace}"> <JobPreview id={job.id} class="p-4"> <div> <div diff --git a/frontend/src/lib/components/schema/InputSelectedBadge.svelte b/frontend/src/lib/components/schema/InputSelectedBadge.svelte index 7abadf14fd..bf4d3e6211 100644 --- a/frontend/src/lib/components/schema/InputSelectedBadge.svelte +++ b/frontend/src/lib/components/schema/InputSelectedBadge.svelte @@ -6,7 +6,10 @@ import type { Snippet } from 'svelte' interface Props { - inputSelected: 'history' | 'captures' | 'saved' | 'ai' | undefined + /** `pending_run` is the odd one: the others report where the arguments in the form came + * from and undo that substitution on reject, while this one reports a chat tool call + * waiting on the form and declines it. */ + inputSelected: 'history' | 'captures' | 'saved' | 'ai' | 'pending_run' | undefined labelColor?: string className?: string acceptButton?: Snippet @@ -26,23 +29,28 @@ )} > <p class={twMerge(classes['info'].descriptionClass, 'text-xs px-2', labelColor)}> - Using {inputSelected === 'history' - ? 'historic' - : inputSelected === 'captures' - ? 'captures' - : inputSelected === 'ai' - ? 'AI generated' - : 'saved'} input arguments + {#if inputSelected === 'pending_run'} + The agent wants to run this + {:else} + Using {inputSelected === 'history' + ? 'historic' + : inputSelected === 'captures' + ? 'captures' + : inputSelected === 'ai' + ? 'AI generated' + : 'saved'} input arguments + {/if} </p> {#if acceptButton} {@render acceptButton()} {/if} <Button - color="light" - size="xs2" + unifiedSize="2xs" + variant="subtle" + tone="info" startIcon={{ icon: X }} shortCut={{ key: 'esc', withoutModifier: true }} - on:click={onReject} + onClick={onReject} /> </div> </div> diff --git a/frontend/src/lib/components/schema/JobSchemaPicker.svelte b/frontend/src/lib/components/schema/JobSchemaPicker.svelte index fe132d546c..b8c2641164 100644 --- a/frontend/src/lib/components/schema/JobSchemaPicker.svelte +++ b/frontend/src/lib/components/schema/JobSchemaPicker.svelte @@ -1,7 +1,6 @@ <script lang="ts"> import SchemaPickerRow from './SchemaPickerRow.svelte' import { ExternalLink } from 'lucide-svelte' - import { base } from '$lib/base' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' const operatingWorkspace = useOperatingWorkspace() @@ -62,7 +61,7 @@ <div class="center-center"> <a target="_blank" - href="{base}/run/{job.id}?workspace={$operatingWorkspace}" + href="/run/{job.id}?workspace={$operatingWorkspace}" class="text-right float-right text-secondary px-2" title="See run detail in a new tab" > diff --git a/frontend/src/lib/components/schema/RunningJobSchemaPicker.svelte b/frontend/src/lib/components/schema/RunningJobSchemaPicker.svelte index 2714cc92c3..1ae81ca63c 100644 --- a/frontend/src/lib/components/schema/RunningJobSchemaPicker.svelte +++ b/frontend/src/lib/components/schema/RunningJobSchemaPicker.svelte @@ -4,7 +4,6 @@ import { JobService } from '$lib/gen/index.js' import { createEventDispatcher, untrack } from 'svelte' import { ExternalLink } from 'lucide-svelte' - import { base } from '$lib/base' import { Cell, Row } from '$lib/components/table' import { twMerge } from 'tailwind-merge' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' @@ -74,7 +73,7 @@ <div class="center-center {hovering ? '' : '!hidden'}"> <a target="_blank" - href="{base}/run/{job.id}?workspace={$operatingWorkspace}" + href="/run/{job.id}?workspace={$operatingWorkspace}" class="text-right float-right text-secondary" title="See run detail in a new tab" > diff --git a/frontend/src/lib/components/scriptEditor/LogPanel.svelte b/frontend/src/lib/components/scriptEditor/LogPanel.svelte index fe2bc6c73c..6101417f90 100644 --- a/frontend/src/lib/components/scriptEditor/LogPanel.svelte +++ b/frontend/src/lib/components/scriptEditor/LogPanel.svelte @@ -9,7 +9,6 @@ type Preview, type WorkflowStatus } from '$lib/gen' - import { base } from '$lib/base' import { displayDate } from '$lib/utils' import Tabs from '../common/tabs/Tabs.svelte' import Tab from '../common/tabs/Tab.svelte' @@ -270,7 +269,7 @@ <Cell first> <a class="pr-3" - href="{base}/run/{id}?workspace={workspace ?? $operatingWorkspace}" + href="/run/{id}?workspace={workspace ?? $operatingWorkspace}" target="_blank">{id.substring(30)}</a > </Cell> diff --git a/frontend/src/lib/components/script_builder.ts b/frontend/src/lib/components/script_builder.ts index 682859da69..4249441d20 100644 --- a/frontend/src/lib/components/script_builder.ts +++ b/frontend/src/lib/components/script_builder.ts @@ -57,6 +57,7 @@ export interface ScriptBuilderProps { | 'docker' | 'bunnative' | 'claudesandbox' + | 'pisandbox' | 'wac_python' | 'wac_typescript' | 'ci_test_bun' diff --git a/frontend/src/lib/components/scripts/CreateActionsScript.svelte b/frontend/src/lib/components/scripts/CreateActionsScript.svelte index 48480918e0..d3e59033e0 100644 --- a/frontend/src/lib/components/scripts/CreateActionsScript.svelte +++ b/frontend/src/lib/components/scripts/CreateActionsScript.svelte @@ -1,5 +1,4 @@ <script lang="ts"> - import { base } from '$lib/base' import { Code2, Plus } from 'lucide-svelte' import { Button } from '$lib/components/common' @@ -14,7 +13,7 @@ unifiedSize="lg" variant="accent" startIcon={{ icon: Plus }} - href="{base}/scripts/add" + href="/scripts/add" endIcon={{ icon: Code2 }} > Script diff --git a/frontend/src/lib/components/search/GlobalSearchModal.svelte b/frontend/src/lib/components/search/GlobalSearchModal.svelte index b94e0faefa..c2c4a15bd8 100644 --- a/frontend/src/lib/components/search/GlobalSearchModal.svelte +++ b/frontend/src/lib/components/search/GlobalSearchModal.svelte @@ -3,16 +3,19 @@ import { AppService, FlowService, + ResourceService, ScriptService, type Flow, type ListableApp, type ListableRawApp, + type ListableResource, type Script, type SearchJobsIndexResponse } from '$lib/gen' import { clickOutside, isMac, scroll_into_view_if_needed_polyfill } from '$lib/utils' import { AlertTriangle, + Bot, BoxesIcon, CalendarIcon, Code2Icon, @@ -432,6 +435,9 @@ case 'raw_app': path = `/apps_raw/get/${e.path}` break + case 'agent': + path = `/agents/get/${e.path}` + break default: path = '/' } @@ -501,7 +507,7 @@ } } - type TableItem<T, U extends 'script' | 'flow' | 'app' | 'raw_app'> = T & { + type TableItem<T, U extends 'script' | 'flow' | 'app' | 'raw_app' | 'agent'> = T & { search_id: string marked?: string type?: U @@ -518,7 +524,9 @@ type TableApp = TableItem<ListableApp, 'app'> type TableRawApp = TableItem<ListableRawApp, 'raw_app'> - type TableAny = TableScript | TableFlow | TableApp | TableRawApp + type TableAgent = TableItem<ListableResource & { summary?: string }, 'agent'> + + type TableAny = TableScript | TableFlow | TableApp | TableRawApp | TableAgent let combinedItems: TableAny[] | undefined = $state(undefined) @@ -532,8 +540,18 @@ withoutDescription: true }) const apps = await AppService.listApps({ workspace: $workspaceStore! }) + const [agents, starredAgents] = await Promise.all( + [false, true].map((starredOnly) => + ResourceService.listResource({ + workspace: $workspaceStore!, + resourceType: 'ai_agent', + starredOnly + }) + ) + ) + const starredAgentPaths = new Set(starredAgents.map((x) => x.path)) - let combinedItems: (TableScript | TableFlow | TableApp | TableRawApp)[] | undefined = [ + let combinedItems: TableAny[] | undefined = [ ...flows.map((x) => ({ ...x, type: 'flow' as 'flow', @@ -555,7 +573,17 @@ type: 'app' as 'app', time: new Date(x.edited_at).getTime(), search_id: x.path - })) + })), + ...agents + .filter((x) => !x.draft_only) + .map((x) => ({ + ...x, + summary: x.description, + type: 'agent' as 'agent', + time: x.edited_at ? new Date(x.edited_at).getTime() : 0, + starred: starredAgentPaths.has(x.path), + search_id: x.path + })) ].sort((a, b) => (a.starred != b.starred ? (a.starred ? -1 : 1) : a.time - b.time > 0 ? -1 : 1)) return combinedItems @@ -571,6 +599,8 @@ return LayoutDashboardIcon case 'raw_app': return LayoutDashboardIcon + case 'agent': + return Bot } } @@ -729,7 +759,9 @@ {#if tab === 'default'} {#if (itemMap[tab] ?? []).filter((e) => (combinedItems ?? []).includes(e)).length > 0} <div class="p-2"> - <div class="py-2 px-1 text-xs font-semibold text-primary"> Flows/Scripts/Apps </div> + <div class="py-2 px-1 text-xs font-semibold text-primary"> + Flows/Scripts/Apps/Agents</div + > {#each (itemMap[tab] ?? []).filter((e) => (combinedItems ?? []).includes(e)) as el} <QuickMenuItem onselect={(shift) => { diff --git a/frontend/src/lib/components/sessions/ItemViewerView.svelte b/frontend/src/lib/components/sessions/ItemViewerView.svelte index f02b215350..e9fa9b7768 100644 --- a/frontend/src/lib/components/sessions/ItemViewerView.svelte +++ b/frontend/src/lib/components/sessions/ItemViewerView.svelte @@ -8,7 +8,6 @@ * the browser out of the session. */ import { setContext, untrack } from 'svelte' - import { base } from '$lib/base' import ScriptDetail from '$lib/components/details/ScriptDetail.svelte' import FlowDetail from '$lib/components/details/FlowDetail.svelte' import InWorkspaceAppViewer from '$lib/components/apps/editor/InWorkspaceAppViewer.svelte' @@ -20,14 +19,18 @@ parseHistoricalScriptEdit, parsePreviewItemRoute, previewLocationLabel, - stripBase + barePath } from './previewRouter' + import { useSessionPermissions } from './sessionPermissions.svelte' let { runtime, kind, path, version, + pendingRunId, + locationHash = '', + dbtRetryFrom, workspaceId, tabId, container, @@ -42,6 +45,12 @@ path: string /** Deployed version this tab is pinned to, from its URL's `?version=`. */ version?: string + /** The chat tool call this tab was opened to answer, from its URL's `?pending_run=`. */ + pendingRunId?: string + /** `#`-fragment of the tab's URL: the args a run's `Run again` prefills the form with. */ + locationHash?: string + /** The failed dbt run that `Run again` offers to resume, from `?dbt_retry_from=`. */ + dbtRetryFrom?: string workspaceId: string /** Whether this side is the one on screen. Hidden sides stay mounted, so this gates * the window-level keyboard handler — several instances listen on the window. */ @@ -55,6 +64,9 @@ untrack(() => runtime.manager) ) + const permissions = useSessionPermissions(() => workspaceId) + const canEdit = $derived(permissions.canOpenEditor(kind)) + // This reads the deployed version over the API rather than from the editor cell the // chat mutates, so it is the one preview kind that does not self-sync (the invariant // `previewReload.ts` states for editors). A deploy from the editor topbar beside it @@ -73,6 +85,16 @@ reloadKey++ }) + // The call waiting on this item's run form, when the reader chose to confirm it here + // rather than on the card. Read live from the runtime, so it disappears the moment the + // call settles — by Run, by Cancel, by a stopped turn or by this tab closing. + // + // Named by this tab's own url rather than looked up by item, so only the tab opened for + // the call carries it. A tab re-pointed anywhere — another version of this item included + // — loses the name and hands the call back to the card, which is where it can still be + // confirmed as proposed. + const pendingRun = $derived(pendingRunId ? runtime.pendingRunFor(pendingRunId) : undefined) + /** Refetch the deployed item. The host calls this for the reload signals that reach a * tab from outside it; nothing about becoming visible triggers it, so a form the reader * filled in survives switching tabs away and back. */ @@ -80,10 +102,22 @@ reloadKey++ } - const searchParams = $derived(version ? new URLSearchParams({ version }) : undefined) + const searchParams = $derived( + version || dbtRetryFrom + ? new URLSearchParams({ + ...(version ? { version } : {}), + ...(dbtRetryFrom ? { dbt_retry_from: dbtRetryFrom } : {}) + }) + : undefined + ) - // Remounts the detail page below, which loads on mount. - const loadKey = $derived(`${workspaceId}/${kind}/${path}/${version ?? ''}/${reloadKey}`) + // Remounts the detail page below, which loads on mount. The fragment and the call are + // part of it because the detail pages read both once, as they build their form: from the + // fragment for a `Run again`, from the call for what the chat proposed. So a tab already + // on this item, re-pointed to either, has to build that form again. + const loadKey = $derived( + `${workspaceId}/${kind}/${path}/${version ?? ''}/${locationHash}/${pendingRunId ?? ''}/${reloadKey}` + ) // Nothing deployed at this path. Stamped with the load it answers, so a refetch or a // re-pointed tab is never answered from an earlier load's verdict. let notFoundFor: string | undefined = $state(undefined) @@ -109,7 +143,7 @@ // opens as its own tab, another side or version of an item re-points this tab, and // any other page opens as a page tab. Nothing reaches the top-level router. function onNavigate(url: string): void { - const clean = stripBase(url) + const clean = barePath(url) const query = new URL(url, 'http://x').searchParams const run = clean.match(/^\/run\/([^/?#]+)$/) if (run) { @@ -151,7 +185,7 @@ } runtime.previewTabs.open({ type: 'page', - href: `${base}${clean}${query.size ? `?${query}` : ''}`, + href: `${clean}${query.size ? `?${query}` : ''}`, label: previewLocationLabel(clean) }) } @@ -197,20 +231,25 @@ <div class="text-sm text-primary">Not deployed yet</div> <div class="text-xs text-tertiary max-w-sm"> Nothing is deployed at <span class="font-mono">{path}</span>, so there is no deployed - version to view. Deploy it from the editor to see it here. + version to view.{#if canEdit} + Deploy it from the editor to see it here.{/if} </div> - <Button unifiedSize="sm" variant="default" startIcon={{ icon: Pen }} on:click={toEditSide}> - Back to editor - </Button> + {#if canEdit} + <Button unifiedSize="sm" variant="default" startIcon={{ icon: Pen }} on:click={toEditSide}> + Back to editor + </Button> + {/if} </div> {:else if kind === 'script'} <ScriptDetail hash={path} workspace={workspaceId} {searchParams} + {locationHash} {onNavigate} {active} embedded + {pendingRun} onLoadState={setLoadState} /> {:else if kind === 'flow'} @@ -218,9 +257,11 @@ {path} workspace={workspaceId} {searchParams} + {locationHash} {onNavigate} {active} embedded + {pendingRun} onLoadState={setLoadState} /> {:else} diff --git a/frontend/src/lib/components/sessions/PageListView.svelte b/frontend/src/lib/components/sessions/PageListView.svelte index 0bc27cd9f0..b5443c25cd 100644 --- a/frontend/src/lib/components/sessions/PageListView.svelte +++ b/frontend/src/lib/components/sessions/PageListView.svelte @@ -3,8 +3,14 @@ import { Loader2 } from 'lucide-svelte' import { setOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' import { setHostedPage, type HostedPage } from '$lib/components/hostedPage' - import { pageItemForListPath, parsePreviewItemRoute } from './previewPaths' - import { previewLocationLabel } from './previewRouter' + import { + RUNS_PATH, + barePath, + isRunsListPath, + pageItemForListPath, + parsePreviewItemRoute + } from './previewPaths' + import { parseRunRoute, previewLocationLabel } from './previewRouter' import { whereIs } from './sessionPreviewTabs.svelte' import type { SessionPreviewTab } from './sessionState.svelte' import type { SessionRuntime } from './sessionRuntime.svelte' @@ -19,7 +25,7 @@ }: { runtime: SessionRuntime tab: SessionPreviewTab - /** The list page, base-stripped. */ + /** The list page path. */ path: string workspaceId: string /** The tab's element, which also holds the list's portalled drawers and menus. */ @@ -44,20 +50,48 @@ ? { pathname: loc, search: '' } : { pathname: loc.slice(0, at), search: loc.slice(at) } } + // The location this page last wrote itself, and the one it was last moved to from outside. + let ownLoc: string | undefined + let movedTo: string | undefined + let moves = 0 + // Bumped when the location moves other than by the page's own write. Derived rather than + // effected: it has to flip in the same flush as the location, before the page's own + // effects read the new query and write their defaults back over the stored preferences. + const moved = $derived.by(() => { + const loc = whereIs(tab) + if (loc !== ownLoc && loc !== movedTo) { + movedTo = loc + moves++ + } + return moves + }) const host: HostedPage = { get search() { return locationParts().search }, setSearch(search) { - runtime.previewTabs.observeLocation(tab.id, locationParts().pathname + search) + ownLoc = locationParts().pathname + search + movedTo = undefined + runtime.previewTabs.observeLocation(tab.id, ownLoc) }, openItem(itemPath) { const ref = pageItemForListPath(path, itemPath) if (ref) runtime.previewTabs.open({ type: 'pageitem', ref }) }, openLink(href) { + const run = parseRunRoute(href) + if (run) { + runtime.manager.openRunInPreview?.({ + jobId: run.jobId, + workspace: run.workspace ?? workspaceId, + label: previewLocationLabel(`/run/${run.jobId}`) + }) + return + } const item = parsePreviewItemRoute(href) - if (item) { + // A link to one version stays a page tab: opening an item focuses a tab already + // on it as it stands, where a page tab's URL is written whole, pin included. + if (item && !new URL(href, 'http://_').searchParams.has('version')) { runtime.previewTabs.open({ type: 'item', item: { kind: item.kind, raw_app: item.raw_app, path: item.itemPath, summary: '' }, @@ -83,18 +117,32 @@ if (e.defaultPrevented || e.button !== 0) return if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return const a = (e.target as Element | null)?.closest?.('a[href]') as HTMLAnchorElement | null - if (!a || (a.target && a.target !== '_self') || a.hasAttribute('download')) return + if (!a || a.hasAttribute('download')) return const url = new URL(a.href, window.location.href) if (url.origin !== window.location.origin) return + const href = url.pathname + url.search + url.hash + // A run's link asks for a new tab so the list keeps its place: here that tab is a + // preview tab, not a browser one that would leave the session. + if (a.target && a.target !== '_self' && !parseRunRoute(href)) return e.preventDefault() if (a.getAttribute('href')?.startsWith('#')) return - host.openLink(url.pathname + url.search + url.hash) + host.openLink(href) } el.addEventListener('click', onClick) return () => el.removeEventListener('click', onClick) }) const listed = $derived(pageItemForListPath(path, '')) + // `/runs/<item path>` lists one item's runs. + const runsOf = $derived.by(() => { + if (!isRunsListPath(path)) return undefined + const itemPath = barePath(path).slice(RUNS_PATH.length + 1) + try { + return decodeURIComponent(itemPath) + } catch { + return itemPath + } + }) </script> {#snippet loading()} @@ -130,6 +178,15 @@ {:then Module} <Module.default triggerKind={listed.triggerKind} /> {/await} + {:else if runsOf !== undefined} + <!-- A move from outside remounts it, so it seeds the filters the user keeps stored. --> + {#key moved} + {#await import('$lib/components/RunsPage.svelte')} + {@render loading()} + {:then Module} + <Module.default initialPath={runsOf} /> + {/await} + {/key} {/if} {/key} </div> diff --git a/frontend/src/lib/components/sessions/PipelineEditorView.svelte b/frontend/src/lib/components/sessions/PipelineEditorView.svelte index b1e461eb32..d6e9f28935 100644 --- a/frontend/src/lib/components/sessions/PipelineEditorView.svelte +++ b/frontend/src/lib/components/sessions/PipelineEditorView.svelte @@ -1,9 +1,10 @@ <script lang="ts"> import { resource } from 'runed' - import { tick, untrack } from 'svelte' - import { Loader2, Workflow } from 'lucide-svelte' + import { onDestroy, tick, untrack } from 'svelte' + import { Loader2, Save, Workflow } from 'lucide-svelte' import PipelineGraphEditor from '$lib/components/assets/AssetGraph/PipelineGraphEditor.svelte' import PipelineTriggerEditors from '$lib/components/assets/AssetGraph/PipelineTriggerEditors.svelte' + import { usePipelineDataUploads } from '$lib/components/assets/AssetGraph/pipelineDataUploads.svelte' import { resolveGraph } from '$lib/components/assets/AssetGraph/resolveGraph' import { useActiveRunnableIds } from '$lib/components/assets/AssetGraph/activeRunnables.svelte' import type { @@ -11,10 +12,26 @@ AssetGraphSelection, NativeTriggerKind } from '$lib/components/assets/AssetGraph/types' - import { AssetService, JobService, type AssetKind } from '$lib/gen' + import { AssetService, JobService, type ScriptLang } from '$lib/gen' + import { DATA_ASSET_KINDS } from '$lib/components/assets/AssetGraph/cascadeRun' + import { usePipelineAssetPrefetch } from '$lib/components/assets/AssetGraph/pipelineAssetPrefetch.svelte' import { sendUserToast } from '$lib/utils' import { createPipelineAiHelpers } from '$lib/components/assets/AssetGraph/pipelineAiHelpers' + import { deployPipelineDrafts } from '$lib/components/assets/AssetGraph/pipelineDeploy.svelte' + import { + diffDeployedGraph, + extractCascadeFacts, + formatDrift + } from '$lib/components/assets/AssetGraph/deployGraphDiff' + import PipelineDeployErrors from '$lib/components/assets/AssetGraph/PipelineDeployErrors.svelte' + import PipelineDeployTriggersModal from '$lib/components/assets/AssetGraph/PipelineDeployTriggersModal.svelte' + import AutosaveIndicator from '$lib/components/AutosaveIndicator.svelte' + import { Button } from '$lib/components/common' + import { UserDraftDbSyncer } from '$lib/userDraftDbSyncer.svelte' + import { PIPELINE_DRAFT_KIND, pipelineBundlePath } from '$lib/pipelinePaths' + import type { DeployResult } from '$lib/utils_workspace_deploy' import type { SessionRuntime } from './sessionRuntime.svelte' + import { maskKey } from './modifiedItemsMask' let { runtime, @@ -29,7 +46,7 @@ /** Folder name the pipeline graph is scoped to (not a workspace item path). */ path: string workspaceId: string - /** Only the visible session registers the pipeline tools on its manager. */ + /** Only the visible session polls the live run badges. */ isActiveSession?: boolean /** Whether this is the foreground preview tab. */ active?: boolean @@ -43,50 +60,36 @@ // wrong chat — leaving this session's chat unable to build canvas nodes. const aiChatManager = runtime.manager - // Only the foreground tab of the foreground session owns the chat's pipeline - // tools and runs the live-badge poll — a background tab (another preview tab is - // showing, or another session is active) must not shadow that context or poll. + // Only the foreground tab of the foreground session runs the live-badge poll. const engaged = $derived(isActiveSession && active) - // Externalized editor state — lives on the runtime so the drafts persist across - // hide/show of the preview pane (the pane unmounts on hide). - const pe = runtime.pipelineEditorState - - // The reused `pe` is scoped to a folder. A same-folder remount (hide→show) - // keeps the drafts; a retarget to a different folder resets so stale drafts - // don't bleed across folders. untrack the writes so this can't self-loop. - $effect(() => { - const folder = path - untrack(() => { - if (pe.folder !== folder) { - if (pe.folder !== undefined) { - pe.reset() - // A retarget without remount re-scopes the poll, so the release - // effect could never match the old folder's job — drop the hint. - activeRunnable = undefined - activeRunnableJobId = undefined - // Re-scope the Global pipeline prompt to the new folder (the helper - // methods already read the reactive path, but the system message - // string was built for the old one). Only when this tab is engaged — - // its helpers are the registered set; a background tab reconfigures - // when it next becomes the foreground one. - if (engaged) aiChatManager.rebuildGlobalSystemMessage() - } - pe.folder = folder - } - }) - }) + // This folder's editor state lives on the runtime, so its drafts survive a + // remount. The host remounts this view when the tab moves to another folder, so + // `path` is fixed for its lifetime. + const pe = untrack(() => runtime.pipelineEditor(path)) const EMPTY_GRAPH: AssetGraphResponse = { assets: [], runnables: [], edges: [], triggers: [] } - const EMPTY_PATH_MAP = new Map<string, Array<{ kind: AssetKind; path: string }>>() - const EMPTY_NATIVE_MAP = new Map<string, Set<any>>() + // Data assets only, as on the pipeline page: variables and resources are + // config most scripts reference, and would swamp the layout as hub nodes. const graphRes = resource( () => ({ workspace: workspaceId, folder: path }), async ({ workspace, folder }) => - workspace && folder ? await AssetService.getAssetsGraph({ workspace, folder }) : EMPTY_GRAPH + workspace && folder + ? await AssetService.getAssetsGraph({ + workspace, + folder, + assetKinds: DATA_ASSET_KINDS.join(',') + }) + : EMPTY_GRAPH ) + const assetPrefetch = usePipelineAssetPrefetch({ + getWorkspace: () => workspaceId, + getGraph: () => graphRes.current as AssetGraphResponse | undefined, + editor: pe + }) + // Folder whose graph is actually rendered — `graphRes.current` is stale- // while-revalidate on a folder retarget, so the canvas's one-shot initial // fit is keyed on the folder captured when a graph lands, not on `path` @@ -97,9 +100,7 @@ }) // Deployed graph + the in-flight draft overlay (AI-built nodes render as plain - // dashed unsaved drafts, same as manual drafts). The session - // skips the route page's folder-wide asset prefetch (empty inferred maps); the - // open script's live overlays still feed the graph. (resolveGraph's base is the + // dashed unsaved drafts, same as manual drafts). (resolveGraph's base is the // pipeline runnables subset; the 'job' usage_kind of the wire type never appears.) let resolvedGraph = $derived.by<AssetGraphResponse>(() => resolveGraph({ @@ -107,9 +108,10 @@ drafts: pe.drafts, liveBodyAssets: pe.liveBodyAssets, liveAnnotations: pe.liveAnnotations, - inferredWritesByPath: EMPTY_PATH_MAP, - inferredReadsByPath: EMPTY_PATH_MAP, - annotatedNativeKindsByPath: EMPTY_NATIVE_MAP + inferredWritesByPath: assetPrefetch.inferredWritesByPath, + inferredReadsByPath: assetPrefetch.inferredReadsByPath, + annotatedNativeKindsByPath: assetPrefetch.annotatedNativeKindsByPath, + triggerDrafts: pe.triggerDrafts.values() }) ) @@ -120,7 +122,13 @@ getDrafts: () => pe.drafts, setDrafts: (next) => (pe.drafts = next), newDraftLocalId: pe.newDraftLocalId, - onForgetPath: pe.forgetPath, + hasTriggerDrafts: () => pe.triggerDrafts.size > 0, + getTriggerDrafts: () => pe.triggerDrafts, + setTriggerDraft: pe.setTriggerDraft, + onForgetPath: (p) => { + pe.forgetPath(p) + pe.discardTriggerDraftsFor(p) + }, // Open the staged node in the details pane so its code is visible. onProposeNode: (p) => { pe.activeDraftPath = p @@ -135,6 +143,7 @@ }) function handleCanvasSelect(s: AssetGraphSelection | undefined) { + uploadInputsPath = undefined if (s && s.kind === 'runnable' && s.runnable_kind === 'script' && pe.drafts.has(s.path)) { pe.activeDraftPath = s.path pe.selection = undefined @@ -145,6 +154,7 @@ } async function afterSaved(savedPath: string) { + assetPrefetch.forget(savedPath) const next = new Map(pe.drafts) next.delete(savedPath) pe.drafts = next @@ -194,7 +204,11 @@ // Data upload has no trigger row — open the target in the details pane and pulse // the signal so its auto-generated run form focuses the S3 input. + // A data-upload click opens the node on its inputs alone; any other selection + // (or "Open script") goes back to the editor. + let uploadInputsPath = $state<string | undefined>(undefined) function openDataUploadRun(scriptPath: string) { + uploadInputsPath = scriptPath if (pe.drafts.has(scriptPath)) { pe.activeDraftPath = scriptPath pe.selection = undefined @@ -236,29 +250,40 @@ } }) + const dataUploads = usePipelineDataUploads(() => resolvedGraph) + function runProducer(producer: { kind: 'script' | 'flow'; path: string; cascade?: boolean }) { // Pipeline nodes are scripts; a flow producer can't be preview/by-path run. if (producer.kind !== 'script') return Promise.resolve(undefined) - return runNode(producer.path, {}, producer.cascade ?? false) + // A data-upload entry runs on the file staged in its run form. + return runNode(producer.path, dataUploads.argsFor(producer.path) ?? {}, producer.cascade ?? false) } + // Tell the open node's runs list a job started, so it shows it right away. + let runsRefreshKey = $state(0) + let runsPendingJobId = $state<string | undefined>(undefined) + + // `live` is an open editor's body, newer than what is stored: it is previewed, + // a deployed node included. async function runNode( nodePath: string, args: Record<string, any> = {}, - cascade = false + cascade = false, + live?: { content: string; language: ScriptLang } ): Promise<string | undefined> { const draft = pe.drafts.get(nodePath) + const body = live ?? (draft && { content: draft.script.content, language: draft.script.language }) activeRunnables.arm(`script:${nodePath}`) try { let jobId: string - if (draft) { - // Preview-run the draft content; a preview never dispatches downstream. + if (body) { + // Preview-run the unsaved body; a preview never dispatches downstream. jobId = await JobService.runScriptPreview({ workspace: workspaceId, requestBody: { path: nodePath, - content: draft.script.content, - language: draft.script.language, + content: body.content, + language: body.language, args } }) @@ -275,6 +300,8 @@ } activeRunnable = { kind: 'script', path: nodePath } activeRunnableJobId = jobId + runsPendingJobId = jobId + runsRefreshKey++ return jobId } catch (e: any) { sendUserToast(`Run failed: ${e?.body ?? e?.message ?? e}`, true) @@ -282,14 +309,126 @@ } } - // Register the pipeline tools on this session's manager while this tab is the - // engaged (foreground) one. setPipelineHelpers rebuilds the global tool set to - // include the pipeline tools and tears them down on cleanup — so switching to - // another preview tab or session releases them. - $effect(() => { - if (!engaged) return - return aiChatManager.setPipelineHelpers(helpers) - }) + // Register this folder's pipeline tools on the session's own manager for as long + // as the view is mounted — background tabs included, since each folder's tools + // act on its own state — and release them on unmount. + $effect(() => aiChatManager.setPipelineHelpers(helpers)) + + // ── Deploy all ─────────────────────────────────────────────────────────── + // The same deploy as the pipeline page's "Save all", reached from this tab's + // button and from the session's changes list (through the runtime). + const pendingCount = $derived( + pe.drafts.size + pe.triggerDrafts.size + (pe.liveEditPath != undefined ? 1 : 0) + ) + let deploying = $state(false) + let deployErrors = $state<Map<string, string>>(new Map()) + let deployErrorsOpen = $state(false) + + let triggerConfirmOpen = $state(false) + let resolveTriggerConfirm: ((ok: boolean) => void) | undefined + function confirmTriggers(): Promise<boolean> { + triggerConfirmOpen = true + return new Promise((resolve) => (resolveTriggerConfirm = resolve)) + } + function answerTriggerConfirm(ok: boolean) { + triggerConfirmOpen = false + resolveTriggerConfirm?.(ok) + resolveTriggerConfirm = undefined + } + + // A deploy asked for from the changes list can arrive while the tab is still + // loading this folder's drafts. + async function hydrated(timeoutMs = 10000): Promise<boolean> { + for (let waited = 0; !pe.hydratedFromDb && waited < timeoutMs; waited += 100) { + await new Promise((resolve) => setTimeout(resolve, 100)) + } + return pe.hydratedFromDb + } + + async function deployAll(): Promise<DeployResult> { + // Taken before any await: a second caller (the tab's button and the changes + // list both reach here) would otherwise replace the pending confirmation and + // leave the first one waiting forever. + if (deploying) return { success: false, error: 'This pipeline is already deploying.' } + deploying = true + try { + if (!(await hydrated())) return { success: false, error: 'The pipeline drafts did not load.' } + if (pendingCount === 0) { + // Nothing left to deploy, but an earlier deploy may have failed to save + // that: the server would still hold the deployed drafts. + const unsaved = await saveRemaining() + return unsaved ? { success: false, error: unsaved } : { success: true } + } + if (pe.triggerDrafts.size > 0 && !(await confirmTriggers())) { + return { success: false, error: 'Deploy cancelled.' } + } + // What the canvas promises for each draft, checked against what the + // backend derived once deployed. + const predicted = new Map( + [...pe.drafts.keys()].map((p) => [p, extractCascadeFacts(resolvedGraph, p)]) + ) + const { savedPaths, savedTriggers, errors } = await deployPipelineDrafts(pe, workspaceId) + assetPrefetch.forget(...savedPaths) + const bundleKey = maskKey(PIPELINE_DRAFT_KIND, pipelineBundlePath(path)) + if (aiChatManager.modifiedItems?.has(bundleKey)) { + await aiChatManager.recordDeployedItems('script', savedPaths) + } + if (savedPaths.length > 0 || savedTriggers.length > 0) { + await graphRes.refetch() + const deployed = new Map([...predicted].filter(([p]) => savedPaths.includes(p))) + const drift = formatDrift( + diffDeployedGraph(deployed, (graphRes.current ?? EMPTY_GRAPH) as AssetGraphResponse) + ) + if (drift) sendUserToast(drift, true) + } + // The session's changes list re-reads the draft once this resolves, so + // what is left of it has to be saved by then. + const unsaved = await saveRemaining() + deployErrors = errors + if (unsaved) return { success: false, error: `Deployed, but ${unsaved}` } + if (errors.size > 0) { + deployErrorsOpen = true + return { + success: false, + error: `${errors.size} of the pipeline's drafts failed to deploy, see its tab.` + } + } + return { success: true } + } finally { + deploying = false + } + } + + // Saves what is left of the folder's draft and says why if that failed. A + // flush resolves even when the save failed, and the server would then keep + // drafts already deployed — deploying them again would recreate their + // triggers. A failed save stays queued until one succeeds, so the flush + // retries exactly what failed, an open script's unsaved edits included. + async function saveRemaining(): Promise<string | undefined> { + await tick() + const draft = { + workspace: workspaceId, + itemKind: PIPELINE_DRAFT_KIND, + path: pipelineBundlePath(path) + } + await UserDraftDbSyncer.flush(draft) + if (UserDraftDbSyncer.getConflict(draft).conflict) + return 'the remaining drafts conflict with a newer version.' + const sync = UserDraftDbSyncer.getState(draft) + if (sync.state === 'failed') + return `the remaining drafts could not be saved: ${sync.failureMessage ?? 'unknown error'}.` + return undefined + } + + async function deployAllFromButton() { + const count = pendingCount + const res = await deployAll() + if (res.success) sendUserToast(`Deployed ${count} draft${count === 1 ? '' : 's'}`) + } + + $effect(() => runtime.registerPipelineView(path, { deployAll })) + // A deploy waiting on the trigger confirmation must still settle when the tab goes. + onDestroy(() => answerTriggerConfirm(false)) </script> <div class="flex flex-col h-full w-full bg-surface"> @@ -299,6 +438,31 @@ <Workflow size={14} /> <span class="font-mono text-emphasis truncate">f/{path}</span> <span class="text-tertiary">· data pipeline</span> + {#if workspaceId} + <AutosaveIndicator + workspace={workspaceId} + itemKind={PIPELINE_DRAFT_KIND} + path={pipelineBundlePath(path)} + draftOnly + loadedFromDraft={pe.loadedFromDbDraft} + /> + {/if} + <div class="flex-1"></div> + {#if deployErrors.size > 0} + <PipelineDeployErrors errors={deployErrors} bind:open={deployErrorsOpen} /> + {/if} + {#if pendingCount > 0} + <Button + variant="accent" + unifiedSize="xs" + startIcon={{ icon: deploying ? Loader2 : Save }} + onclick={deployAllFromButton} + disabled={deploying} + title={deploying ? 'Deploying drafts…' : `Deploy all ${pendingCount} drafts`} + > + {deploying ? 'Deploying…' : `Deploy all (${pendingCount})`} + </Button> + {/if} </div> <div class="flex-1 min-h-0"> <!-- Only block on the deployed-graph fetch when there's nothing to show yet. @@ -328,6 +492,8 @@ folder={path} viewportFitKey={viewportFitFolder} persistDrafts={true} + modalPanel + prefetchingAssets={assetPrefetch.prefetching} displayGraph={resolvedGraph} mode="edit" workspace={workspaceId} @@ -338,12 +504,21 @@ onOpenWebhook={openWebhookDrawer} onOpenDataUpload={openDataUploadRun} focusUploadSignal={focusDataUploadSignal} + readyDataUploadPaths={dataUploads.readyPaths} + runFormInitialArgs={pe.openScriptPath ? dataUploads.argsFor(pe.openScriptPath) : undefined} + onRunFormArgsChange={dataUploads.stage} {activeRunnable} + {runsRefreshKey} + {runsPendingJobId} activeRunnableIds={activeRunnables.ids} runStates={activeRunnables.states} eventLogEvents={activeRunnables.events} onRunProducer={runProducer} onRunByPath={(path, args) => runNode(path, args)} + inputsOnly={uploadInputsPath !== undefined && + (pe.openScriptPath === undefined || uploadInputsPath === pe.openScriptPath)} + onRunInputs={(path, args, live) => runNode(path, args, false, live)} + onShowScript={() => (uploadInputsPath = undefined)} canRunByPath onTestStateChange={(running) => { const openPath = pe.openScriptPath @@ -370,6 +545,7 @@ await graphRes.refetch() }} onScriptRenamed={async (oldPath, newPath) => { + assetPrefetch.forget(oldPath, newPath) // Repoint the selection so the canvas follows the renamed node instead // of staying on the now-gone old path until an unrelated refetch. if (pe.selection?.kind === 'runnable' && pe.selection.path === oldPath) { @@ -402,3 +578,10 @@ workspace={workspaceId} onUpdate={() => graphRes.refetch()} /> + +<PipelineDeployTriggersModal + open={triggerConfirmOpen} + triggerDrafts={pe.triggerDrafts} + onConfirmed={() => answerTriggerConfirm(true)} + onCanceled={() => answerTriggerConfirm(false)} +/> diff --git a/frontend/src/lib/components/sessions/PreviewRouterPicker.svelte b/frontend/src/lib/components/sessions/PreviewRouterPicker.svelte index 1795c17fe5..bc03272712 100644 --- a/frontend/src/lib/components/sessions/PreviewRouterPicker.svelte +++ b/frontend/src/lib/components/sessions/PreviewRouterPicker.svelte @@ -16,8 +16,9 @@ section or the flat layout. <script lang="ts"> import { untrack } from 'svelte' - import { Compass, FileText, Pen } from 'lucide-svelte' + import { Compass, FileText, NetworkIcon, Pen } from 'lucide-svelte' import { resource } from 'runed' + import { AssetService } from '$lib/gen' import { workspaceStore } from '$lib/stores' import RowIcon from '$lib/components/common/table/RowIcon.svelte' import { @@ -43,11 +44,12 @@ section or the flat layout. PREVIEW_PAGES, artifactKey, isArtifactKey, - pageHref, + isPageKey, pageKey, previewModeFor, type PreviewTarget } from './previewRouter' + import { useSessionPermissions } from './sessionPermissions.svelte' type Kind = WorkspaceItemKind type DrillPickerHandle = { @@ -89,6 +91,8 @@ section or the flat layout. const kinds: Kind[] = ['flow', 'script', 'app'] const effectiveWorkspace = $derived(workspaceId ?? $workspaceStore) + const permissions = useSessionPermissions(() => effectiveWorkspace) + const canEdit = (item: WorkspaceItem) => permissions.canEditItem(item) let inner = $state<DrillPickerHandle | undefined>(undefined) export function focus() { @@ -154,20 +158,28 @@ section or the flat layout. // `mode` is stamped here rather than left to the tab: picking is the reader // saying "show me this", so it lands on the deployed page, and `navigate` // would otherwise keep whichever side the re-pointed tab happened to be on. + // A draft-only item opens its editor, unless this user cannot save there. function tagItems(nodes: DrillNode<WorkspaceItem>[]): DrillNode<PreviewTarget>[] { return nodes.map((n) => n.type === 'leaf' - ? { ...n, data: { type: 'item', item: n.data, mode: previewModeFor(n.data) } } + ? { + ...n, + data: { + type: 'item', + item: n.data, + mode: canEdit(n.data) ? previewModeFor(n.data) : 'view' + } + } : { ...n, children: tagItems(n.children) } ) } - // Open the item's editor. Offered on every item row, including the draft-only ones - // a plain click already opens there: a row that drops the button to say "you were - // getting this anyway" reads as one that cannot be edited. + // Open the item's editor. Offered on every item row this user can edit, including the + // draft-only ones a plain click already opens there: a row that drops the button to say + // "you were getting this anyway" reads as one that cannot be edited. function editAction(leaf: DrillLeaf<PreviewTarget>) { const target = leaf.data - if (target.type !== 'item') return undefined + if (target.type !== 'item' || !canEdit(target.item)) return undefined return { icon: Pen, label: 'Edit', @@ -192,7 +204,7 @@ section or the flat layout. key: pageKey(p.path), label: p.label, icon: p.icon, - data: { type: 'page', href: pageHref(p.path), label: p.label } + data: { type: 'page', href: p.path, label: p.label } } } @@ -204,7 +216,9 @@ section or the flat layout. label: 'Pages', icon: Compass, searchGroup: true, - children: PREVIEW_PAGES.filter((p) => p.path !== '/').map(pageLeaf) + children: PREVIEW_PAGES.filter((p) => p.path !== '/' && permissions.pageAllowed(p)).map( + pageLeaf + ) }) // Session artifacts, when present, get their own branch between Pages and the @@ -228,9 +242,39 @@ section or the flat layout. : undefined ) + // Data pipelines are folders, not items, so they get a branch of their own + // rather than a leaf in the workspace tree. + const pipelinesResource = resource( + () => effectiveWorkspace, + async (ws) => (ws ? await AssetService.listPipelineFolders({ workspace: ws }) : []) + ) + const pipelinesBranch = $derived<DrillBranch<PreviewTarget> | undefined>( + pipelinesResource.current && pipelinesResource.current.length > 0 + ? { + type: 'branch', + key: 'pipelines', + label: 'Data pipelines', + icon: NetworkIcon, + searchGroup: true, + children: pipelinesResource.current.map(({ folder }) => { + const path = `/pipeline/${encodeURIComponent(folder)}` + return { + type: 'leaf' as const, + key: pageKey(path), + label: `f/${folder}`, + icon: NetworkIcon, + data: { type: 'page', href: path, label: folder } + } + }) + } + : undefined + ) + const tree = $derived<DrillNode<PreviewTarget>[]>([ - pagesBranch, + // An operator's workspace may enable none of them. + ...(pagesBranch.children.length > 0 ? [pagesBranch] : []), ...(artifactsBranch ? [artifactsBranch] : []), + ...(pipelinesBranch ? [pipelinesBranch] : []), ...tagItems( buildWorkspaceTree({ loaded: loader.loaded, @@ -243,16 +287,18 @@ section or the flat layout. ) ]) - // An artifact highlight lives under the 'artifacts' branch, which the legacy - // {kind, dir} scope can't express — open the picker inside that branch so the - // active artifact is actually visible and highlighted (not the first root row). - // Keyed on the highlight's shape alone: the branch itself may not have - // materialized yet (artifacts hydrate from IndexedDB after tabs restore), and - // the drill entries fill in reactively once it does. + // A page or artifact highlight lives under its own branch, which the legacy + // {kind, dir} scope can't express — open the picker inside that branch, so the + // reader standing on one sees its siblings with it highlighted. Keyed on the + // highlight's shape alone: the artifacts branch may not have materialized yet + // (artifacts hydrate from IndexedDB after tabs restore), and the drill entries + // fill in reactively once it does. const computedInitialScope = untrack(() => initialHighlight && isArtifactKey(initialHighlight) ? ['artifacts'] - : legacyScopeToPath(initialScope, kinds, 'flat') + : initialHighlight && isPageKey(initialHighlight) + ? ['pages'] + : legacyScopeToPath(initialScope, kinds, 'flat') ) // The flat root has no branch to carry a per-kind loading flag — surface diff --git a/frontend/src/lib/components/sessions/PreviewTabHost.svelte b/frontend/src/lib/components/sessions/PreviewTabHost.svelte index 955f98b599..c2adaf7688 100644 --- a/frontend/src/lib/components/sessions/PreviewTabHost.svelte +++ b/frontend/src/lib/components/sessions/PreviewTabHost.svelte @@ -18,6 +18,7 @@ showsView } from './previewRouter' import { withMenuHidden } from './sessionMode.svelte' + import { useSessionPermissions } from './sessionPermissions.svelte' import ArtifactViewer from '../copilot/chat/artifacts/ArtifactViewer.svelte' import RunFormPreviewSlot from './RunFormPreviewSlot.svelte' import { setOverlayHost } from '../common/overlayHost.svelte' @@ -76,7 +77,15 @@ const itemPath = $derived( slot.kind === 'editor' || slot.kind === 'viewer' ? slot.path : undefined ) - const mode = $derived(slot.kind === 'viewer' ? 'view' : 'edit') + const workspaceId = $derived( + session ? (getEffectiveWorkspaceId(session) ?? $workspaceStore ?? '') : '' + ) + const permissions = useSessionPermissions(() => workspaceId || undefined) + // Every route into an editor ends here, the breadcrumb and the chat's openers included, so + // this is where an editor the user cannot save is turned into the deployed page. + const mode = $derived( + slot.kind === 'viewer' || (itemKind && !permissions.canOpenEditor(itemKind)) ? 'view' : 'edit' + ) // `new_draft` marks a raw app handed over by the new-app builder. const newRawApp = $derived( itemKind === 'raw_app' && new URL(tab.url, 'http://x').searchParams.get('new_draft') === 'true' @@ -88,6 +97,14 @@ ? (new URL(tab.url, 'http://x').searchParams.get('version') ?? undefined) : undefined ) + // What a run's `Run again` hands the deployed page it opens: the run's args in the + // fragment, and for a dbt run the failure it could resume instead. + const viewerUrl = $derived(slot.kind === 'viewer' ? new URL(tab.url, 'http://x') : undefined) + // The chat tool call this tab was opened to answer rides in the same query. Re-pointing + // the tab rebuilds its url without it, so a tab sent anywhere else — another item, + // another version — stops carrying the call rather than answering it from a page it was + // never confirmed against. + const pendingRunId = $derived(viewerUrl?.searchParams.get('pending_run') ?? undefined) // The path an editor reports is its deployed one, which a staged rename can make // differ from this tab's — so the view opens on what actually exists. @@ -103,9 +120,6 @@ // session"). Only the in-process editors need it handed over — an iframe tab // loads the URL whole, params included. const selectedId = $derived(parsePreviewSelectedId(tab.url)) - const workspaceId = $derived( - session ? (getEffectiveWorkspaceId(session) ?? $workspaceStore ?? '') : '' - ) const isActiveSession = $derived(!!session && sessionState.currentSessionId === session.id) // Resolved live from the session's store so an update_artifact re-renders the panel. @@ -141,6 +155,7 @@ // A page item's editor reads its draft only when it loads, so a reload remounts it. let pageItemReloadNonce = $state(0) let pageListReloadNonce = $state(0) + let runReloadNonce = $state(0) export function reload() { // A live editor shares the runtime store the chat mutates, so generic chat @@ -162,6 +177,10 @@ pageListReloadNonce++ return } + if (slot.kind === 'run') { + runReloadNonce++ + return + } try { const win = frame?.contentWindow if (!win) return @@ -354,7 +373,10 @@ {#await import('./PipelineEditorView.svelte')} {@render editorLoading()} {:then Module} - <Module.default {runtime} path={itemPath} {workspaceId} {isActiveSession} {active} /> + <!-- Keyed: the view binds one folder's state for its lifetime. --> + {#key itemPath} + <Module.default {runtime} path={itemPath} {workspaceId} {isActiveSession} {active} /> + {/key} {/await} {:else} {#await import('./RawAppEditorView.svelte')} @@ -384,6 +406,9 @@ kind={itemKind} path={itemPath} version={pinnedVersion} + {pendingRunId} + locationHash={viewerUrl?.hash} + dbtRetryFrom={viewerUrl?.searchParams.get('dbt_retry_from') ?? undefined} {workspaceId} tabId={tab.id} container={overlayHostEl} @@ -391,6 +416,11 @@ /> {/await} </div> + {:else} + <!-- A pipeline has no deployed page, only its editor. --> + <div class="flex-1 flex items-center justify-center p-8 text-center text-sm text-secondary"> + The pipeline editor saves drafts, which your role cannot do in this workspace. + </div> {/if} </div> {:else if slot.kind === 'pageitem' && mounted && runtime} @@ -430,6 +460,29 @@ {/await} {/if} </div> +{:else if slot.kind === 'run' && mounted && runtime} + <div + bind:this={overlayHostEl} + class="absolute inset-0 flex flex-col min-h-0 bg-surface {visibility}" + aria-hidden={!active} + > + {#if overlayHostEl} + {#await import('./RunViewerView.svelte')} + {@render editorLoading()} + {:then Module} + <!-- A run stays in the workspace it ran in, which the tab's URL names: the + session's own can change under an open tab (a staged fork committing). --> + <Module.default + {runtime} + jobId={slot.jobId} + workspaceId={slot.workspace ?? workspaceId} + tabId={tab.id} + container={overlayHostEl} + reloadNonce={runReloadNonce} + /> + {/await} + {/if} + </div> {:else if slot.kind === 'artifact' && mounted} <div bind:this={overlayHostEl} diff --git a/frontend/src/lib/components/sessions/RawAppEditorView.svelte b/frontend/src/lib/components/sessions/RawAppEditorView.svelte index de05359bd5..b944612f91 100644 --- a/frontend/src/lib/components/sessions/RawAppEditorView.svelte +++ b/frontend/src/lib/components/sessions/RawAppEditorView.svelte @@ -1,6 +1,5 @@ <script lang="ts"> import { tick, untrack } from 'svelte' - import { base } from '$lib/base' import { goto } from '$lib/navigation' import { sendUserToast } from '$lib/toast' import { UserDraft } from '$lib/userDraft.svelte' @@ -16,10 +15,15 @@ import DiffDrawer from '$lib/components/DiffDrawer.svelte' import type { WorkspaceItem } from '$lib/components/workspacePicker' import { removeSession, type SessionRuntime } from './sessionRuntime.svelte' - import { FRAMEWORK_TEMPLATES, STARTER_RUNNABLES } from '$lib/components/raw_apps/templates' + import { + BUILDER_FRAMEWORK_TEMPLATES, + FRAMEWORK_TEMPLATES, + STARTER_RUNNABLES + } from '$lib/components/raw_apps/templates' import SessionEditorTarget from './SessionEditorTarget.svelte' import { runResetToDeployed } from '$lib/userDraftToast' import { invalidateWorkspaceDrafts } from '$lib/workspaceDrafts.svelte' + import { operatorBuilderAppsIn } from '$lib/operatorWriteRights' import type { RawAppRuntimeLogRequester, RawAppRunsProvider, @@ -63,7 +67,10 @@ const files = cell.store.val?.files if (!newRawApp || (cell.saved.val && !cell.saved.val.no_deployed) || !files) return false const count = Object.keys(files).length - return Object.values(FRAMEWORK_TEMPLATES).some((template: Record<string, string>) => { + return [ + ...Object.values(FRAMEWORK_TEMPLATES), + ...Object.values(BUILDER_FRAMEWORK_TEMPLATES) + ].some((template: Record<string, string>) => { const keys = Object.keys(template) return count === keys.length && keys.every((k) => files[k] === template[k]) }) @@ -91,7 +98,10 @@ const setUp = { ...val, files: { ...result.files }, - runnables: { ...result.runnables, ...structuredClone(STARTER_RUNNABLES) }, + runnables: { + ...result.runnables, + ...(operatorBuilderAppsIn(workspaceId) ? {} : structuredClone(STARTER_RUNNABLES)) + }, data: result.data, policy: result.policy } @@ -110,7 +120,7 @@ if (mode === 'code') { // The session was opened for this app alone; with nothing said in it, it goes. const unused = runtime.manager.displayMessages.length === 0 - await goto(withWorkspaceParam(`${base}/apps_raw/edit/${path}`, workspaceId)) + await goto(withWorkspaceParam(`/apps_raw/edit/${path}`, workspaceId)) if (unused) removeSession(runtime.sessionId) return } diff --git a/frontend/src/lib/components/sessions/RunViewerView.svelte b/frontend/src/lib/components/sessions/RunViewerView.svelte new file mode 100644 index 0000000000..0266327f89 --- /dev/null +++ b/frontend/src/lib/components/sessions/RunViewerView.svelte @@ -0,0 +1,106 @@ +<script lang="ts"> + /* + * A run in a session preview tab, rendered by the component the workspace `/run/<id>` page + * renders. Everything it reaches is scoped to the run's workspace through `workspace`, and + * every navigation it attempts is caught here and turned into a move inside the preview + * panel, so nothing takes the browser out of the session. + */ + import { setContext, untrack } from 'svelte' + import RunDetail from '$lib/components/runs/RunDetail.svelte' + import type { SessionRuntime } from './sessionRuntime.svelte' + import { + parseHistoricalScriptEdit, + parsePreviewItemRoute, + parseRunRoute, + previewLocationLabel, + barePath + } from './previewRouter' + + let { + runtime, + jobId, + workspaceId, + tabId, + container, + reloadNonce = 0 + }: { + runtime: SessionRuntime + jobId: string + workspaceId: string + /** The preview tab hosting this run, which a move to another run re-points. */ + tabId: string + /** The tab's host element, which also holds the overlays the page portals out. */ + container: HTMLElement | undefined + /** Bumped to load the run again from the server. */ + reloadNonce?: number + } = $props() + + // Mounted in the preview panel, outside the chat's own subtree, as ItemViewerView is: the + // run page's AI entry points would otherwise offer a session from inside one. + setContext( + 'aiChatManager', + untrack(() => runtime.manager) + ) + + // Everything the run page navigates to, resolved against the preview panel. Another run — + // a re-run, a retry, the parent job — is still this tab's subject, so it re-points in + // place; an item or any other page opens beside it. Nothing reaches the top-level router. + function onNavigate(url: string): void { + const parsed = new URL(url, window.location.origin) + const href = `${parsed.pathname}${parsed.search}${parsed.hash}` + if (parseRunRoute(href)) { + runtime.previewTabs.navigate({ type: 'page', href, label: previewLocationLabel(href) }, tabId) + return + } + const route = parsePreviewItemRoute(href) + // Legacy drag-and-drop apps and historical script edits have no in-panel host, so they + // fall through to a page tab. So does `Run again`, whose args ride in the fragment, and + // a link to one version: opening an item focuses a tab already on it as it stands, + // where a page tab's URL is written whole, pin and fragment included. + if ( + route && + (route.kind !== 'app' || route.raw_app) && + !parseHistoricalScriptEdit(href) && + !parsed.hash && + !parsed.searchParams.has('version') + ) { + runtime.previewTabs.open({ + type: 'item', + item: { path: route.itemPath, summary: '', kind: route.kind, raw_app: route.raw_app }, + mode: route.mode + }) + return + } + runtime.previewTabs.open({ type: 'page', href, label: previewLocationLabel(barePath(href)) }) + } + + // Every in-app link under the tab, not only the ones that call `onNavigate`: a plain anchor + // followed by the browser would take it out of the session. Listened for on `body`, as + // ItemViewerView does and for the same reason. + $effect(() => { + const el = container + if (!el) return + function onClick(e: MouseEvent) { + if (e.defaultPrevented || e.button !== 0) return + if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return + const target = e.target as Element | null + if (!target || !el!.contains(target)) return + const a = target.closest?.('a[href]') as HTMLAnchorElement | null + if (!a || (a.target && a.target !== '_self') || a.hasAttribute('download')) return + const url = new URL(a.href, window.location.href) + if (url.origin !== window.location.origin) return + e.preventDefault() + if (a.getAttribute('href')?.startsWith('#')) return + onNavigate(`${url.pathname}${url.search}${url.hash}`) + } + document.body.addEventListener('click', onClick) + return () => document.body.removeEventListener('click', onClick) + }) +</script> + +<div class="flex h-full min-h-0 flex-col overflow-auto"> + <!-- Keyed: the run page binds one job's loaders and panels for its lifetime. --> + {#key `${workspaceId}/${jobId}/${reloadNonce}`} + <RunDetail id={jobId} workspace={workspaceId} {onNavigate} embedded /> + {/key} +</div> diff --git a/frontend/src/lib/components/sessions/SessionChangesBar.svelte b/frontend/src/lib/components/sessions/SessionChangesBar.svelte index 140300ea30..3929b78ca9 100644 --- a/frontend/src/lib/components/sessions/SessionChangesBar.svelte +++ b/frontend/src/lib/components/sessions/SessionChangesBar.svelte @@ -22,7 +22,7 @@ import { badgeCounts, badgeOf, buildDeployItems, type DeployItem } from './sessionDeployModel' import { useExistingMaskKeys } from './sessionDeployModel.svelte' import { previewTargetForDeployKind } from './sessionPreviewTabs.svelte' - import { pipelineFolderFromBundlePath } from '$lib/pipelinePaths' + import { PIPELINE_DRAFT_KIND, pipelineFolderFromBundlePath } from '$lib/pipelinePaths' import type { PreviewTarget } from './previewRouter' import JobsSegment from '$lib/components/copilot/chat/JobsSegment.svelte' import RowIcon from '$lib/components/common/table/RowIcon.svelte' @@ -378,6 +378,11 @@ onDataChanged={refreshDock} onItemDeployed={(item) => void runtime?.manager.renameModifiedItem(item.draftKind, item.path, item.displayPath)} - onItemDiscarded={(item) => void runtime?.manager.removeModifiedItem(item.draftKind, item.path)} + onItemDiscarded={(item) => { + void runtime?.manager.removeModifiedItem(item.draftKind, item.path) + const folder = pipelineFolderFromBundlePath(item.path) + if (item.draftKind === PIPELINE_DRAFT_KIND && folder) void runtime?.forgetPipelineDrafts(folder) + }} + deployPipeline={runtime?.deployPipeline} /> {/if} diff --git a/frontend/src/lib/components/sessions/SessionDiffDrawer.svelte b/frontend/src/lib/components/sessions/SessionDiffDrawer.svelte index 9f0f18674a..d921e435b0 100644 --- a/frontend/src/lib/components/sessions/SessionDiffDrawer.svelte +++ b/frontend/src/lib/components/sessions/SessionDiffDrawer.svelte @@ -5,6 +5,7 @@ import DevWorkspaceBadge from '$lib/components/DevWorkspaceBadge.svelte' import { useSessionDeployModel } from './sessionDeployModel.svelte' import type { DeployItem } from './sessionDeployModel' + import type { DeployResult } from '$lib/utils_workspace_deploy' // Session "Edits" drawer. Builds the deploy model over the session // workspace's drafts and hands it to WorkspaceDiffDrawer, which renders the @@ -18,7 +19,8 @@ keys, onDataChanged, onItemDeployed, - onItemDiscarded + onItemDiscarded, + deployPipeline }: { workspaceId: string parentWorkspaceId?: string @@ -35,6 +37,8 @@ * drops it. */ onItemDeployed?: (item: DeployItem) => void onItemDiscarded?: (item: DeployItem) => void + /** Forwarded to the deploy model: deploys a pipeline folder's draft bundle. */ + deployPipeline?: (folder: string) => Promise<DeployResult> } = $props() const isFork = $derived(!!parentWorkspaceId) @@ -50,7 +54,8 @@ mask: keys, onDataChanged, onItemDeployed, - onItemDiscarded + onItemDiscarded, + deployPipeline })) // Editor URL for a row (every item lives in the session workspace). diff --git a/frontend/src/lib/components/sessions/SessionModeSwitch.svelte b/frontend/src/lib/components/sessions/SessionModeSwitch.svelte index a14990583d..2d3d0fbef2 100644 --- a/frontend/src/lib/components/sessions/SessionModeSwitch.svelte +++ b/frontend/src/lib/components/sessions/SessionModeSwitch.svelte @@ -6,7 +6,6 @@ import { goto } from '$lib/navigation' import { sendUserToast } from '$lib/toast' import { page } from '$app/state' - import { base } from '$lib/base' // Which side of the switch is active. `nav` = workspace navigation (the classic // app), `session` = the sessions sidebar + chat + preview. @@ -47,7 +46,7 @@ if (mode !== 'nav') return // `goto` has no same-URL short-circuit, so navigating from home would push a // duplicate history entry and make the next Back press look broken. - if (page.url.pathname === `${base}/`) return + if (page.url.pathname === '/') return void goto('/') } </script> diff --git a/frontend/src/lib/components/sessions/SessionPicker.svelte b/frontend/src/lib/components/sessions/SessionPicker.svelte index e81a0e500f..898a97739b 100644 --- a/frontend/src/lib/components/sessions/SessionPicker.svelte +++ b/frontend/src/lib/components/sessions/SessionPicker.svelte @@ -60,13 +60,12 @@ import MenuButton, { sidebarClasses } from '$lib/components/sidebar/MenuButton.svelte' import DropdownV2 from '$lib/components/DropdownV2.svelte' import { isGlobalAiEnabled } from '$lib/components/copilot/chat/global/gate' - import { userWorkspaces, workspaceStore } from '$lib/stores' + import { userStore, userWorkspaces, workspaceStore } from '$lib/stores' import { workspaceIsFork } from '$lib/utils/workspaceHierarchy' import { WorkspaceService } from '$lib/gen' import { sendUserToast } from '$lib/toast' import { currentWorkspaceRootId, workspaceRootId } from './sessionScope.svelte' import { page } from '$app/state' - import { base } from '$app/paths' import DevWorkspaceBadge from '$lib/components/DevWorkspaceBadge.svelte' import { dateBucket, @@ -119,7 +118,7 @@ // Only highlight the active session while the sessions page is open — elsewhere // `currentSessionId` lingers but no row should appear selected. - const onSessionsPage = $derived(page.url.pathname.startsWith(`${base}/sessions`)) + const onSessionsPage = $derived(page.url.pathname.startsWith('/sessions')) const sessionActive = $derived(onSessionsPage) interface Props { @@ -221,7 +220,7 @@ // Workspace tree scoped to the current family (root + its forks), so the rail // only shows the workspaces in the family we're in — not every workspace. const workspaceTreeItems = $derived.by(() => { - const all = buildWorkspaceHierarchy($userWorkspaces) + const all = buildWorkspaceHierarchy($userWorkspaces, $userStore?.email) const currentRoot = $currentWorkspaceRootId if (!currentRoot) return all return all.filter((i) => workspaceRootId(i.workspace.id, $userWorkspaces) === currentRoot) @@ -1338,8 +1337,8 @@ bind:open={seedOfferOpen} kind="X" enterConfirms={false} - title="Keep this {seedOffer?.route.kind ?? 'item'} in the new session?" - description="You came here from {seedOffer?.route.itemPath ?? ''}." + title="Keep this {seedOffer?.kind ?? 'item'} in the new session?" + description="You came here from {seedOffer?.path ?? ''}." > <p class="text-sm text-secondary"> Keeping it opens it in the preview, so the chat starts with it as context. diff --git a/frontend/src/lib/components/sessions/SessionShareButton.svelte b/frontend/src/lib/components/sessions/SessionShareButton.svelte new file mode 100644 index 0000000000..59f2fd19cb --- /dev/null +++ b/frontend/src/lib/components/sessions/SessionShareButton.svelte @@ -0,0 +1,231 @@ +<script lang="ts"> + import { Globe, Link, Share2 } from 'lucide-svelte' + import { resource } from 'runed' + import { Button } from '$lib/components/common' + import Popover from '$lib/components/meltComponents/Popover.svelte' + import ClipboardPanel from '$lib/components/details/ClipboardPanel.svelte' + import Toggle from '$lib/components/Toggle.svelte' + import { AiService, type SharedAiSessionInfo } from '$lib/gen' + import { userWorkspaces } from '$lib/stores' + import { sendUserToast } from '$lib/toast' + import { copyToClipboard, displayDate } from '$lib/utils' + import { shareWorkspaceId } from '$lib/components/copilot/chat/artifacts/artifactSharing' + import type { AIChatManager } from '$lib/components/copilot/chat/AIChatManager.svelte' + import { buildSessionSnapshot, sharedSessionUrl } from './sessionSharing' + + interface Props { + sessionId: string + name: string + /** The workspace the session acts on; undefined until its first message is sent. */ + workspaceId: string | undefined + manager: AIChatManager + } + + let { sessionId, name, workspaceId, manager }: Props = $props() + + const workspace = $derived( + workspaceId ? shareWorkspaceId(workspaceId, $userWorkspaces) : undefined + ) + const messageCount = $derived(manager.displayMessages.length) + const shareName = $derived(name.trim() || 'Untitled session') + + const status = resource( + () => ({ workspace, sessionId }), + async ({ workspace, sessionId }) => { + if (!workspace) return undefined + try { + return await AiService.getAiSessionShareStatus({ workspace, sessionId }) + } catch (err) { + // The button still works without it: sharing reports its own failure. + console.error('Could not read the session share status', err) + return undefined + } + } + ) + + const share = $derived(status.current?.share) + const url = $derived(share && workspace ? sharedSessionUrl(workspace, share.id) : undefined) + // A hint only: an edited and regenerated turn keeps both, so updating stays offered either way. + const outdated = $derived( + share !== undefined && (share.message_count !== messageCount || share.name !== shareName) + ) + + let saving = $state(false) + + function errorMessage(err: unknown): string { + const body = (err as { body?: unknown })?.body + return typeof body === 'string' && body ? body : String((err as Error)?.message ?? err) + } + + function reflect(next: SharedAiSessionInfo | undefined) { + if (status.current) status.mutate({ ...status.current, share: next }) + } + + async function shareSnapshot() { + if (!workspace) return + const updating = share !== undefined + saving = true + try { + const snapshot = buildSessionSnapshot( + $state.snapshot(manager.displayMessages), + $state.snapshot(manager.artifacts.artifacts) + ) + const shared = await AiService.shareAiSession({ + workspace, + requestBody: { + session_id: sessionId, + name: shareName, + message_count: messageCount, + snapshot + } + }) + if (status.current) reflect(shared) + else await status.refetch() + if (updating) { + sendUserToast('The link now shows the latest messages') + } else if (await copyToClipboard(sharedSessionUrl(workspace, shared.id), false)) { + sendUserToast('Link copied to clipboard') + } + } catch (err) { + sendUserToast(`Could not share the session: ${errorMessage(err)}`, true) + } finally { + saving = false + } + } + + async function setPublic(isPublic: boolean) { + if (!workspace || !share) return + saving = true + try { + reflect( + await AiService.setAiSessionSharePublic({ + workspace, + id: share.id, + requestBody: { is_public: isPublic } + }) + ) + } catch (err) { + sendUserToast(`Could not change who can open the link: ${errorMessage(err)}`, true) + } finally { + saving = false + } + } + + async function stopSharing() { + if (!workspace || !share) return + saving = true + try { + await AiService.unshareAiSession({ workspace, id: share.id }) + reflect(undefined) + sendUserToast('Stopped sharing: the link no longer opens') + } catch (err) { + sendUserToast(`Could not stop sharing: ${errorMessage(err)}`, true) + } finally { + saving = false + } + } +</script> + +<Popover + placement="bottom-end" + contentClasses="!bg-surface" + disabled={!workspace || messageCount === 0} + triggerAttrs={{ 'aria-label': 'Share session', 'aria-haspopup': 'dialog' }} +> + {#snippet trigger()} + <!-- Icon only, like the session menu beside it: tinted once a link exists. --> + <Button + unifiedSize="xs" + variant="subtle" + iconOnly + nonCaptureEvent + disabled={!workspace || messageCount === 0} + btnClasses={share ? '!text-accent' : 'text-tertiary'} + startIcon={{ icon: share ? (share.is_public ? Globe : Link) : Share2 }} + title={!workspace || messageCount === 0 + ? 'Send a first message to share this session' + : share + ? share.is_public + ? 'Shared publicly' + : 'Shared with the workspace' + : 'Share session'} + /> + {/snippet} + {#snippet content()} + <div class="flex w-80 flex-col gap-3 p-3 text-xs"> + <div class="flex flex-col gap-1"> + <span class="font-semibold text-emphasis">Share session</span> + <span class="font-normal text-secondary"> + {#if share?.is_public} + Anyone with the link can read a copy of this conversation. Nobody can continue it. + {:else} + Members of {workspace} can read a copy of this conversation with the link. Nobody can continue + it. + {/if} + </span> + </div> + + {#if share && url} + <Toggle + size="xs" + checked={share.is_public} + disabled={saving} + options={{ + right: 'Public', + rightTooltip: 'Anyone with the link can open it, without signing in' + }} + on:change={(e) => setPublic(e.detail)} + /> + <div class="flex flex-col gap-1"> + <ClipboardPanel content={url} size="sm" /> + <span class="text-2xs font-normal text-hint"> + Shows {share.message_count} message{share.message_count === 1 ? '' : 's'} as of {displayDate( + share.shared_at + )} + </span> + </div> + <div class="flex items-center justify-between gap-2"> + <span class="font-normal text-secondary"> + {outdated + ? 'The session changed since it was shared.' + : 'The link shows the session as it was when shared.'} + </span> + <Button + unifiedSize="sm" + variant={outdated ? 'accent' : 'default'} + loading={saving} + disabled={manager.loading} + onClick={shareSnapshot} + > + Update link + </Button> + </div> + <div class="flex justify-end"> + <Button + unifiedSize="sm" + variant="default" + destructive + disabled={saving} + onClick={stopSharing} + > + Stop sharing + </Button> + </div> + {:else} + <div class="flex justify-end"> + <Button + unifiedSize="sm" + variant="accent" + startIcon={{ icon: Link }} + loading={saving} + disabled={status.loading || manager.loading} + title={manager.loading ? 'Wait for the current turn to finish' : undefined} + onClick={shareSnapshot} + > + Create link + </Button> + </div> + {/if} + </div> + {/snippet} +</Popover> diff --git a/frontend/src/lib/components/sessions/SessionWrapper.svelte b/frontend/src/lib/components/sessions/SessionWrapper.svelte index af00454f81..05a0cdda41 100644 --- a/frontend/src/lib/components/sessions/SessionWrapper.svelte +++ b/frontend/src/lib/components/sessions/SessionWrapper.svelte @@ -26,6 +26,7 @@ } from 'lucide-svelte' import SessionWorkspaceBar from './SessionWorkspaceBar.svelte' import SessionChangesBar from './SessionChangesBar.svelte' + import SessionShareButton from './SessionShareButton.svelte' import { clearSessionRecovered, isSessionRecovered } from './sessionRecoveryNotice.svelte' import { composerFocusRequest, @@ -432,6 +433,13 @@ </span> {/snippet} </DropdownV2> + + <SessionShareButton + sessionId={session.id} + name={session.summary ?? ''} + workspaceId={session.workspace_id} + manager={runtime.manager} + /> {/snippet} {#if headerInPage} @@ -440,7 +448,11 @@ breadcrumb's own workspace part, the way every other route names it — a session in a fork reads like anything else in that fork. --> <PageHeaderContent - section={{ label: session.summary ?? 'Untitled session', content: sessionHeader }} + section={{ + label: session.summary ?? 'Untitled session', + content: sessionHeader, + noNavPicker: true + }} {actingWorkspaceId} /> {/if} diff --git a/frontend/src/lib/components/sessions/SessionsBetaBanner.svelte b/frontend/src/lib/components/sessions/SessionsBetaBanner.svelte index 86b6ba030a..0d523a4e65 100644 --- a/frontend/src/lib/components/sessions/SessionsBetaBanner.svelte +++ b/frontend/src/lib/components/sessions/SessionsBetaBanner.svelte @@ -1,5 +1,4 @@ <script lang="ts"> - import { base } from '$lib/base' import { Button } from '$lib/components/common' import { classes as alertClasses, icons as alertIcons } from '$lib/components/common/alert/model' import { clearSessionsBetaOptOut } from '$lib/components/copilot/chat/global/gate' @@ -22,7 +21,7 @@ <Button variant="subtle" unifiedSize="xs" - onclick={() => clearSessionsBetaOptOut(`${base}/sessions`)} + onclick={() => clearSessionsBetaOptOut('/sessions')} > Activate </Button> diff --git a/frontend/src/lib/components/sessions/SharedSessionTranscript.svelte b/frontend/src/lib/components/sessions/SharedSessionTranscript.svelte new file mode 100644 index 0000000000..19239fe48c --- /dev/null +++ b/frontend/src/lib/components/sessions/SharedSessionTranscript.svelte @@ -0,0 +1,121 @@ +<script lang="ts"> + import { Button, Drawer, DrawerContent } from '$lib/components/common' + import { FileText } from 'lucide-svelte' + import AIChatMessage from '$lib/components/copilot/chat/AIChatMessage.svelte' + import ToolGroupDisplay from '$lib/components/copilot/chat/ToolGroupDisplay.svelte' + import ArtifactBody from '$lib/components/copilot/chat/artifacts/ArtifactBody.svelte' + import { setChatViewHost } from '$lib/components/copilot/chat/chatViewHost' + import { readOnlyChatViewHost } from '$lib/components/copilot/chat/readOnlyChatViewHost.svelte' + import { chatItemKey, groupToolRuns } from '$lib/components/copilot/chat/toolGroups' + import type { DisplayMessage } from '$lib/components/copilot/chat/shared' + import type { SessionSnapshot } from './sessionSharing' + import { untrack } from 'svelte' + + interface Props { + snapshot: SessionSnapshot + workspace: string + } + + let { snapshot, workspace }: Props = $props() + + let openArtifactId: string | undefined = $state(undefined) + let drawer: Drawer | undefined = $state(undefined) + + // Built once: the page remounts this component for another share. + const initial = untrack(() => ({ snapshot, workspace })) + setChatViewHost( + readOnlyChatViewHost({ + messages: initial.snapshot.messages, + workspace: initial.workspace, + artifacts: initial.snapshot.artifacts.map((a) => ({ + ...a, + sessionId: '', + createdAt: 0, + updatedAt: 0 + })), + openArtifact: (id) => showArtifact(id) + }) + ) + + function showArtifact(id: string) { + openArtifactId = id + drawer?.openDrawer() + } + + const messages = $derived(snapshot.messages) + const chatItems = $derived(groupToolRuns(messages)) + const openArtifact = $derived(snapshot.artifacts.find((a) => a.id === openArtifactId)) + + // An answer's copy row shows once per turn, on its last answer, as in the live chat. + const showsAnswerActions = $derived.by(() => { + const shows: boolean[] = new Array(messages.length).fill(false) + const answeredLater = new Set<string | undefined>() + for (let i = messages.length - 1; i >= 0; i--) { + const message = messages[i] + if (message.role === 'user' || message.role === 'summary') { + answeredLater.clear() + } else if (message.role === 'assistant' && message.content) { + const run = message.jobId ?? message.stepName + shows[i] = !answeredLater.has(run) + answeredLater.add(run) + } + } + return shows + }) +</script> + +{#snippet messageRow(message: DisplayMessage, messageIndex: number, inGroup: boolean)} + <AIChatMessage + {message} + {messageIndex} + availableContext={[]} + editingMessageIndex={null} + isLast={messageIndex === messages.length - 1} + {inGroup} + showAnswerActions={showsAnswerActions[messageIndex]} + /> +{/snippet} +{#snippet groupRow(message: DisplayMessage, messageIndex: number)} + {@render messageRow(message, messageIndex, true)} +{/snippet} + +{#if snapshot.artifacts.length > 0} + <!-- The transcript only links plan documents; every other artifact is reached from here. --> + <div class="mb-4 flex flex-wrap items-center gap-2 px-2"> + <span class="text-xs font-semibold text-emphasis">Artifacts</span> + {#each snapshot.artifacts as artifact (artifact.id)} + <Button + unifiedSize="sm" + variant="default" + startIcon={{ icon: FileText }} + onClick={() => showArtifact(artifact.id)} + > + {artifact.name} + </Button> + {/each} + </div> +{/if} + +<div class="flex flex-col pb-2"> + {#each chatItems as item (chatItemKey(item))} + {#if item.kind === 'group'} + <div class="mb-1 min-w-0 text-sm px-2 text-primary"> + <div class="px-[1px]"> + <ToolGroupDisplay group={item} entry={groupRow} /> + </div> + </div> + {:else} + {@render messageRow(item.message, item.index, false)} + {/if} + {/each} +</div> + +<Drawer bind:this={drawer} size="900px"> + <DrawerContent title={openArtifact?.name ?? 'Artifact'} on:close={() => drawer?.closeDrawer()}> + {#if openArtifact} + <ArtifactBody content={openArtifact.content} source={openArtifact.kind !== 'md'} /> + {:else} + <span class="text-xs text-secondary">This artifact was not part of the share.</span> + {/if} + </DrawerContent> +</Drawer> diff --git a/frontend/src/lib/components/sessions/WorkspaceFamilyPicker.svelte b/frontend/src/lib/components/sessions/WorkspaceFamilyPicker.svelte index f5b7e8d34f..09fed8bba6 100644 --- a/frontend/src/lib/components/sessions/WorkspaceFamilyPicker.svelte +++ b/frontend/src/lib/components/sessions/WorkspaceFamilyPicker.svelte @@ -10,11 +10,11 @@ type UserWorkspace } from '$lib/stores' import { - findWorkspaceDescendants, findCanonicalDevWorkspace, findDefaultForkBase, findWorkspaceRoot, - buildWorkspaceHierarchy + buildWorkspaceHierarchy, + workspaceSubtreeRows } from '$lib/utils/workspaceHierarchy' import { useForkableWorkspaces } from '$lib/utils/useForkableWorkspaces.svelte' import { canCreateFork } from '$lib/utils/editInFork' @@ -102,7 +102,11 @@ }) const forkableWorkspaces = $derived(forkableWorkspacesProp ?? ownForkable.current) const root = $derived(findWorkspaceRoot(effectiveId, forkableWorkspaces)) - const forks = $derived(root ? findWorkspaceDescendants(root.id, forkableWorkspaces) : []) + // The same hierarchy the sidebar workspace menu builds: forks of forks follow their parent, and the + // user's own forks lead each group of siblings. + const hierarchy = $derived(buildWorkspaceHierarchy(forkableWorkspaces, $userStore?.email)) + const forkRows = $derived(root ? workspaceSubtreeRows(root.id, hierarchy) : []) + const forks = $derived(forkRows.map((h) => h.workspace)) // The family's canonical dev workspace, if any — still used for gating (a forking-locked root can be // forked via its dev) and as a selectable base with a "dev" badge. @@ -126,13 +130,10 @@ })) ) - // Depth of each workspace within its family (root = 0, its forks = 1, forks of forks = 2, …), from - // the shared hierarchy builder — the same one the sidebar workspace menu uses — so the list indents - // forks of forks under their parent the same way. `forks` is a DFS of descendants (parent before - // child), so indenting each row by its depth nests it under its parent. - const familyDepths = $derived( - new Map(buildWorkspaceHierarchy(forkableWorkspaces).map((h) => [h.workspace.id, h.depth])) - ) + // Depth of each workspace within its family (root = 0, its forks = 1, forks of forks = 2, …). + // `forks` is a DFS (parent before child), so indenting each row by its depth nests it under its + // parent, the same way the sidebar menu does. + const familyDepths = $derived(new Map(hierarchy.map((h) => [h.workspace.id, h.depth]))) // Extra left padding (on top of the row's base px-3) to nest a workspace one step per depth level, // matching the sidebar menu's `depth * 16px`. function indentStyle(id: string): string | undefined { @@ -429,9 +430,16 @@ /> </div> {/if} - {#each forks as f, fi (f.id)} + {#each forkRows as { workspace: f, separatorBefore }, fi (f.id)} {@const forkIdx = (root ? 1 : 0) + fi} {@const accentStyle = forkAccentStyle(f.color)} + {#if separatorBefore} + <div + class="my-1 border-t border-border-light shrink-0" + style:margin-left={`${((familyDepths.get(f.id) ?? 1) - 1) * 16}px`} + role="separator" + ></div> + {/if} <div class="relative group shrink-0"> <button type="button" diff --git a/frontend/src/lib/components/sessions/modifiedItemsMask.test.ts b/frontend/src/lib/components/sessions/modifiedItemsMask.test.ts index 6cad6121cd..e5f4ff9873 100644 --- a/frontend/src/lib/components/sessions/modifiedItemsMask.test.ts +++ b/frontend/src/lib/components/sessions/modifiedItemsMask.test.ts @@ -62,6 +62,12 @@ describe('diffInMask', () => { expect(diffInMask(diff('script', 'u/me/s'), mask)).toBe(true) }) + it('selects only the scripts a masked pipeline deployed, not the rest of its folder', () => { + const mask = new Set(['data_pipeline:f/crm/data_pipeline', 'script:f/crm/clean']) + expect(diffInMask(diff('script', 'f/crm/clean'), mask)).toBe(true) + expect(diffInMask(diff('script', 'f/crm/unrelated'), mask)).toBe(false) + }) + it('matches a legacy app diff under both its identity and bridged mask keys', () => { expect(diffInMask(diff('app', 'u/me/legacy'), new Set(['app:u/me/legacy']))).toBe(true) expect(diffInMask(diff('app', 'u/me/legacy'), new Set(['raw_app:u/me/legacy']))).toBe(true) diff --git a/frontend/src/lib/components/sessions/modifiedItemsMask.ts b/frontend/src/lib/components/sessions/modifiedItemsMask.ts index 7d0d3abbae..d597c46ec9 100644 --- a/frontend/src/lib/components/sessions/modifiedItemsMask.ts +++ b/frontend/src/lib/components/sessions/modifiedItemsMask.ts @@ -1,4 +1,5 @@ import type { UserDraftItemKind, WorkspaceItemDiff } from '$lib/gen' +import { PIPELINE_DRAFT_KIND, pipelineBundlePath } from '$lib/pipelinePaths' // The "modified items mask" tracks which workspace items an AI chat touched via // tool calls. Each key is `${UserDraftItemKind}:${storagePath}`. UserDraftItemKind @@ -45,6 +46,21 @@ export function forkDiffKindToUserDraftKind(kind: ForkDiffKind): UserDraftItemKi return FORK_DIFF_KIND_TO_USER_DRAFT_KIND[kind] } +// A pipeline the chat edited is masked as its folder's draft bundle, and each +// script that bundle deploys is masked too, so a fork review selects exactly +// those. The session's changes list shows deployed scripts of a masked +// pipeline's folder as that pipeline's one row — any of them, since a script's +// mask entry does not say whether a pipeline deploy or the chat put it there. +export function foldedIntoPipelineRow( + mask: ReadonlySet<string>, + kind: UserDraftItemKind, + path: string +): boolean { + if (kind !== 'script') return false + const folder = path.match(/^f\/([^/]+)\//)?.[1] + return !!folder && mask.has(maskKey(PIPELINE_DRAFT_KIND, pipelineBundlePath(folder))) +} + // True when a fork-comparison diff names an item present in the chat-modified mask. export function diffInMask(diff: WorkspaceItemDiff, mask: Set<string>): boolean { const kind = forkDiffKindToUserDraftKind(diff.kind) diff --git a/frontend/src/lib/components/sessions/openInSessionContext.ts b/frontend/src/lib/components/sessions/openInSessionContext.ts index ddecb01b4f..af1a5113ad 100644 --- a/frontend/src/lib/components/sessions/openInSessionContext.ts +++ b/frontend/src/lib/components/sessions/openInSessionContext.ts @@ -1,6 +1,6 @@ import { getContext, onDestroy, setContext } from 'svelte' import type { OpenInSessionSource } from './OpenInSessionButton.svelte' -import type { PreviewItemRoute } from './previewPaths' +import type { SessionTarget } from './sessionState.svelte' // The "Open in AI session" hand-off, published by the component that owns the // item being edited (FlowBuilder, RawAppEditor) for AI entry points too deep in @@ -38,20 +38,17 @@ export function getOpenInSessionHandoff(): OpenInSessionHandoff | undefined { return getContext<OpenInSessionHandoff | undefined>(KEY) } -/** The mounted editor's hand-off for the item `route` names, or undefined when - * no editor on screen publishes one for it (a legacy app, a detail page). - * Matched on the item rather than taken as "the latest registered": a script - * editor mounted in a flow's drawer registers too, and the rail wants the - * page's own item. */ +/** The mounted editor's hand-off for `target`, or undefined when no editor on + * screen publishes one for it (a detail page). Matched on the item rather than + * taken as "the latest registered": a script editor mounted in a flow's drawer + * registers too, and the rail wants the page's own item. */ export function findMountedOpenInSessionSource( - route: PreviewItemRoute + target: SessionTarget ): OpenInSessionSource | undefined { - const kind = route.kind === 'app' ? (route.raw_app ? 'raw_app' : undefined) : route.kind - if (!kind) return undefined for (const handoff of mounted) { const source = handoff.source() - const target = source?.target - if (target && target.kind === kind && target.path === route.itemPath) return source + const t = source?.target + if (t && t.kind === target.kind && t.path === target.path) return source } return undefined } diff --git a/frontend/src/lib/components/sessions/pageDrawerSession.ts b/frontend/src/lib/components/sessions/pageDrawerSession.ts index 0a3e7435ca..35d0a4560b 100644 --- a/frontend/src/lib/components/sessions/pageDrawerSession.ts +++ b/frontend/src/lib/components/sessions/pageDrawerSession.ts @@ -12,8 +12,7 @@ import type { UserDraftItemKind } from '$lib/gen' // every trigger's save utils eager. import { drawerHashFor, - pageHref, - stripBase, + barePath, TRIGGER_PAGES, RESOURCES_PATH, SCHEDULES_PATH, @@ -77,7 +76,7 @@ async function flushOrRefuse(query: Parameters<typeof UserDraftDbSyncer.flush>[0 export function setPageDrawerAnchor(pagePath: string, itemPath: string | undefined): void { if (!itemPath) return const { pathname, search, hash } = window.location - if (stripBase(pathname) !== pagePath) return + if (barePath(pathname) !== pagePath) return const anchor = `#${drawerHashFor(pagePath, itemPath)}` if (hash === anchor) return history.replaceState(history.state, '', `${pathname}${search}${anchor}`) @@ -94,7 +93,7 @@ export async function clearPageDrawerAnchor(pagePath: string): Promise<void> { // filters with shallow routing, which never reaches `page.url`, so rebuilding the query // from it would drop the filters the user typed along with the anchor. const { pathname, search, hash } = window.location - if (stripBase(pathname) !== pagePath || !hash) return + if (barePath(pathname) !== pagePath || !hash) return await goto(`${pathname}${search}`, { replaceState: true, noScroll: true }) } @@ -112,14 +111,14 @@ export function pageDrawerSessionSource( itemPath: string | undefined, workspaceId: string | undefined ): OpenInSessionSource | undefined { - if (!itemPath || stripBase(page.url.pathname) !== pagePath) return undefined + if (!itemPath || barePath(page.url.pathname) !== pagePath) return undefined const anchor = drawerHashFor(pagePath, itemPath) const itemKind = DRAWER_DRAFT_KIND[pagePath] return { // The list behind the drawer is part of what the user is looking at, and its filters // are written with shallow routing — so the query has to come from the document at // click time, as the thunk exists for. - page: () => `${pageHref(pagePath)}${window.location.search}#${anchor}`, + page: () => `${pagePath}${window.location.search}#${anchor}`, workspaceId, // Autosave is debounced, and the preview reads the draft back through the server // from a document of its own — routing before the POST lands opens the drawer on a diff --git a/frontend/src/lib/components/sessions/previewPaths.ts b/frontend/src/lib/components/sessions/previewPaths.ts index 10ad5b00ef..31c610889d 100644 --- a/frontend/src/lib/components/sessions/previewPaths.ts +++ b/frontend/src/lib/components/sessions/previewPaths.ts @@ -1,5 +1,5 @@ -import { base } from '$lib/base' import type { WorkspaceItemKind } from '$lib/components/workspacePicker' +import { normalizePipelineFolder } from '$lib/utils/pipelineFolder' // The paths a preview location can point at, and the base handling around them. Kept apart // from `previewRouter`, which reads a location's *view* from each page's filter schema and @@ -62,7 +62,7 @@ export const drawerHashFor = (pagePath: string, itemPath: string) => /** The full page a page item is edited on: its list page, with the row's drawer open. */ export function pageItemPageHref(ref: PageItemRef): string { const listPath = pageItemListPath(ref) - return `${pageHref(listPath)}#${drawerHashFor(listPath, ref.path)}` + return `${listPath}#${drawerHashFor(listPath, ref.path)}` } /** The list page a page item is edited from. */ @@ -79,14 +79,25 @@ export function pageItemListPath(ref: PageItemRef): string { } } -/** Whether a (base-stripped) path is the list page of a page item kind. */ +/** Whether a path is the list page of a page item kind. */ export function isPageItemListPath(path: string): boolean { return pageItemForListPath(path, '') !== undefined } +/** Whether a path is the runs list: every run, or `/runs/<item path>` for one item's. */ +export function isRunsListPath(path: string): boolean { + const clean = barePath(path) + return clean === RUNS_PATH || clean.startsWith(`${RUNS_PATH}/`) +} + +/** Whether a path is a list page a session preview mounts in process rather than frames. */ +export function isPreviewListPath(path: string): boolean { + return isPageItemListPath(path) || isRunsListPath(path) +} + /** The page item a list page's row names, or undefined for a page that lists none. */ export function pageItemForListPath(pagePath: string, path: string): PageItemRef | undefined { - const clean = stripBase(pagePath) + const clean = barePath(pagePath) if (clean === VARIABLES_PATH) return { kind: 'variable', path } if (clean === RESOURCES_PATH) return { kind: 'resource', path } if (clean === SCHEDULES_PATH) return { kind: 'schedule', path } @@ -134,21 +145,25 @@ export function pageItemKindLabel(ref: PageItemRef): string { } } -/** Label a trigger list page from its (base-stripped) pathname, or undefined. */ +/** Label a trigger list page from its pathname, or undefined. */ export function triggerLabelForPath(path: string): string | undefined { - const clean = stripBase(path) + const clean = barePath(path) return Object.values(TRIGGER_PAGES).find((t) => t.path === clean)?.label } export const pageKey = (path: string) => `page:${path}` -export const pageHref = (path: string) => `${base}${path}` +export const isPageKey = (key: string) => key.startsWith('page:') -/** Strip the deployment base prefix (and any query/hash) from a preview path - * so it can be matched against `PREVIEW_PAGES` / parsed as an item route. */ -export function stripBase(path: string): string { - let p = path.split('?')[0].split('#')[0] - if (base && p.startsWith(base)) p = p.slice(base.length) - return p || '/' +/** Strip the query and hash from a preview path so it can be matched against + * `PREVIEW_PAGES` / parsed as an item route. */ +export function barePath(path: string): string { + // The router serves `/runs/` as `/runs`, and links are written both ways. + return ( + path + .split('?')[0] + .split('#')[0] + .replace(/(.)\/+$/, '$1') || '/' + ) } /** Which side of an item a route addresses: `/edit/` builds it, `/get/` shows the @@ -166,7 +181,7 @@ export type PreviewItemRoute = { // non-item page (home, runs, …). Shared by the breadcrumb (drill segments) and // `previewRouter`'s tab resolver so both agree on what counts as an item route. export function parsePreviewItemRoute(fullPath: string): PreviewItemRoute | null { - const p = stripBase(fullPath) + const p = barePath(fullPath) const m = p.match(/^\/(scripts|flows|apps|apps_raw)\/(edit|get)\/(.+)$/) if (!m) return null const itemPath = decodeURIComponent(m[3]) @@ -186,3 +201,11 @@ export function parseHistoricalScriptEdit(url: string): { path: string; hash: st const hash = new URL(url, 'http://x').searchParams.get('hash') return hash ? { path: route.itemPath, hash } : null } + +// A `/pipeline/<folder>` route is the data-pipeline graph editor for that folder +// (the folder is a single path segment, not a workspace item path). The bare +// `/pipeline` list page is not an editor. Returns the folder name, or null. +export function parsePipelineRoute(fullPath: string): string | null { + const m = barePath(fullPath).match(/^\/pipeline\/([^/?#]+)/) + return m ? normalizePipelineFolder(decodeURIComponent(m[1])) : null +} diff --git a/frontend/src/lib/components/sessions/previewReload.test.ts b/frontend/src/lib/components/sessions/previewReload.test.ts index e7924a1813..2cc40cd3cc 100644 --- a/frontend/src/lib/components/sessions/previewReload.test.ts +++ b/frontend/src/lib/components/sessions/previewReload.test.ts @@ -9,6 +9,7 @@ describe('toolReloadEffect', () => { expect(toolReloadEffect('write_resource', {}).pages).toEqual(['/resources']) expect(toolReloadEffect('write_variable', {}).pages).toEqual(['/variables']) expect(toolReloadEffect('create_folder', { name: 'f' }).pages).toEqual(['/folders']) + expect(toolReloadEffect('create_resource_type', { name: 'c_x' }).pages).toEqual(['/resources']) }) it('maps a trigger write to its kind-specific page', () => { diff --git a/frontend/src/lib/components/sessions/previewReload.ts b/frontend/src/lib/components/sessions/previewReload.ts index d9259c900d..1de6ad6951 100644 --- a/frontend/src/lib/components/sessions/previewReload.ts +++ b/frontend/src/lib/components/sessions/previewReload.ts @@ -5,13 +5,13 @@ import { pageItemUrl, parsePageItemRoute, parsePreviewItemRoute, - stripBase, + barePath, TRIGGER_PAGES, type PageItemRef, type TriggerKind } from './previewPaths' -// Which list pages a completed chat tool can change, as base-stripped paths +// Which list pages a completed chat tool can change, as paths // (e.g. `/schedules`). This allowlist is the single source of truth for "does // this tool change a list page a preview tab might show". A new mutating tool // that surfaces on one of these pages must be added here or that tab silently @@ -49,6 +49,8 @@ export function toolReloadEffect(name: string, args: any): ToolReloadEffect { return withItem(['/variables'], itemRef('variable', args)) case 'create_folder': return { pages: ['/folders'], items: [], deployed: [] } + case 'create_resource_type': + return { pages: ['/resources'], items: [], deployed: [] } // These two change what is deployed at a path, so a tab on that item's View side // is showing a version that no longer exists. case 'delete_workspace_item': @@ -128,7 +130,7 @@ export function tabsToReload( if (pages.size === 0) return [] return tabs.filter((t) => { const pageItem = parsePageItemRoute(t.url) - if (!pageItem) return pages.has(stripBase(whereIs(t))) + if (!pageItem) return pages.has(barePath(whereIs(t))) const listPath = pageItemListPath(pageItem) if (!pages.has(listPath)) return false const named = [...items].some((u) => pageItemListPath(parsePageItemRoute(u)!) === listPath) diff --git a/frontend/src/lib/components/sessions/previewRouter.test.ts b/frontend/src/lib/components/sessions/previewRouter.test.ts index 038691da55..18d287769e 100644 --- a/frontend/src/lib/components/sessions/previewRouter.test.ts +++ b/frontend/src/lib/components/sessions/previewRouter.test.ts @@ -313,7 +313,30 @@ describe('itemDisplayName', () => { describe('resolvePreviewTab', () => { it('routes a static page to the iframe fallback', () => { - expect(resolvePreviewTab('/runs')).toEqual({ kind: 'iframe' }) + expect(resolvePreviewTab('/audit_logs')).toEqual({ kind: 'iframe' }) + }) + + it('mounts a run in process, in the workspace its URL names', () => { + expect(resolvePreviewTab('/run/01a0?workspace=fork')).toEqual({ + kind: 'run', + jobId: '01a0', + workspace: 'fork' + }) + expect(resolvePreviewTab('/run/01a0')).toEqual({ kind: 'run', jobId: '01a0' }) + expect(resolvePreviewTab('/run/01a0?workspace=fork&view_token=t')).toEqual({ kind: 'iframe' }) + }) + + it('mounts the runs list in process, for every run or for one item', () => { + expect(resolvePreviewTab('/runs?status=failure')).toEqual({ kind: 'pagelist', path: '/runs' }) + expect(resolvePreviewTab('/runs/f/a/b')).toEqual({ kind: 'pagelist', path: '/runs/f/a/b' }) + expect(resolvePreviewTab('/runsheet')).toEqual({ kind: 'iframe' }) + }) + + it('tells two runs lists apart by their filters, trailing slash or not', () => { + expect(resolvePreviewTab('/runs/?status=failure')).toEqual({ kind: 'pagelist', path: '/runs' }) + expect(showsView('/runs/?schedule_path=a', '/runs/?schedule_path=b')).toBe(false) + expect(showsView('/runs?schedule_path=a', '/runs/?schedule_path=a')).toBe(true) + expect(showsView('/runs/f/a/b?status=failure', '/runs/f/a/b')).toBe(false) }) it('mounts the list page of a page item kind in process, whatever its filters', () => { diff --git a/frontend/src/lib/components/sessions/previewRouter.ts b/frontend/src/lib/components/sessions/previewRouter.ts index 6614adfe80..6417903f94 100644 --- a/frontend/src/lib/components/sessions/previewRouter.ts +++ b/frontend/src/lib/components/sessions/previewRouter.ts @@ -1,22 +1,24 @@ import { ASSETS_PATH, AUDIT_LOGS_PATH, + isPageKey, FOLDERS_PATH, GROUPS_PATH, - isPageItemListPath, + isPreviewListPath, + isRunsListPath, pageItemForListPath, pageItemListPath, pageItemPageHref, pageItemUrl, pageKey, - pageHref, parsePageItemRoute, + parsePipelineRoute, parseHistoricalScriptEdit, parsePreviewItemRoute, RESOURCES_PATH, RUNS_PATH, SCHEDULES_PATH, - stripBase, + barePath, VARIABLES_PATH, WORKSPACE_SETTINGS_PATH, triggerLabelForPath, @@ -26,17 +28,20 @@ import { type PreviewItemRoute, type TriggerKind } from './previewPaths' +import type { UserExt, UserWorkspace } from '$lib/stores' +import { sidebarPageAllowed, type OperatorPageKey } from '../sidebar/operatorRoutes' // Re-exported so the preview code that already reads locations through this module keeps // one import, while a caller needing only a path can reach for the leaf instead. export { + isPageKey, pageItemListPath, pageItemUrl, pageKey, - pageHref, parseHistoricalScriptEdit, parsePageItemRoute, + parsePipelineRoute, parsePreviewItemRoute, - stripBase, + barePath, TRIGGER_PAGES, type PageItemRef, type PreviewItemMode, @@ -63,7 +68,6 @@ import { buildVariablesFilterSchema } from '$lib/components/variables/variablesF import { buildResourcesFilterSchema } from '$lib/components/resources/resourcesFilter' import { buildAssetsFilterSchema } from '$lib/components/assets/assetsFilter' import { COMPARE_ITEMS_PARAM } from './modifiedItemsMask' -import { normalizePipelineFolder } from '$lib/utils/pipelineFolder' import type { WorkspaceItem } from '$lib/components/workspacePicker' import type { SessionTargetKind } from './sessionRuntime.svelte' @@ -84,7 +88,19 @@ export type PreviewTarget = // caller that predates the View side keeps opening the editor. `version` pins the // View side to one deployed version, in the query so the tab's identity stays the // item's path rather than becoming the version's own hash. - | { type: 'item'; item: WorkspaceItem; mode?: PreviewItemMode; version?: string } + // `pendingRunId` hands this tab a chat tool call parked on a run form: the deployed page + // shows that form, and Run there answers the call instead of starting a job of its own. + // In the query for the same reason as `version` — the tab stays the item's, and the call + // is a property of this tab rather than of the item. The id alone: what the call proposed + // is read off the chat, since a tab's url is persisted with the session and those + // arguments can hold file bytes and secrets typed into the form. + | { + type: 'item' + item: WorkspaceItem + mode?: PreviewItemMode + version?: string + pendingRunId?: string + } | { type: 'artifact'; id: string; name: string; version?: ArtifactVersionTarget } | { type: 'runform'; toolCallId: string; label: string } | { type: 'pageitem'; ref: PageItemRef } @@ -102,22 +118,40 @@ export function previewModeFor(item: Pick<WorkspaceItem, 'draftOnly'>): PreviewI return item.draftOnly ? 'edit' : 'view' } -export type PreviewPage = { label: string; path: string; icon: DrillIcon } +export type PreviewPage = { + label: string + path: string + icon: DrillIcon + /** The `operator_settings` key that admits an operator, as the sidebar reads it. */ + operatorKey?: OperatorPageKey + adminOnly?: boolean +} + +/** Whether `page` loads for `user` rather than showing its "not available" state. An unknown + * user is let through to every page but the admin-only ones. */ +export function previewPageAllowed( + page: PreviewPage, + user: Pick<UserExt, 'operator' | 'is_admin' | 'is_super_admin'> | undefined, + workspace: UserWorkspace | undefined +): boolean { + if (page.adminOnly) return !!user && (user.is_admin || user.is_super_admin) + return !page.operatorKey || sidebarPageAllowed(user?.operator, workspace, page.operatorKey) +} // Core workspace-level destinations the preview can route to. Intentionally // curated — the main pages, not every trigger sub-page (those live behind // EE/feature gating in SidebarContent and aren't worth duplicating here). export const PREVIEW_PAGES: PreviewPage[] = [ { label: 'Home', path: '/', icon: Home }, - { label: 'Runs', path: RUNS_PATH, icon: Play }, - { label: 'Variables', path: VARIABLES_PATH, icon: DollarSign }, - { label: 'Resources', path: RESOURCES_PATH, icon: Boxes }, - { label: 'Schedules', path: SCHEDULES_PATH, icon: Calendar }, - { label: 'Assets', path: ASSETS_PATH, icon: Database }, - { label: 'Folders', path: FOLDERS_PATH, icon: FolderOpen }, - { label: 'Groups', path: GROUPS_PATH, icon: Users }, - { label: 'Workspace settings', path: WORKSPACE_SETTINGS_PATH, icon: Settings }, - { label: 'Audit logs', path: AUDIT_LOGS_PATH, icon: ScrollText } + { label: 'Runs', path: RUNS_PATH, icon: Play, operatorKey: 'runs' }, + { label: 'Variables', path: VARIABLES_PATH, icon: DollarSign, operatorKey: 'variables' }, + { label: 'Resources', path: RESOURCES_PATH, icon: Boxes, operatorKey: 'resources' }, + { label: 'Schedules', path: SCHEDULES_PATH, icon: Calendar, operatorKey: 'schedules' }, + { label: 'Assets', path: ASSETS_PATH, icon: Database, operatorKey: 'assets' }, + { label: 'Folders', path: FOLDERS_PATH, icon: FolderOpen, operatorKey: 'folders' }, + { label: 'Groups', path: GROUPS_PATH, icon: Users, operatorKey: 'groups' }, + { label: 'Workspace settings', path: WORKSPACE_SETTINGS_PATH, icon: Settings, adminOnly: true }, + { label: 'Audit logs', path: AUDIT_LOGS_PATH, icon: ScrollText, operatorKey: 'audit_logs' } ] // The Compare & Deploy review page. Kept out of PREVIEW_PAGES (it's not a picker @@ -142,7 +176,7 @@ const DRAWER_ANCHOR_PAGES = [SCHEDULES_PATH, VARIABLES_PATH, RESOURCES_PATH] as export function drawerAnchorFor(location: string): string | undefined { const hashAt = location.indexOf('#') if (hashAt < 0) return undefined - const route = stripBase(location) + const route = barePath(location) const known = (DRAWER_ANCHOR_PAGES as readonly string[]).includes(route) || Object.values(TRIGGER_PAGES).some((p) => p.path === route) @@ -228,9 +262,14 @@ function pageRequestParamTable(): Record<string, readonly string[]> { }) } +// The page whose filters a path takes: one item's runs filter as every run does. +function filterPageOf(path: string): string { + return isRunsListPath(path) ? RUNS_PATH : path +} + /** The query params a request can set on `path` — empty for a page that takes none. */ export function pageRequestParams(path: string): readonly string[] { - return pageRequestParamTable()[stripBase(path)] ?? [] + return pageRequestParamTable()[filterPageOf(barePath(path))] ?? [] } /** What a preview location means, read against the page it points at. */ @@ -262,12 +301,12 @@ export function describeLocation(loc: string): PreviewLocation { return { identity: `/scripts/edit/${historical.path}@${historical.hash}`, view: '', anchor: '' } } const canonical = canonicalizeObservedLoc(loc) - const path = stripBase(canonical) + const path = barePath(canonical) const bare = canonical.split('#')[0] const query = bare.includes('?') ? bare.slice(bare.indexOf('?') + 1) : '' return { identity: path, - view: requestedParams(query, pageRequestParamTable()[path]), + view: requestedParams(query, pageRequestParamTable()[filterPageOf(path)]), anchor: drawerAnchorFor(canonical) ?? '' } } @@ -300,7 +339,7 @@ export function showsView(observed: string, commanded: string): boolean { const y = describeLocation(commanded) if (x.identity !== y.identity || x.anchor !== y.anchor) return false if (x.view === y.view) return true - const seeded = PAGE_SEEDED_PARAMS[x.identity] + const seeded = PAGE_SEEDED_PARAMS[filterPageOf(x.identity)] if (!seeded?.length) return false // Both views come out of `requestedParams` already sorted and encoded, so they compare // as strings once the seeded params are dropped. One direction only: the page may add @@ -414,10 +453,10 @@ export function previewLocationContext(loc: string): { } } -// Match a base-stripped preview pathname to a known page, for breadcrumb +// Match a preview pathname to a known page, for breadcrumb // labelling + picker highlight. Exact match; '/' only matches home. export function matchPreviewPage(path: string): PreviewPage | undefined { - const clean = stripBase(path) + const clean = barePath(path) return PREVIEW_PAGES.find((p) => p.path === clean) } @@ -427,7 +466,7 @@ export function matchPreviewPage(path: string): PreviewPage | undefined { * matched — they take the generic path in `SessionPreviewTabs.open`, which * dedupes on the location ignoring the hash and re-points the tab it finds. */ export function matchReusablePage(href: string): PreviewPage | undefined { - if (stripBase(href) === COMPARE_PAGE.path) return COMPARE_PAGE + if (barePath(href) === COMPARE_PAGE.path) return COMPARE_PAGE return matchPreviewPage(href) } @@ -445,11 +484,11 @@ export function previewLocationLabel(url: string): string { if (page) return page.label const trigger = triggerLabelForPath(url) if (trigger) return trigger - const run = stripBase(url).match(/^\/run\/([^/?#]+)/) + const run = parseRunRoute(url) // Job ids are time-ordered, so runs started moments apart share their head. - if (run) return `Run ${decodeURIComponent(run[1]).slice(-8)}` + if (run) return `Run ${run.jobId.slice(-8)}` // The runs of one item, as a detail page's Runs button links them. - const itemRuns = stripBase(url).match(/^\/runs\/(.+)$/) + const itemRuns = barePath(url).match(/^\/runs\/(.+)$/) if (itemRuns) return `Runs · ${decodeURIComponent(itemRuns[1]).split('/').pop()}` const pipelineFolder = parsePipelineRoute(url) if (pipelineFolder) return pipelineFolder @@ -457,7 +496,7 @@ export function previewLocationLabel(url: string): string { if (historical) return `${historical.path.split('/').pop()} @ ${historical.hash.slice(0, 8)}` const parsed = parsePreviewItemRoute(url) if (parsed) return parsed.itemPath.split('/').pop() ?? parsed.itemPath - return stripBase(url) + return barePath(url) } /** The friendly display leaf for a preview tab, or `undefined` to fall back to @@ -502,14 +541,6 @@ export function parsePreviewSelectedId(url: string): string | undefined { } } -// A `/pipeline/<folder>` route is the data-pipeline graph editor for that folder -// (the folder is a single path segment, not a workspace item path). The bare -// `/pipeline` list page is not an editor. Returns the folder name, or null. -export function parsePipelineRoute(fullPath: string): string | null { - const m = stripBase(fullPath).match(/^\/pipeline\/([^/?#]+)/) - return m ? normalizePipelineFolder(decodeURIComponent(m[1])) : null -} - // The id (before the query) is the artifact's stable routing identity; the name rides in the // hash so the tab strip labels it without a store lookup, and the version in the query so the // tab persists it. @@ -539,6 +570,34 @@ export function parseRunFormRoute(url: string): { toolCallId: string; label: str } } +/** The chat tool call a viewer tab was opened to answer, read off the tab's url. A deployed + * page tab is still the item's tab — only the call rides in its query — so this is how a tab + * says which call it is carrying, and re-pointing it anywhere drops the answer. */ +export function pendingRunIdOf(url: string): string | undefined { + const slot = resolvePreviewTab(url) + if (slot.kind !== 'viewer') return undefined + return new URL(url, 'http://x').searchParams.get('pending_run') ?? undefined +} + +/** The run a `/run/<id>` location shows, in the workspace its query names (the opener's, + * when it names none). */ +export function parseRunRoute( + url: string +): { jobId: string; workspace?: string; viewToken: boolean } | null { + const m = barePath(url).match(/^\/run\/([^/?#]+)$/) + if (!m) return null + try { + const query = new URL(url, 'http://_').searchParams + return { + jobId: decodeURIComponent(m[1]), + workspace: query.get('workspace') || undefined, + viewToken: query.has('view_token') + } + } catch { + return null + } +} + export function runFormUrl(toolCallId: string, label: string): string { return `runform:${encodeURIComponent(toolCallId)}#${encodeURIComponent(label)}` } @@ -562,9 +621,10 @@ export const isArtifactKey = (key: string) => key.startsWith('artifact:') // How a preview tab should render: as an in-process live editor, the deployed // item's view page, or an iframe fallback. An item of a wrappable kind (script, // flow, raw app) mounts its per-(kind,path) cell editor on `/edit/` and its viewer -// on `/get/`; a `/pipeline/<folder>` route mounts the data-pipeline graph editor -// (single, shared runtime.pipelineEditorState — `path` is the folder); the list page -// of a page item kind mounts that list; everything +// on `/get/`; a `/pipeline/<folder>` route mounts the data-pipeline graph editor of +// that folder (`path` is the folder); the list page of a page item kind mounts that +// list, and so does the runs list; a `/run/<id>` route without a share token mounts that +// run's page; everything // else (static pages, regular drag-and-drop apps, any other route) stays an iframe. export type PreviewSlot = | { kind: 'editor'; editorKind: SessionTargetKind | 'pipeline'; path: string } @@ -573,8 +633,21 @@ export type PreviewSlot = | { kind: 'runform'; toolCallId: string } | { kind: 'pageitem'; ref: PageItemRef } | { kind: 'pagelist'; path: string } + | { kind: 'run'; jobId: string; workspace?: string } | { kind: 'iframe' } +/** Whether a tab on this slot shows a page, framed or mounted in process, and so has a + * location to stamp as the chat's ACTIVE PREVIEW. Editors register as the ACTIVE EDITOR. */ +export function slotShowsPage(kind: PreviewSlot['kind']): boolean { + return ( + kind === 'iframe' || + kind === 'pageitem' || + kind === 'pagelist' || + kind === 'run' || + kind === 'viewer' + ) +} + export function resolvePreviewTab(url: string): PreviewSlot { const artifact = parseArtifactRoute(url) if (artifact) return { kind: 'artifact', id: artifact.id, version: artifact.version } @@ -582,8 +655,14 @@ export function resolvePreviewTab(url: string): PreviewSlot { if (runForm) return { kind: 'runform', toolCallId: runForm.toolCallId } const pageItem = parsePageItemRoute(url) if (pageItem) return { kind: 'pageitem', ref: pageItem } - const route = stripBase(url) - if (isPageItemListPath(route)) return { kind: 'pagelist', path: route } + const route = barePath(url) + if (isPreviewListPath(route)) return { kind: 'pagelist', path: route } + const run = parseRunRoute(url) + // A share link's token authorizes every request of the window that installs it, so a run + // opened through one keeps a frame of its own rather than lending the token to the session. + if (run && !run.viewToken) { + return { kind: 'run', jobId: run.jobId, ...(run.workspace && { workspace: run.workspace }) } + } const pipelineFolder = parsePipelineRoute(url) if (pipelineFolder) { return { kind: 'editor', editorKind: 'pipeline', path: pipelineFolder } @@ -617,6 +696,7 @@ export function workspacePageHref(location: string): string | undefined { case 'editor': case 'viewer': case 'pagelist': + case 'run': case 'iframe': return location default: { diff --git a/frontend/src/lib/components/sessions/sessionDeployModel.svelte.ts b/frontend/src/lib/components/sessions/sessionDeployModel.svelte.ts index 981b4cc752..4ade5552bf 100644 --- a/frontend/src/lib/components/sessions/sessionDeployModel.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionDeployModel.svelte.ts @@ -1,6 +1,10 @@ import { getDraftItems, type DraftItem } from '$lib/workspaceDrafts.svelte' +import { get } from 'svelte/store' +import { userWorkspaces } from '$lib/stores' +import { roleCanAuthor } from '$lib/editRights' import { checkDeployPermission, + checkDeployRules, checkItemExists, deployPermissionForKind, getItemValue, @@ -27,6 +31,8 @@ import { import { maskKey } from './modifiedItemsMask' import { sessionState } from './sessionState.svelte' import { logFeatureUsage } from '$lib/utils/featureUsage' +import { AssetService } from '$lib/gen' +import { PIPELINE_DRAFT_KIND, pipelineFolderFromBundlePath } from '$lib/pipelinePaths' export type DeploymentStatus = { status: 'loading' | 'failed'; error?: string } @@ -52,6 +58,9 @@ export interface SessionDeployModelArgs { onItemDiscarded?: (item: DeployItem) => void /** Chat-modified-items mask; undefined shows every draft. */ mask?: Set<string> + /** Deploys a pipeline folder's draft bundle, which no per-item deploy can: it + * expands into the folder's scripts and triggers. */ + deployPipeline?: (folder: string) => Promise<DeployResult> } export interface DiffValues { @@ -59,6 +68,15 @@ export interface DiffValues { after: unknown } +// A pipeline has no row of its own: it exists while its folder holds pipeline scripts. +async function itemExists(kind: Kind, path: string, workspace: string): Promise<boolean> { + if (kind !== PIPELINE_DRAFT_KIND) return checkItemExists(kind, path, workspace) + const folder = pipelineFolderFromBundlePath(path) + if (!folder) return false + const pipelines = await AssetService.listPipelineFolders({ workspace }) + return pipelines.some((p) => p.folder === folder) +} + /** Resolves which mask-only candidates still exist in the session workspace * (deployed) vs are gone (discarded drafts / deleted items) — the * `existingKeys` input of `buildDeployItems`. Undefined while resolving, so @@ -100,7 +118,7 @@ export function useExistingMaskKeys( // workspace; a discarded or deleted one doesn't. void Promise.all( cands.map((c) => - checkItemExists(c.deployKind, c.path, workspaceId) + itemExists(c.deployKind, c.path, workspaceId) .then((exists) => (exists ? c.key : null)) .catch(() => null) ) @@ -214,6 +232,9 @@ export function useSessionDeployModel(getArgs: () => SessionDeployModelArgs) { // button disables with a reason instead of failing on click. `ok` defaults // true while resolving (fail-open). let deployPerm = $state<DeployPermission>({ ok: true }) + // `checkDeployPermission` refuses every operator, but flows.rs and apps.rs let one with the + // workspace's matching builder right deploy that kind, under the rules alone. + let builder = $state<{ perm: DeployPermission; kinds: Kind[] } | undefined>(undefined) let deployPermFetchedFor = '' $effect(() => { const ws = getArgs().workspaceId @@ -223,12 +244,27 @@ export function useSessionDeployModel(getArgs: () => SessionDeployModelArgs) { // Reset to fail-open for the new workspace and drop a stale resolution // (a slower fetch for the previous workspace must not gate this one). deployPerm = { ok: true } - void checkDeployPermission(ws).then((perm) => { - if (deployPermFetchedFor === ws) deployPerm = perm + builder = undefined + void checkDeployPermission(ws).then(async (perm) => { + if (deployPermFetchedFor !== ws) return + deployPerm = perm + const settings = get(userWorkspaces).find((w) => w.id === ws)?.operator_settings + const kinds = (['flow', 'raw_app'] as const).filter((k) => + roleCanAuthor(k, { operator: true }, settings) + ) + if (perm.refusedBy === 'operator' && kinds.length) { + const rules = await checkDeployRules(ws) + if (deployPermFetchedFor === ws) builder = { perm: rules, kinds } + } }) }) }) + function permissionFor(kind: Kind): DeployPermission { + if (builder?.kinds.includes(kind)) return deployPermissionForKind(builder.perm, kind) + return deployPermissionForKind(deployPerm, kind) + } + // ── Deploy execution ───────────────────────────────────────────────────── // Per-item transient deploy state (keyed by DeployItem.key): loading or // failed. Success has no status — the row's badge flipping to Deployed is @@ -246,11 +282,18 @@ export function useSessionDeployModel(getArgs: () => SessionDeployModelArgs) { async function runPlan(entry: DeployPlanEntry): Promise<DeployResult> { const cur = getArgs().workspaceId switch (entry.op) { - case 'deploy_draft': + case 'deploy_draft': { + const folder = + entry.draftKind === PIPELINE_DRAFT_KIND + ? pipelineFolderFromBundlePath(entry.path) + : undefined + const deployPipeline = getArgs().deployPipeline + if (folder && deployPipeline) return deployPipeline(folder) return deployDraft(entry.draftKind, entry.path, cur, { draftOnly: entry.draftOnly, rawApp: entry.rawApp }) + } case 'discard': return discardDraft(entry.draftKind, entry.path, cur, entry.draftOnly, entry.legacy) } @@ -271,8 +314,7 @@ export function useSessionDeployModel(getArgs: () => SessionDeployModelArgs) { // Don't attempt a deploy we know the user can't make (no write permission on // the path, or refused by the preflight for this kind) — the UI disables it // too; this is the guard behind that. - if (!discard && (!item.canWrite || !deployPermissionForKind(deployPerm, item.deployKind).ok)) - return false + if (!discard && (!item.canWrite || !permissionFor(item.deployKind).ok)) return false setStatus(item.key, { status: 'loading' }) deploying = true try { @@ -314,6 +356,16 @@ export function useSessionDeployModel(getArgs: () => SessionDeployModelArgs) { // ── Diff values (one resolver for tree + column) ───────────────────────── async function loadDiffValues(item: DeployItem): Promise<DiffValues> { + const pipelineFolder = + item.draftKind === PIPELINE_DRAFT_KIND ? pipelineFolderFromBundlePath(item.path) : undefined + if (pipelineFolder) { + // Dynamic: the pipeline deploy module reaches every trigger kind's save utils. + const { loadPipelineDraftDiff } = await import( + '$lib/components/assets/AssetGraph/pipelineDeploy.svelte' + ) + if (item.hasDraft) return loadPipelineDraftDiff(getArgs().workspaceId, pipelineFolder) + return { before: undefined, after: undefined } + } const base = diffBaseFor(item, getArgs().workspaceId) if (base.kind === 'draft') { const { deployed, draft } = await getDraftDiffValues( @@ -358,7 +410,7 @@ export function useSessionDeployModel(getArgs: () => SessionDeployModelArgs) { * that kind stays deployable while a script row does not. */ deployPermissionForKind(kind: Kind): DeployPermission { - return deployPermissionForKind(deployPerm, kind) + return permissionFor(kind) }, deployRow, discardRow diff --git a/frontend/src/lib/components/sessions/sessionDeployModel.test.ts b/frontend/src/lib/components/sessions/sessionDeployModel.test.ts index 7fa4e3cca8..ee2a4115da 100644 --- a/frontend/src/lib/components/sessions/sessionDeployModel.test.ts +++ b/frontend/src/lib/components/sessions/sessionDeployModel.test.ts @@ -101,6 +101,15 @@ describe('buildDeployItems', () => { expect(items[0].hasDraft).toBe(true) }) + it("a pipeline's deployed scripts fold into its one row", () => { + const bundle = maskKey('data_pipeline', 'f/crm/data_pipeline') + const node = maskKey('script', 'f/crm/clean') + const mask = new Set([bundle, node]) + const items = buildDeployItems({ draftItems: [], mask, existingKeys: new Set([bundle, node]) }) + expect(items.map((i) => i.key)).toEqual([bundle]) + expect(maskOnlyCandidates({ draftItems: [], mask }).map((c) => c.key)).toEqual([bundle]) + }) + it('maskOnlyCandidates returns keys not covered by a draft', () => { const cands = maskOnlyCandidates({ draftItems: [draft('script', 'u/a/draft')], diff --git a/frontend/src/lib/components/sessions/sessionDeployModel.ts b/frontend/src/lib/components/sessions/sessionDeployModel.ts index d38de06c86..4933f3a64a 100644 --- a/frontend/src/lib/components/sessions/sessionDeployModel.ts +++ b/frontend/src/lib/components/sessions/sessionDeployModel.ts @@ -1,7 +1,7 @@ import type { UserDraftItemKind } from '$lib/gen' import type { DraftItem } from '$lib/workspaceDrafts.svelte' import type { Kind } from '$lib/utils_deployable' -import { maskKey } from './modifiedItemsMask' +import { foldedIntoPipelineRow, maskKey } from './modifiedItemsMask' // Unified item model for the session Review & Deploy surface. This is the pure, // UI-free core: every item the session touched is either a pending **draft** or @@ -128,6 +128,7 @@ export function buildDeployItems(input: BuildInput): DeployItem[] { if (sep < 0) continue const udk = k.slice(0, sep) as UserDraftItemKind const path = k.slice(sep + 1) + if (foldedIntoPipelineRow(mask, udk, path)) continue seen.add(k) out.push({ key: k, @@ -172,6 +173,7 @@ export function maskOnlyCandidates( if (sep < 0) continue const udk = k.slice(0, sep) as UserDraftItemKind const path = k.slice(sep + 1) + if (foldedIntoPipelineRow(mask, udk, path)) continue out.push({ key: k, draftKind: udk, deployKind: deployKindOf(udk, udk === 'raw_app'), path }) } return out diff --git a/frontend/src/lib/components/sessions/sessionMirror.svelte.ts b/frontend/src/lib/components/sessions/sessionMirror.svelte.ts index f30d66ca45..657f120e98 100644 --- a/frontend/src/lib/components/sessions/sessionMirror.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionMirror.svelte.ts @@ -998,9 +998,23 @@ async function flush(): Promise<void> { let settledAny = false let leftForNext = false for (const [ws, w] of work) { - const out = await pushWorkspace(ws, w, email) - if (out.status === 'abort') return - if (out.status === 'off') { + // A push carries whole transcripts, and a workspace that keeps no backups is + // asked again on every page load: one this page has not heard from yet is asked + // with the listing first, which costs nothing to refuse. + let probe: 'on' | 'off' | 'failed' = 'on' + if (!wsState.has(ws)) { + const listing = await fetchListing(ws) + if (getCurrentUserEmail() !== email) return + probe = listing === 'off' || listing === 'failed' ? listing : 'on' + if (probe === 'on') wsState.set(ws, 'on') + } + if (probe === 'failed') { + backOff() + continue + } + const out = probe === 'off' ? undefined : await pushWorkspace(ws, w, email) + if (out?.status === 'abort') return + if (!out || out.status === 'off') { markOff(ws) await staleWorkspaceSync(ws, email) // Same rule as the loop above: a removal is worth keeping only for a session @@ -1189,22 +1203,28 @@ function unpackBackup( type BackupListing = Awaited<ReturnType<typeof AiService.listAiSessionBackups>> -/** The workspace's listing; `off` when it keeps no backups, `failed` when it could not be - * listed this time. */ -async function listWorkspace(ws: string, email: string): Promise<BackupListing | 'off' | 'failed'> { +/** The workspace's listing as the server answers it; `off` when it keeps no backups, + * `failed` when it could not be listed this time. */ +async function fetchListing(ws: string): Promise<BackupListing | 'off' | 'failed'> { let listing try { listing = await AiService.listAiSessionBackups({ workspace: ws }) } catch (e) { const status = statusOf(e) - if (status === 404 || status === 403) { - markOff(ws) - return 'off' - } + // 404: a build without object storage, or a storage whose resource is gone. + // 403: nothing this token may back up. + if (status === 404 || status === 403) return 'off' console.warn('Could not list session backups', e) return 'failed' } - if (!listing.enabled) { + return listing.enabled ? listing : 'off' +} + +/** `fetchListing`, with what it says of the workspace recorded for the page. */ +async function listWorkspace(ws: string, email: string): Promise<BackupListing | 'off' | 'failed'> { + const listing = await fetchListing(ws) + if (listing === 'failed') return 'failed' + if (listing === 'off') { markOff(ws) return 'off' } diff --git a/frontend/src/lib/components/sessions/sessionMirror.test.ts b/frontend/src/lib/components/sessions/sessionMirror.test.ts index 55a1acc138..9a8a211ded 100644 --- a/frontend/src/lib/components/sessions/sessionMirror.test.ts +++ b/frontend/src/lib/components/sessions/sessionMirror.test.ts @@ -150,6 +150,7 @@ beforeEach(async () => { __resetMirrorForTesting() pushMock.mockReset() listMock.mockReset() + listMock.mockResolvedValue({ enabled: true, sessions: [] }) pullMock.mockReset() chatImport.unavailable = false chatImport.pruneFails = false @@ -316,6 +317,30 @@ describe('sessionMirror flush', () => { expect((await __syncRowsForTesting(EMAIL)).some((r) => r.id === 'sr')).toBe(false) }) + it('asks a workspace it has not heard from before sending it a transcript', async () => { + const s: Session = { id: 'sp', name: 'session-1', createdAt: 1, workspace_id: 'ws' } + sessionState.sessions = [s] + await putSession(s) + const { ApiError } = await import('$lib/gen') + listMock.mockRejectedValueOnce( + new ApiError({ method: 'GET', url: '' } as never, { status: 404 } as never, 'no resource') + ) + await __flushForTesting() + expect(listMock).toHaveBeenCalledTimes(1) + expect(pushMock).not.toHaveBeenCalled() + expect(await pendingDirty()).toEqual(['sp']) + + // A page that heard the workspace keeps backups pushes without asking again. + __resetMirrorForTesting() + pushMock.mockResolvedValue({ enabled: true, results: [{ id: 'sp' }] }) + await __flushForTesting() + await putSession({ ...s, summary: 'changed' }) + await __flushForTesting() + expect(listMock).toHaveBeenCalledTimes(2) + expect(pushMock).toHaveBeenCalledTimes(2) + expect(await pendingDirty()).toEqual([]) + }) + it('keeps the marks when the push fails, and stops for a workspace without storage', async () => { const s: Session = { id: 's2', name: 'session-2', createdAt: 1, workspace_id: 'ws' } const never: Session = { id: 's2b', name: 'session-3', createdAt: 2, workspace_id: 'ws' } @@ -355,11 +380,11 @@ describe('sessionMirror flush', () => { // Backups an admin turns on again elsewhere are noticed once the page's memory of // them being off expires, with nothing else prompting it: the removal goes then. - listMock.mockResolvedValue({ enabled: true, sessions: [] }) + listMock.mockClear() pushMock.mockResolvedValueOnce({ enabled: true, results: [{ id: 's2' }] }) await vi.waitFor(() => expect(pushMock).toHaveBeenCalledTimes(4), { timeout: 3000 }) expect(pushMock.mock.calls[3][0].requestBody.removed).toEqual(['s2']) - await vi.waitFor(() => expect(listMock).toHaveBeenCalledTimes(1)) + await vi.waitFor(() => expect(listMock).toHaveBeenCalled()) await __settleForTesting() expect(pendingKeys()).toEqual([]) }) @@ -426,7 +451,7 @@ describe('sessionMirror flush', () => { await __flushForTesting() expect(pushMock).toHaveBeenCalledTimes(2) - listMock.mockResolvedValue({ enabled: true, sessions: [] }) + listMock.mockClear() pushMock.mockResolvedValueOnce({ enabled: true, results: [{ id: 'so' }] }) usersWorkspaceStore.set({ email: EMAIL, workspaces: [] } as never) backupSettingsChanged('ws') diff --git a/frontend/src/lib/components/sessions/sessionMode.svelte.ts b/frontend/src/lib/components/sessions/sessionMode.svelte.ts index 294cca19fb..c6aea96a67 100644 --- a/frontend/src/lib/components/sessions/sessionMode.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionMode.svelte.ts @@ -1,9 +1,12 @@ -import { base } from '$app/paths' import type { SessionTarget } from './sessionState.svelte' +import { normalizePipelineFolder } from '$lib/utils/pipelineFolder' // Maps a session's editor target to the canonical full-page Windmill route. export function sessionTargetHref(target: SessionTarget | undefined): string | undefined { if (!target) return undefined + if (target.kind === 'pipeline') { + return `/pipeline/${encodeURIComponent(normalizePipelineFolder(target.path))}` + } const seg = target.kind === 'script' ? 'scripts/edit' @@ -13,12 +16,12 @@ export function sessionTargetHref(target: SessionTarget | undefined): string | u ? 'apps_raw/edit' : undefined if (!seg) return undefined - return `${base}/${seg}/${target.path}` + return `/${seg}/${target.path}` } // Point a preview tab's URL at a place inside the previewed editor (the flow // step to select). The params are not part of the item's identity — every tab -// resolver strips the query (see previewRouter's stripBase) — so they only ever +// resolver strips the query (see previewRouter's barePath) — so they only ever // steer where the editor opens. No-op without params. export function withPreviewParams( url: string | undefined, diff --git a/frontend/src/lib/components/sessions/sessionMode.test.ts b/frontend/src/lib/components/sessions/sessionMode.test.ts index 9bc67b9a58..75d3445fed 100644 --- a/frontend/src/lib/components/sessions/sessionMode.test.ts +++ b/frontend/src/lib/components/sessions/sessionMode.test.ts @@ -13,9 +13,13 @@ describe('sessionTargetHref', () => { expect(sessionTargetHref({ kind: 'raw_app', path: 'u/me/app' })).toBe('/apps_raw/edit/u/me/app') }) - it('returns undefined for no target or a kind without a full-page route', () => { + it('maps a pipeline to its folder page, whichever form the folder is given in', () => { + expect(sessionTargetHref({ kind: 'pipeline', path: 'crm' })).toBe('/pipeline/crm') + expect(sessionTargetHref({ kind: 'pipeline', path: 'f/crm' })).toBe('/pipeline/crm') + }) + + it('returns undefined for no target', () => { expect(sessionTargetHref(undefined)).toBeUndefined() - expect(sessionTargetHref({ kind: 'pipeline', path: 'u/me/pipe' })).toBeUndefined() }) }) diff --git a/frontend/src/lib/components/sessions/sessionPermissions.svelte.ts b/frontend/src/lib/components/sessions/sessionPermissions.svelte.ts new file mode 100644 index 0000000000..caceb2e623 --- /dev/null +++ b/frontend/src/lib/components/sessions/sessionPermissions.svelte.ts @@ -0,0 +1,31 @@ +import { fromStore } from 'svelte/store' +import { userWorkspaces } from '$lib/stores' +import { useActingUser } from '$lib/actingUser.svelte' +import { useEditRights } from '$lib/operatorWriteRights' +import type { WorkspaceItem } from '$lib/components/workspacePicker' +import { previewPageAllowed, type PreviewPage } from './previewRouter' + +/** + * What the session UI may offer in `workspace`. Its editors save drafts, so it reads + * `roleCanDraft` / `canDraftItem` — the rule the chat's draft tools and `open_preview` follow — so + * a control and the tool behind it never disagree. An unknown user reads as able to draft, as the toolset does before access + * resolves: hiding every editor from a developer while `whoami` is in flight is the worse + * mistake, and the server refuses an operator anyway. Reads context and registers an effect: + * call during component initialisation. + */ +export function useSessionPermissions(workspace: () => string | undefined) { + const rights = useEditRights(workspace) + const user = useActingUser(workspace) + const workspaces = fromStore(userWorkspaces) + const entry = $derived(workspaces.current.find((w) => w.id === workspace())) + + return { + /** Whether this user can save the drafts the `kind` editor writes. */ + canOpenEditor: (kind: string) => rights.roleCanDraft(kind), + /** The same, and this item's own permissions let them write it. */ + canEditItem: (item: Pick<WorkspaceItem, 'kind' | 'raw_app' | 'path' | 'extraPerms'>) => + rights.canDraftItem(item.raw_app ? 'raw_app' : item.kind, item.path, item.extraPerms), + /** Whether the page loads for this user rather than refusing them. */ + pageAllowed: (page: PreviewPage) => previewPageAllowed(page, user.current, entry) + } +} diff --git a/frontend/src/lib/components/sessions/sessionPreviewTabs.svelte.ts b/frontend/src/lib/components/sessions/sessionPreviewTabs.svelte.ts index 1104e1c4b3..ee13729d4d 100644 --- a/frontend/src/lib/components/sessions/sessionPreviewTabs.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionPreviewTabs.svelte.ts @@ -1,4 +1,3 @@ -import { base } from '$lib/base' import { randomUUID } from '$lib/utils/uuid' import { editPathFor, viewPathFor, type WorkspaceItem } from '$lib/components/workspacePicker' import { normalizePipelineFolder } from '$lib/utils/pipelineFolder' @@ -20,7 +19,7 @@ import { previewLocationLabel, resolvePreviewTab, runFormUrl, - stripBase, + barePath, type ArtifactVersionTarget, type PreviewItemMode, type PreviewTarget @@ -113,11 +112,17 @@ function targetUrl(target: PreviewTarget, onto?: SessionPreviewTab): string { // A re-point with no mode keeps the side the tab is already on, so an AI write to // an item the user left on View does not yank them back to the editor. const mode = target.mode ?? (onto ? (parsePreviewItemRoute(onto.url)?.mode ?? 'edit') : 'edit') - if (mode !== 'view') return `${base}${editPathFor(target.item)}` - // Not carried over from `onto`: a version pin is something the reader asked for - // once, so every other re-point of this tab lands on the current deployed version. - const pin = target.version ? `?version=${encodeURIComponent(target.version)}` : '' - return `${base}${viewPathFor(target.item)}${pin}` + if (mode !== 'view') return editPathFor(target.item) + // Neither is carried over from `onto`. A version pin is something the reader asked for + // once, so every other re-point of this tab lands on the current deployed version — and a + // chat tool call is carried by the tab that was opened for it, so re-pointing that tab + // anywhere else, a version included, hands the call back rather than running it against + // something it was not confirmed for. + const params = new URLSearchParams() + if (target.version) params.set('version', target.version) + if (target.pendingRunId) params.set('pending_run', target.pendingRunId) + const query = params.size > 0 ? `?${params}` : '' + return `${viewPathFor(target.item)}${query}` } // Point a tab at a new destination. Clears `friendlyLabel`/`friendlyPath` @@ -175,7 +180,7 @@ export function previewTargetForSessionTarget( ): PreviewTarget | undefined { if (kind === 'pipeline') { const folder = normalizePipelineFolder(path) - return { type: 'page', href: `${base}/pipeline/${encodeURIComponent(folder)}`, label: folder } + return { type: 'page', href: `/pipeline/${encodeURIComponent(folder)}`, label: folder } } const item: WorkspaceItem = kind === 'raw_app' @@ -455,20 +460,15 @@ export class SessionPreviewTabs { } } const url = targetUrl(target) - // Pipeline previews all share one runtime.pipelineEditorState, so keep at - // most one pipeline tab: re-point the existing one to the requested folder - // rather than opening a second pipeline editor that would fight over the - // shared state (`focused` when it already showed this folder, else `opened` - // since the view now shows a different pipeline). + // One tab per pipeline folder: two would mount two editors over one folder's + // state and draft. const pipelineFolder = parsePipelineRoute(url) if (pipelineFolder) { - const existing = this.#tabs.find((t) => parsePipelineRoute(t.url) !== null) + const existing = this.#tabs.find((t) => parsePipelineRoute(t.url) === pipelineFolder) if (existing) { - const same = existing.url === url - this.#retarget(existing, url) this.#activeId = existing.id this.#flush() - return { status: same ? 'focused' : 'opened' } + return { status: 'focused' } } } // Dedupe artifacts by id, not full url: an update may have changed the name the url carries. @@ -543,15 +543,11 @@ export class SessionPreviewTabs { return } } - // Keep at most one pipeline tab (all share runtime.pipelineEditorState): if a - // *different* tab already hosts a pipeline, retarget and focus it rather than - // turning the active tab into a second pipeline editor racing the shared - // state. Same invariant as open(); a no-op when the active tab is that tab. + // Same one-tab-per-folder rule as open(): focus the tab already on this folder. const pipelineFolder = parsePipelineRoute(targetUrl(target)) if (pipelineFolder) { - const existing = this.#tabs.find((x) => parsePipelineRoute(x.url) !== null) + const existing = this.#tabs.find((x) => parsePipelineRoute(x.url) === pipelineFolder) if (existing && existing.id !== t.id) { - this.#retarget(existing, targetUrl(target, existing)) this.#activeId = existing.id this.#flush() return @@ -696,6 +692,15 @@ export class SessionPreviewTabs { this.#flush() } + /** Point one known tab at `url`. For a caller that found the tab itself — the deployed + * page that confirmed a run becomes that run, and only the caller knows which page. */ + retargetById(id: string, url: string): void { + const tab = this.#tabs.find((t) => t.id === id) + if (!tab) return + retargetTab(tab, url) + this.#flush() + } + setCollapsed(collapsed: boolean): void { if (this.#collapsed === collapsed) return this.#collapsed = collapsed @@ -803,7 +808,7 @@ export function selectPreviewTabsToClose( // whose hash is app state, and any page can carry a filter value the user typed. function previewLocationDetail(where: string): string { const { location, open } = previewLocationContext(where) - const detail = [location === stripBase(where) ? undefined : location, open && `open: ${open}`] + const detail = [location === barePath(where) ? undefined : location, open && `open: ${open}`] .filter(Boolean) .join(', ') return detail ? ` (${detail})` : '' @@ -839,7 +844,7 @@ export function describePreview( ? `${route.raw_app ? 'raw_app' : route.kind} "${route.itemPath}"` : // Trigger list pages land here (they're outside PREVIEW_PAGES), and // their `#<path>` is the trigger the drawer has open. - `${stripBase(where)}${previewLocationDetail(where)}` + `${barePath(where)}${previewLocationDetail(where)}` const slotKind = resolvePreviewTab(t.url).kind const live = slotKind === 'editor' || slotKind === 'pageitem' diff --git a/frontend/src/lib/components/sessions/sessionPreviewTabs.test.ts b/frontend/src/lib/components/sessions/sessionPreviewTabs.test.ts index 994624511a..669e9fc594 100644 --- a/frontend/src/lib/components/sessions/sessionPreviewTabs.test.ts +++ b/frontend/src/lib/components/sessions/sessionPreviewTabs.test.ts @@ -11,7 +11,6 @@ import { } from './sessionPreviewTabs.svelte' import { artifactUrl, type PreviewTarget } from './previewRouter' import type { SessionPreviewTab } from './sessionState.svelte' -import { base } from '$lib/base' // In-memory adapter spy: records persisted snapshots, no IDB. function makeAdapter() { @@ -48,10 +47,10 @@ const dndAppTarget: PreviewTarget = { item: { kind: 'app', path: 'u/me/legacy', summary: '' } } const pageTarget: PreviewTarget = { type: 'page', href: '/runs', label: 'Runs' } -const pipelineTarget: PreviewTarget = { type: 'page', href: `${base}/pipeline/crm`, label: 'crm' } +const pipelineTarget: PreviewTarget = { type: 'page', href: '/pipeline/crm', label: 'crm' } const pipelineTarget2: PreviewTarget = { type: 'page', - href: `${base}/pipeline/sales`, + href: '/pipeline/sales', label: 'sales' } const artifactTarget: PreviewTarget = { type: 'artifact', id: 'art1', name: 'Plan' } @@ -149,7 +148,7 @@ describe('previewTargetForSessionTarget', () => { it('maps pipeline to its folder route page target', () => { expect(previewTargetForSessionTarget('pipeline', 'my_folder')).toEqual({ type: 'page', - href: `${base}/pipeline/my_folder`, + href: '/pipeline/my_folder', label: 'my_folder' }) }) @@ -159,7 +158,7 @@ describe('previewTargetForSessionTarget', () => { // path `f/f/<folder>/…`. expect(previewTargetForSessionTarget('pipeline', 'f/my_folder')).toEqual({ type: 'page', - href: `${base}/pipeline/my_folder`, + href: '/pipeline/my_folder', label: 'my_folder' }) }) @@ -252,7 +251,7 @@ describe('page item tabs', () => { { kind: 'raw_app', path: 'u/me/draft_1' }, { kind: 'raw_app', path: 'u/me/app' } ) - const url = `${base}/apps_raw/edit/u/me/app` + const url = '/apps_raw/edit/u/me/app' expect(o.tabs).toEqual([{ id, url, loc: url }]) }) @@ -454,7 +453,7 @@ describe('SessionPreviewTabs.open', () => { it('dedupes a run form by tool call, and hands that tab to the run in place', () => { const o = owner() - o.open({ type: 'page', href: `${base}/runs`, label: 'Runs' }) + o.open({ type: 'page', href: '/runs', label: 'Runs' }) o.open({ type: 'runform', toolCallId: 'call_1', label: 'Run refund' }) const id = o.tabs[1].id // The label carries the script's summary, which is not what identifies the call. @@ -462,10 +461,10 @@ describe('SessionPreviewTabs.open', () => { 'focused' ) expect(o.tabs).toHaveLength(2) - o.retargetRunForm('call_1', `${base}/run/01a0?workspace=w`) + o.retargetRunForm('call_1', '/run/01a0?workspace=w') // Still second: a tab that followed its call to the run has not moved in the strip. expect(o.tabs[1].id).toBe(id) - expect(o.tabs[1].url).toBe(`${base}/run/01a0?workspace=w`) + expect(o.tabs[1].url).toBe('/run/01a0?workspace=w') }) it('re-points the same tab (no duplicate) when the artifact was renamed', () => { @@ -578,19 +577,22 @@ describe('SessionPreviewTabs.navigate', () => { expect(o.tabs.find((t) => t.id === pageTabId)?.url).toBe('/runs') }) - it('retargets the one pipeline tab instead of turning the active tab into a second', () => { + it('keeps one tab per pipeline folder, several folders side by side', () => { const o = owner() o.open(pipelineTarget) - const pipelineTabId = o.activeId - o.open(scriptTarget) // a second, non-pipeline tab is now active - const scriptTabId = o.activeId - o.navigate(pipelineTarget2) - // No second pipeline editor: the existing one is retargeted and focused. + const crmTabId = o.activeId + o.open(pipelineTarget2) + const salesTabId = o.activeId expect(o.tabs).toHaveLength(2) - expect(o.activeId).toBe(pipelineTabId) - expect(o.tabs.find((t) => t.id === pipelineTabId)?.url).toBe(`${base}/pipeline/sales`) - // The script tab is untouched. - expect(o.tabs.find((t) => t.id === scriptTabId)?.url).toBe('/scripts/edit/u/me/foo') + expect(salesTabId).not.toBe(crmTabId) + o.open(scriptTarget) + // A folder already open is focused, from open() and navigate() alike. + o.open(pipelineTarget) + expect(o.activeId).toBe(crmTabId) + o.navigate(pipelineTarget2) + expect(o.activeId).toBe(salesTabId) + expect(o.tabs).toHaveLength(3) + expect(o.tabs.find((t) => t.id === crmTabId)?.url).toBe('/pipeline/crm') }) it('retargets the active pipeline tab in place to a new folder', () => { @@ -600,7 +602,7 @@ describe('SessionPreviewTabs.navigate', () => { o.navigate(pipelineTarget2) expect(o.tabs).toHaveLength(1) expect(o.activeId).toBe(tabId) - expect(o.tabs[0].url).toBe(`${base}/pipeline/sales`) + expect(o.tabs[0].url).toBe('/pipeline/sales') }) it('focuses the tab already viewing the artifact instead of duplicating the viewer', () => { @@ -1115,12 +1117,12 @@ describe('SessionPreviewTabs.pulseFocus', () => { const o = owner() const run: PreviewTarget = { type: 'page', - href: `${base}/run/job-1?workspace=fork`, + href: '/run/job-1?workspace=fork', label: 'Run' } o.open(run) // What the frame reports back has the injected params stripped. - o.observeLocation(o.activeId, `${base}/run/job-1?workspace=fork&nomenubar=true`) + o.observeLocation(o.activeId, '/run/job-1?workspace=fork&nomenubar=true') expect(o.tabs.length).toBe(1) expect(o.open(run).status).toBe('focused') expect(o.tabs.length).toBe(1) diff --git a/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts b/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts index 42221cdd9a..f40882b95b 100644 --- a/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionRuntime.svelte.ts @@ -1,10 +1,12 @@ import { SvelteMap } from 'svelte/reactivity' +import type { PendingRun } from '$lib/components/details/pendingRun' import { get } from 'svelte/store' -import { base } from '$lib/base' import { invalidate as invalidateWorkspaceItems } from '$lib/components/workspacePicker' import { invalidateWorkspaceDrafts } from '$lib/workspaceDrafts.svelte' import { AIChatManager, AIMode } from '$lib/components/copilot/chat/AIChatManager.svelte' import { PipelineEditorState } from '$lib/components/assets/AssetGraph/pipelineEditorState.svelte' +import { PIPELINE_DRAFT_KIND, pipelineBundlePath, pipelineLocalMirrorKey } from '$lib/pipelinePaths' +import type { DeployResult } from '$lib/utils_workspace_deploy' import { initFlow } from '$lib/components/flows/flowStore.svelte' import { ApiError, @@ -29,7 +31,12 @@ type SavedFlow = Omit<Flow & UserDraftOverlay, 'draft'> & { draft?: Flow } import type { HiddenRunnable } from '$lib/components/apps/types' import { type RawAppData, DEFAULT_DATA } from '$lib/components/raw_apps/dataTableRefUtils' import { userStore, userWorkspaces, workspaceStore } from '$lib/stores' -import { react19Template, STARTER_RUNNABLES } from '$lib/components/raw_apps/templates' +import { + BUILDER_FRAMEWORK_TEMPLATES, + react19Template, + STARTER_RUNNABLES +} from '$lib/components/raw_apps/templates' +import { operatorBuilderAppsIn, workspaceListLoaded } from '$lib/operatorWriteRights' import { random_adj } from '$lib/components/random_positive_adjetive' import { copilotWorkspace } from '$lib/aiStore' import { loadCopilot } from '$lib/components/copilot/loadCopilot' @@ -71,6 +78,8 @@ import { promptSafe, parseRunFormRoute, resolvePreviewTab, + pendingRunIdOf, + slotShowsPage, type PreviewSlot } from './previewRouter' import { normalizePipelineFolder } from '$lib/utils/pipelineFolder' @@ -102,6 +111,7 @@ import { type RawAppRunsProvider, type RawAppScreenshotRequester } from '$lib/components/raw_apps/utils' +import { resolveGlobalDraftStoragePathByKind } from '$lib/components/copilot/chat/global/userDraftAdapter' import type { RawAppDomQuery, RawAppDomRequester, @@ -135,6 +145,12 @@ export interface LoadSlot { export type SessionTargetKind = 'flow' | 'script' | 'raw_app' +/** What a mounted pipeline editor view offers the rest of the session. */ +export interface PipelineView { + /** Deploy all of the folder's drafts; failures stay drafts and are shown in the view. */ + deployAll(): Promise<DeployResult> +} + // The live runtime value a raw-app editor cell binds. Legacy drag-and-drop apps // are intentionally NOT hosted in the session preview (only code-based raw apps). export interface RawAppRuntimeValue { @@ -207,9 +223,17 @@ export interface SessionRuntime { // (renderer) and the open_preview/get_preview_status tools cross it, so the // tab model has exactly one live copy. readonly previewTabs: SessionPreviewTabs - // Pipeline target state — persists across editor hide/show (the pane unmounts - // on hide, so this can't be component-local) and across session switches. - readonly pipelineEditorState: PipelineEditorState + // Pipeline editor state per folder — persists across editor remounts and + // session switches, so it can't be component-local. Created on first use. + pipelineEditor(folder: string): PipelineEditorState + // A mounted pipeline editor view offers its deploy here; returns the unregister. + registerPipelineView(folder: string, view: PipelineView): () => void + // Deploy a folder's pipeline drafts through its editor tab, opening the tab if + // needed: the tab hydrates the drafts and shows what deployed and what failed. + deployPipeline(folder: string): Promise<DeployResult> + // Drop a folder's in-memory drafts once its draft bundle is discarded, so an + // open or later-mounted editor does not save them back. + forgetPipelineDrafts(folder: string): Promise<void> // Per-(kind, path) editor cells (content/baseline stores + load slot), created // on demand. Each editable preview tab resolves its own cell, so several items // stay live at once. @@ -226,6 +250,8 @@ export interface SessionRuntime { * viewer refetches when this changes — it reads the deployed version from the * API, so nothing else tells it the editor beside it just published. */ deployedRevision(kind: SessionTargetKind, path: string): number + /** The chat tool call a viewer tab was opened to answer, named by that tab's own url. */ + pendingRunFor(toolCallId: string): PendingRun | undefined /** Record that a preview tab landed on `url`. Fires for a newly opened tab and * for an existing one switched to the other side of its item. */ logTabUsage(url: string): void @@ -450,14 +476,7 @@ function createRuntime(session: Session): SessionRuntime { // point those at a page the user cannot see. const tab = owner?.displayedTab if (!tab) return undefined - const slotKind = resolvePreviewTab(tab.url).kind - if ( - slotKind !== 'iframe' && - slotKind !== 'pageitem' && - slotKind !== 'pagelist' && - slotKind !== 'viewer' - ) - return undefined + if (!slotShowsPage(resolvePreviewTab(tab.url).kind)) return undefined return previewLocationContext(whereIs(tab)) } // Pre-flight: materialise the (still-transient) session, then commit @@ -573,17 +592,37 @@ function createRuntime(session: Session): SessionRuntime { // Only persist a real width; undefined means "never resized" (defaults to 50). if (snap.previewSize != null) setSessionPreviewSize(session.id, snap.previewSize) }, + // Closing a tab that carried a call is not a refusal: the card still has the form. onTabsChanged: pruneEditorCells, onTabOpened: logTabUsage }) - // Let the jobs tray open a run in this session's preview panel (as an iframe - // tab over the run page). The global side-panel chat leaves this unset and + /** The call a viewer tab was opened to answer, for the page that renders it. Built from + * the id the tab carries rather than from state of our own, so there is nothing to keep in + * step: the tab names the call, and the manager says whether it is still waiting. */ + function pendingRunFor(toolCallId: string): PendingRun | undefined { + if (!manager.isRunFormPending(toolCallId)) return undefined + return { + toolCallId, + // Read here, so the page's `$derived` rebuilds when the posture changes under it. + planModeActive: manager.planModeActive, + // A getter, not a value: the page reads it once, when it builds the form, and this + // object is rebuilt on every keystroke of the card's draft otherwise. + get proposedArgs() { + return manager.pendingRunFormArgs(toolCallId) ?? {} + }, + adopt: (jobId, args, schema) => manager.handleRunFormJob(toolCallId, jobId, args, schema), + decline: () => manager.handleRunFormCancel(toolCallId) + } + } + + // Let the jobs tray open a run in this session's preview panel (as a tab on + // the run's page). The global side-panel chat leaves this unset and // falls back to a new browser tab. manager.openRunInPreview = ({ jobId, workspace, label }) => { previewTabs.open({ type: 'page', - href: `${base}/run/${jobId}?workspace=${workspace}`, + href: `/run/${jobId}?workspace=${workspace}`, label }) } @@ -594,15 +633,89 @@ function createRuntime(session: Session): SessionRuntime { manager.openRunForm = ({ toolCallId, label }) => { previewTabs.open({ type: 'runform', toolCallId, label }) } - manager.closeRunForm = (toolCallId) => previewTabs.closeRunForm(toolCallId) - manager.showRunInPlaceOfForm = ({ toolCallId, jobId, workspace }) => { - previewTabs.retargetRunForm(toolCallId, `${base}/run/${jobId}?workspace=${workspace}`) + // Show a deployed run on the item's own page. With `carries`, that page answers the call: + // the job its Run starts is the one the tool follows. + manager.openRunOnDeployedPage = ({ + toolCallId, + kind, + path, + summary, + carries, + onlyIfAlreadyOpen + }) => { + // Through the shared adapter: a session target spells a code-based app `raw_app` and a + // workspace item spells it `app` with a flag, and one place should know that. + const target = previewTargetForSessionTarget(kind, path) + if (target?.type !== 'item') return false + const viewTarget = { + ...target, + item: { ...target.item, summary }, + mode: 'view' as const, + pendingRunId: carries ? toolCallId : undefined + } + // Re-pointed rather than focused: the url is what hands the tab the call, and + // rebuilding it also drops whatever version the reader had pinned. + const open = previewTabs.tabs.find((t) => { + const slot = resolvePreviewTab(t.url) + return slot.kind === 'viewer' && slot.viewerKind === kind && slot.path === path + }) + if (open) { + // An unasked-for hand-off goes only to the page the reader already has in front of + // them. `navigate` below re-points the tab, which reloads it and rebuilds its url: + // on a tab they cannot see that silently drops whatever they had typed into its + // form and leaves the call on an off-screen page, and on a pinned one it moves them + // off the version they chose. Declining leaves the call on the card, which can run + // it. A reader who presses Preview is asking for all of that. + if ( + onlyIfAlreadyOpen && + (previewTabs.activeId !== open.id || + previewTabs.collapsed || + new URL(open.url, 'http://x').searchParams.get('version')) + ) { + return false + } + previewTabs.navigate(viewTarget, open.id) + // `navigate` re-points a tab in place and nothing more, while the call is about to + // tell the reader the page is open. `open` would have brought it forward and shown + // the panel; this path has to do both itself. + previewTabs.select(open.id) + previewTabs.setCollapsed(false) + } else { + // Only the item's own page carries a form for this call, so a caller routing a call + // that was not asked to open anything gets a no rather than a new tab. + if (onlyIfAlreadyOpen) return false + previewTabs.open(viewTarget) + } + return true } - // Read off the tab list rather than the slot's lifecycle: a tab the user has switched - // away from is unmounted but still open, and the card must keep its form hidden until it - // is closed. A resolver, like activePreviewResolver: the reader's own $derived subscribes - // to `tabs` through it, and the runtime is not inside an effect root to push from. + manager.closeRunForm = (toolCallId) => { + // A page carrying the call outlives it, and stops carrying it because the call stops + // being pending. Only the chat's own form tab, which is the call, goes with it. + previewTabs.closeRunForm(toolCallId) + } + manager.showRunInPlaceOfForm = ({ toolCallId, jobId, workspace }) => { + const runHref = `/run/${jobId}?workspace=${workspace}` + // Either surface the call was waiting on becomes the run it started, in place. + const carrying = previewTabs.tabs.find((t) => pendingRunIdOf(t.url) === toolCallId) + if (carrying) previewTabs.retargetById(carrying.id, runHref) + previewTabs.retargetRunForm(toolCallId, runHref) + } + // Both read off the tab list rather than the slot's lifecycle: a tab the user has switched + // away from is unmounted but still open. Resolvers, like activePreviewResolver: the + // reader's own $derived subscribes to `tabs` through them, and the runtime is not inside + // an effect root to push from. So a tab closed or re-pointed hands the card back whatever + // it had given up. + // Either surface — the chat's own form in a tab, or the item's page carrying the call. manager.isRunFormInPreview = (toolCallId) => + previewTabs.tabs.some( + (t) => + parseRunFormRoute(t.url)?.toolCallId === toolCallId || pendingRunIdOf(t.url) === toolCallId + ) + // The chat's own form alone. The card's form is exclusive with this one and no other: + // both bind the one draft, and SchemaForm reorders in place the schema it is handed, so a + // second mount reorders it again. A page builds its own form from a copy of the proposal + // and shares nothing, so the card keeps its form while a page carries the call. + manager.isRunFormTabOpen = (toolCallId) => previewTabs.tabs.some((t) => parseRunFormRoute(t.url)?.toolCallId === toolCallId) manager.openArtifact = (id, name, version) => { @@ -618,10 +731,78 @@ function createRuntime(session: Session): SessionRuntime { // picker lists, so changeMode's network refreshes would fire once per listing. manager.configureGlobalMode() - // Pipeline target state lives on the runtime (not the PipelineEditorView - // component) so the in-session drafts survive hide/show of the editor pane — - // the pane unmounts on hide, and a component-local store would be discarded. - const pipelineEditorState = new PipelineEditorState() + const pipelineEditors = new Map<string, PipelineEditorState>() + function pipelineEditor(folder: string): PipelineEditorState { + const key = normalizePipelineFolder(folder) + let editor = pipelineEditors.get(key) + if (!editor) { + editor = new PipelineEditorState() + editor.folder = key + pipelineEditors.set(key, editor) + } + return editor + } + + const pipelineViews = new Map<string, PipelineView>() + const pipelineViewWaiters = new Map<string, Set<(view: PipelineView) => void>>() + function registerPipelineView(folder: string, view: PipelineView): () => void { + const key = normalizePipelineFolder(folder) + pipelineViews.set(key, view) + const waiters = pipelineViewWaiters.get(key) + pipelineViewWaiters.delete(key) + waiters?.forEach((notify) => notify(view)) + return () => { + if (pipelineViews.get(key) === view) pipelineViews.delete(key) + } + } + function pipelineViewFor(folder: string, timeoutMs = 15000): Promise<PipelineView | undefined> { + const mounted = pipelineViews.get(folder) + if (mounted) return Promise.resolve(mounted) + return new Promise((resolve) => { + const waiters = pipelineViewWaiters.get(folder) ?? new Set() + pipelineViewWaiters.set(folder, waiters) + const notify = (view: PipelineView) => { + clearTimeout(timer) + resolve(view) + } + const timer = setTimeout(() => { + waiters.delete(notify) + resolve(undefined) + }, timeoutMs) + waiters.add(notify) + }) + } + manager.setPipelineReopener((folder) => { + const target = previewTargetForSessionTarget('pipeline', folder) + if (target) previewTabs.open(target) + }) + async function deployPipeline(folder: string): Promise<DeployResult> { + const key = normalizePipelineFolder(folder) + const target = previewTargetForSessionTarget('pipeline', key) + if (target) previewTabs.open(target) + const view = await pipelineViewFor(key) + if (!view) return { success: false, error: `The pipeline editor for f/${key} did not open.` } + return view.deployAll() + } + async function forgetPipelineDrafts(folder: string): Promise<void> { + const key = normalizePipelineFolder(folder) + const editor = pipelineEditors.get(key) + if (editor) { + // The open pane saves its edits back as a draft when it closes: let it, then + // drop that draft with the rest, or it would come back afterwards. + await editor.closePane() + editor.drafts = new Map() + editor.triggerDrafts = new Map() + editor.clearLiveOverlays() + } + // The editor's crash mirror, which its load falls back to when the DB has + // no draft: left behind, it would restore what was just discarded. + try { + localStorage.removeItem(pipelineLocalMirrorKey(key)) + } catch { + // Storage unavailable: nothing was mirrored either. + } + } const runtimeLogRequesters = new Map<string, RawAppRuntimeLogRequester>() // appPath → requester, one entry per mounted raw-app preview tab. @@ -635,10 +816,14 @@ function createRuntime(session: Session): SessionRuntime { sessionId: session.id, manager, previewTabs, - pipelineEditorState, + pipelineEditor, + registerPipelineView, + deployPipeline, + forgetPipelineDrafts, flowCell, loadedEditorPath, deployedRevision, + pendingRunFor, logTabUsage, async loadFlow(workspace: string, path: string, force = false) { @@ -965,15 +1150,19 @@ function createRuntime(session: Session): SessionRuntime { } catch (err) { if (seedIfMissing && !deployedOnly && err instanceof ApiError && err.status === 404) { const user = get(userStore) + // A builder can save no inline runnable, so the regular starter could never be saved. + await workspaceListLoaded() + const builder = operatorBuilderAppsIn(workspace) saved.val = undefined store.val = { - files: { ...react19Template }, - runnables: structuredClone(STARTER_RUNNABLES), + files: { ...(builder ? BUILDER_FRAMEWORK_TEMPLATES.react19 : react19Template) }, + runnables: builder ? {} : structuredClone(STARTER_RUNNABLES), data: { ...DEFAULT_DATA }, policy: { on_behalf_of: user?.username.includes('@') ? user.username : `u/${user?.username}`, on_behalf_of_email: user?.email, - execution_mode: 'publisher' + execution_mode: 'publisher', + sandbox: true }, summary: '', path, @@ -1034,7 +1223,7 @@ function createRuntime(session: Session): SessionRuntime { }, async requestRuntimeLogs(limit, appPath) { const path = - appPath ?? + (appPath && draftStoragePath(session, 'raw_app', appPath)) ?? activeDomAppPath ?? (runtimeLogRequesters.size === 1 ? [...runtimeLogRequesters.keys()][0] : undefined) if (path === undefined) { @@ -1070,7 +1259,7 @@ function createRuntime(session: Session): SessionRuntime { // its element's app even when another tab is now visible), else the // active preview, else the only one open. const path = - query.appPath ?? + (query.appPath && draftStoragePath(session, 'raw_app', query.appPath)) ?? activeDomAppPath ?? (domRequesters.size === 1 ? [...domRequesters.keys()][0] : undefined) if (path === undefined) return undefined @@ -1167,6 +1356,18 @@ export function listRuntimes(): SessionRuntime[] { return Array.from(runtimes.values()) } +/** A pipeline deleted outside the session: every live session on its workspace + * drops what it holds of it. Its in-memory drafts would otherwise keep showing the + * pipeline in the preview, and autosave would write the deleted draft back. */ +export function forgetDeletedPipeline(workspace: string, folder: string): void { + const key = normalizePipelineFolder(folder) + for (const runtime of runtimes.values()) { + if (runtime.manager.operatingWorkspace !== workspace) continue + void runtime.forgetPipelineDrafts(key) + void runtime.manager.removeModifiedItem(PIPELINE_DRAFT_KIND, pipelineBundlePath(key)) + } +} + export function getRuntime(sessionId: string): SessionRuntime | undefined { return runtimes.get(sessionId) } @@ -1274,6 +1475,18 @@ export function removeSession(sessionId: string): void { deleteSessionState(sessionId) } +// The chat calls a new item by its chosen name while its draft is stored at +// `draft_<uuid>`; resolve the name the way the chat's write tools do. +function draftStoragePath( + session: Session, + kind: 'script' | 'flow' | 'raw_app', + path: string +): string { + return session.workspace_id + ? resolveGlobalDraftStoragePathByKind(session.workspace_id, kind, path) + : path +} + // Register the global open_preview tool handler once at module load. It // dispatches to the *calling* session (sessionId threaded from the tool ctx), // falling back to the UI-active session only when none was passed — so a @@ -1289,7 +1502,10 @@ setOpenPreviewHandler(async ({ sessionId: callerSessionId, kind, path, mode }) = if (!session) { return 'Error: no active session to open the preview in.' } - const target = previewTargetForSessionTarget(kind, path) + const target = previewTargetForSessionTarget( + kind, + mode === 'view' || kind === 'pipeline' ? path : draftStoragePath(session, kind, path) + ) if (!target) { return `Error: ${kind} targets cannot be shown in the preview panel.` } @@ -1305,8 +1521,8 @@ setOpenPreviewHandler(async ({ sessionId: callerSessionId, kind, path, mode }) = // "Unknown tool call" error on the first node it tries to build. if (kind === 'pipeline') { const folder = normalizePipelineFolder(path) - const ready = await runtime.manager.waitForPipelineHelpers() - // A backgrounded session's preview tab does not mount, so its editor never + const ready = await runtime.manager.waitForPipelineHelpers(folder) + // A session whose page is not mounted never mounts the editor, so it never // registers — don't claim success, or the model calls build_pipeline_node // into the void. Tell it the tools aren't available and how to recover. if (!ready) { @@ -1316,7 +1532,7 @@ setOpenPreviewHandler(async ({ sessionId: callerSessionId, kind, path, mode }) = // off the owner path twice over) is rejected by build_pipeline_node. return `${ result.status === 'focused' ? 'Focused the' : 'Opened the' - } pipeline editor for folder "${folder}" in the side panel. Its nodes go at paths under \`f/${folder}/\` (e.g. \`f/${folder}/<node_name>\`).` + } pipeline editor for folder "${folder}" in the side panel. build_pipeline_node, edit_pipeline_node and the other pipeline tools are now in your tool list: call them in your next step. Its nodes go at paths under \`f/${folder}/\` (e.g. \`f/${folder}/<node_name>\`).` } return result.status === 'focused' ? `A preview tab is already showing ${kind} "${path}" — focused it.` diff --git a/frontend/src/lib/components/sessions/sessionSharing.test.ts b/frontend/src/lib/components/sessions/sessionSharing.test.ts new file mode 100644 index 0000000000..a7720666fa --- /dev/null +++ b/frontend/src/lib/components/sessions/sessionSharing.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it } from 'vitest' + +import { readSessionSnapshot } from './sessionSharing' + +describe('readSessionSnapshot', () => { + it('keeps only inline images and the rows and artifacts the viewer can render', () => { + const snapshot = readSessionSnapshot({ + messages: [ + { + role: 'user', + content: 'hi', + images: [ + { dataUrl: 'https://tracker.example/u.png', mediaType: 'image/png' }, + { dataUrl: 'data:image/png;base64,AAAA', mediaType: 'image/png' } + ] + }, + { role: 'tool', content: 'shot', imageUrl: 'https://tracker.example/t.png' }, + { role: 'tool', content: 'shot', imageUrl: 'data:image/png;base64,BBBB' }, + { + role: 'tool', + content: 'Run', + isLoading: true, + needsConfirmation: true, + runForm: { kind: 'test', code: 'export async function main() {}' }, + userQuestion: { question: 'ok?' }, + actions: [{ label: 'Open' }], + inspectedRun: { jobId: 'j', workspace: 'w', runId: 'j' } + }, + { role: 'system', content: 'not a chat row' }, + 'not an object' + ], + artifacts: [ + { id: 'a', name: 'Plan', kind: 'md', content: '# Plan' }, + { id: 'b', name: 'Bad', kind: 'svg', content: '<svg/>' } + ] + }) + + expect(snapshot.messages.map((m) => m.role)).toEqual(['user', 'tool', 'tool', 'tool']) + expect(snapshot.messages[0]).toMatchObject({ + images: [{ dataUrl: 'data:image/png;base64,AAAA' }] + }) + expect((snapshot.messages[1] as { imageUrl?: string }).imageUrl).toBeUndefined() + expect(snapshot.messages[2]).toMatchObject({ imageUrl: 'data:image/png;base64,BBBB' }) + // Every affordance that would act as the reader is gone, pending state included. + expect(snapshot.messages[3]).toEqual({ + role: 'tool', + tool_call_id: 'shared-3', + content: 'Run', + showDetails: false, + blockedByPlanMode: false, + declinedByUser: false + }) + expect(snapshot.artifacts.map((a) => a.id)).toEqual(['a']) + }) + + it('reads a malformed snapshot as an empty one', () => { + expect(readSessionSnapshot('nope')).toEqual({ messages: [], artifacts: [] }) + }) +}) diff --git a/frontend/src/lib/components/sessions/sessionSharing.ts b/frontend/src/lib/components/sessions/sessionSharing.ts new file mode 100644 index 0000000000..3ecbe214e9 --- /dev/null +++ b/frontend/src/lib/components/sessions/sessionSharing.ts @@ -0,0 +1,188 @@ +import type { DisplayMessage } from '$lib/components/copilot/chat/shared' +import type { ImageMediaType } from '$lib/components/copilot/chat/imageUtils' +import type { + ArtifactKind, + PersistedArtifact +} from '$lib/components/copilot/chat/artifacts/artifactsDB' + +/** The server's `MAX_SNAPSHOT_BYTES`. */ +export const MAX_SNAPSHOT_BYTES = 10 * 1024 * 1024 + +export type SharedSessionArtifact = { + id: string + name: string + kind: ArtifactKind + content: string + role?: 'plan' +} + +export type SessionSnapshot = { + messages: DisplayMessage[] + artifacts: SharedSessionArtifact[] +} + +export function sharedSessionUrl(workspaceId: string, shareId: string): string { + return `${window.location.origin}/shared_sessions/${encodeURIComponent( + workspaceId + )}/${encodeURIComponent(shareId)}` +} + +/** A row as it reads once the turn is over: the viewer can neither wait on nor answer it. */ +function settled(message: DisplayMessage, keepImages: boolean): DisplayMessage { + switch (message.role) { + case 'tool': + return { + ...message, + isLoading: false, + isQueued: false, + isStreamingArguments: false, + needsConfirmation: false, + resultStream: undefined + } + case 'assistant': + return { ...message, streaming: false } + case 'user': + return keepImages ? message : { ...message, images: undefined } + default: + return message + } +} + +/** + * The snapshot a share carries. Images go first when the whole would not fit: the + * transcript is what the link is for. + */ +export function buildSessionSnapshot( + messages: DisplayMessage[], + artifacts: PersistedArtifact[] +): SessionSnapshot { + const sharedArtifacts: SharedSessionArtifact[] = artifacts.map((a) => ({ + id: a.id, + name: a.name, + kind: a.kind, + content: a.content, + role: a.role + })) + for (const keepImages of [true, false]) { + const snapshot: SessionSnapshot = { + messages: messages.map((m) => settled(m, keepImages)), + artifacts: sharedArtifacts + } + if (new TextEncoder().encode(JSON.stringify(snapshot)).length <= MAX_SNAPSHOT_BYTES) { + return snapshot + } + } + throw new Error( + `the session is larger than the ${MAX_SNAPSHOT_BYTES / 1024 / 1024} MB a share can hold` + ) +} + +function isInlineImage(url: unknown): url is string { + return typeof url === 'string' && url.startsWith('data:image/') +} + +function isRecord(value: unknown): value is Record<string, unknown> { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +function str(value: unknown): string | undefined { + return typeof value === 'string' ? value : undefined +} + +function records(value: unknown): Record<string, unknown>[] { + return Array.isArray(value) ? value.filter(isRecord) : [] +} + +/** + * A row rebuilt from the fields that only display. Everything else the live chat carries on a + * row is an affordance acting as whoever has the page open (a run form, a question to answer, + * a run to inspect, an item to open) or a pending state that mounts one, so it never survives: + * the author controls every byte of the snapshot. + */ +function readMessage(m: Record<string, unknown>, index: number): DisplayMessage | undefined { + const content = str(m.content) ?? '' + switch (m.role) { + case 'user': + return { + role: 'user', + content, + index, + images: records(m.images) + .filter((i) => isInlineImage(i.dataUrl)) + .map((i) => ({ + dataUrl: i.dataUrl as string, + mediaType: i.mediaType as ImageMediaType, + name: str(i.name) + })), + pastes: records(m.pastes) + .filter((p) => typeof p.id === 'number' && typeof p.content === 'string') + .map((p) => ({ + id: p.id as number, + lines: typeof p.lines === 'number' ? p.lines : 0, + content: p.content as string + })), + files: records(m.files) + .filter((f) => typeof f.name === 'string' && typeof f.content === 'string') + .map((f) => ({ name: f.name as string, content: f.content as string })) + } + case 'assistant': + return { + role: 'assistant', + content, + reasoning: str(m.reasoning), + reasoningDurationMs: + typeof m.reasoningDurationMs === 'number' ? m.reasoningDurationMs : undefined, + createdAt: str(m.createdAt) + } + case 'tool': + return { + role: 'tool', + tool_call_id: str(m.tool_call_id) ?? `shared-${index}`, + content, + toolName: str(m.toolName), + parameters: m.parameters, + result: m.result, + logs: str(m.logs), + error: str(m.error), + showDetails: m.showDetails === true, + imageUrl: isInlineImage(m.imageUrl) ? m.imageUrl : undefined, + planArtifactId: str(m.planArtifactId), + planVersion: typeof m.planVersion === 'number' ? m.planVersion : undefined, + blockedByPlanMode: m.blockedByPlanMode === true, + declinedByUser: m.declinedByUser === true + } + case 'summary': + return { role: 'summary', content } + default: + return undefined + } +} + +/** + * A snapshot as the viewer may render it: rows rebuilt by {@link readMessage}, and an attached + * image only from an inline data URL, since any other source would load a third-party resource + * on behalf of whoever opens the link. Images inside rendered text are left to the viewer + * page's `img-src` policy. + */ +export function readSessionSnapshot(raw: unknown): SessionSnapshot { + const snapshot = isRecord(raw) ? raw : {} + const messages = records(snapshot.messages) + .map(readMessage) + .filter((m): m is DisplayMessage => m !== undefined) + const artifacts = records(snapshot.artifacts) + .filter( + (a) => + typeof a.id === 'string' && + typeof a.name === 'string' && + typeof a.content === 'string' && + (a.kind === 'md' || a.kind === 'html') + ) + .map((a) => ({ + id: a.id as string, + name: a.name as string, + kind: a.kind as ArtifactKind, + content: a.content as string, + role: a.role === 'plan' ? ('plan' as const) : undefined + })) + return { messages, artifacts } +} diff --git a/frontend/src/lib/components/sessions/sessionSwitch.svelte.ts b/frontend/src/lib/components/sessions/sessionSwitch.svelte.ts index a0ef0e5696..30b7792487 100644 --- a/frontend/src/lib/components/sessions/sessionSwitch.svelte.ts +++ b/frontend/src/lib/components/sessions/sessionSwitch.svelte.ts @@ -15,7 +15,7 @@ import { type SessionTarget } from './sessionState.svelte' import { sessionTargetHref, withPreviewParams } from './sessionMode.svelte' -import { parsePreviewItemRoute, type PreviewItemRoute } from './previewPaths' +import { parsePipelineRoute, parsePreviewItemRoute } from './previewPaths' import { findMountedOpenInSessionSource } from './openInSessionContext' // Type-only: erased at compile time, so the component graph stays out of this // navigation seam (see the dynamic import in openEditorInSession). @@ -42,10 +42,28 @@ export function rememberNavRoute(pathnameWithSearch: string): void { } /** An item editor the user reached session mode from, as the in-app href a new - * session's preview can open, plus the item it edits (for naming it). */ -export type NewSessionSeed = { url: string; route: PreviewItemRoute } + * session's preview can open, plus what it edits (for naming it). */ +export type NewSessionSeed = { url: string; kind: string; path: string } -// The item (flow, script, app) the user came to session mode from, or undefined +/** What an editor route edits: a session target, or an unset target for an item + * with no in-session editor (a legacy app), which is opened by its page instead. */ +function editedAt( + url: string +): { target: SessionTarget | undefined; kind: string; path: string } | undefined { + const folder = parsePipelineRoute(url) + if (folder) + return { target: { kind: 'pipeline', path: folder }, kind: 'pipeline', path: `f/${folder}` } + const route = parsePreviewItemRoute(url) + if (!route) return undefined + const kind = route.kind === 'app' ? (route.raw_app ? 'raw_app' : undefined) : route.kind + return { + target: kind ? { kind, path: route.itemPath } : undefined, + kind: route.kind, + path: route.itemPath + } +} + +// The item (flow, script, app, pipeline) the user came to session mode from, or undefined // when they came from anywhere else. A "New session" asked for after arriving // from an item is usually a session about that item, but the arrival route // (`enterSessionMode`) resumes whatever session was open, so the picker offers @@ -56,8 +74,8 @@ export type NewSessionSeed = { url: string; route: PreviewItemRoute } export function takeNewSessionSeed(): NewSessionSeed | undefined { if (navRouteOffered) return undefined navRouteOffered = true - const route = parsePreviewItemRoute(lastNavRoute) - return route ? { url: lastNavRoute, route } : undefined + const edited = editedAt(lastNavRoute) + return edited ? { url: lastNavRoute, kind: edited.kind, path: edited.path } : undefined } // The session entering session mode resumes: the active one if selected, else @@ -102,8 +120,8 @@ const RESUME_IDLE_LIMIT_MS = 60 * 60 * 1000 // enterSessionMode does. Rejects when the editor could not persist its draft, // so the caller can stay on the page and say so. export async function enterSessionModeFromNav(): Promise<void> { - const route = parsePreviewItemRoute(lastNavRoute) - if (route) { + const edited = editedAt(lastNavRoute) + if (edited) { const resumable = resumableSession() if (!resumable || Date.now() - sessionLastActivityAt(resumable) > RESUME_IDLE_LIMIT_MS) { // The editor's own hand-off is what its "Open in AI session" button uses: @@ -112,7 +130,7 @@ export async function enterSessionModeFromNav(): Promise<void> { // workspace the item lives in. Only an item with no such editor on // screen (a legacy app, a detail page) is opened by route, as last // persisted, in the workspace the route was scoped to. - const source = findMountedOpenInSessionSource(route) + const source = edited.target && findMountedOpenInSessionSource(edited.target) if (source) await openSourceInSession(source) else await openPageInSession(lastNavRoute, workspaceParamOf(lastNavRoute)) return diff --git a/frontend/src/lib/components/sessions/sessionSwitch.test.ts b/frontend/src/lib/components/sessions/sessionSwitch.test.ts index 4eae32da6b..497e3cbad9 100644 --- a/frontend/src/lib/components/sessions/sessionSwitch.test.ts +++ b/frontend/src/lib/components/sessions/sessionSwitch.test.ts @@ -259,16 +259,21 @@ describe('takeNewSessionSeed', () => { rememberNavRoute('/flows/edit/u/me/my_flow?workspace=ws') expect(takeNewSessionSeed()).toEqual({ url: '/flows/edit/u/me/my_flow?workspace=ws', - route: { kind: 'flow', raw_app: false, itemPath: 'u/me/my_flow', mode: 'edit' } + kind: 'flow', + path: 'u/me/my_flow' }) // A dismissed or taken offer is not repeated until the user leaves again. expect(takeNewSessionSeed()).toBeUndefined() rememberNavRoute('/apps_raw/edit/f/team/dashboard?workspace=ws') - expect(takeNewSessionSeed()?.route).toEqual({ - kind: 'app', - raw_app: true, - itemPath: 'f/team/dashboard', - mode: 'edit' + expect(takeNewSessionSeed()).toMatchObject({ kind: 'app', path: 'f/team/dashboard' }) + }) + + it('offers the pipeline the user came from, named by its folder', () => { + rememberNavRoute('/pipeline/crm?workspace=ws') + expect(takeNewSessionSeed()).toEqual({ + url: '/pipeline/crm?workspace=ws', + kind: 'pipeline', + path: 'f/crm' }) }) diff --git a/frontend/src/lib/components/settings/CreateToken.svelte b/frontend/src/lib/components/settings/CreateToken.svelte index 8ee5391443..56952eb584 100644 --- a/frontend/src/lib/components/settings/CreateToken.svelte +++ b/frontend/src/lib/components/settings/CreateToken.svelte @@ -245,6 +245,8 @@ // Undefined wherever the workspace is: `/api/mcp/w/undefined/mcp` reads like a real URL // and is copyable, so the OAuth panel withholds it rather than showing a broken one. The // token branch guards the same case by disabling its generate button. + // On the browsing origin, not the API base url: the OAuth metadata the server + // publishes for this URL is built from `base_url`, and a client rejects a mismatch. const mcpUrl = $derived( isAllWorkspaces ? `${window.location.origin}/api/mcp/gateway` diff --git a/frontend/src/lib/components/settings/PremiumInfo.svelte b/frontend/src/lib/components/settings/PremiumInfo.svelte index 766b2c6495..06c490426a 100644 --- a/frontend/src/lib/components/settings/PremiumInfo.svelte +++ b/frontend/src/lib/components/settings/PremiumInfo.svelte @@ -1,7 +1,6 @@ <script lang="ts"> import { run } from 'svelte/legacy' - import { base } from '$lib/base' import { capitalize, pluralize, sendUserToast } from '$lib/utils' import DataTable from '$lib/components/table/DataTable.svelte' import Cell from '$lib/components/table/Cell.svelte' @@ -195,7 +194,7 @@ <Button endIcon={{ icon: ExternalLink }} variant="accent" - href="{base}/api/w/{$workspaceStore}/workspaces/billing_portal">Customer Portal</Button + href="/api/w/{$workspaceStore}/workspaces/billing_portal">Customer Portal</Button > <p class="text-xs text-primary mt-1"> See invoices, change billing information or subscription details. @@ -591,7 +590,7 @@ <Button size="xs" color="bg-blue-500 text-white" - href="{base}/api/w/{$workspaceStore}/workspaces/checkout?plan=team" + href="/api/w/{$workspaceStore}/workspaces/checkout?plan=team" > Upgrade to Team plan</Button > diff --git a/frontend/src/lib/components/settings/ScopeSelector.svelte b/frontend/src/lib/components/settings/ScopeSelector.svelte index b3293ab36e..663e043035 100644 --- a/frontend/src/lib/components/settings/ScopeSelector.svelte +++ b/frontend/src/lib/components/settings/ScopeSelector.svelte @@ -643,7 +643,7 @@ ? 'bg-surface-disabled opacity-60' : 'bg-surface-tertiary'}" > - <div class="flex justify-between items-center"> + <div class="flex justify-between items-center min-h-7"> <label class={twMerge( 'flex items-center gap-2 flex-1 min-w-0', @@ -677,7 +677,7 @@ > {#snippet trigger()} <Button - size="xs" + unifiedSize="sm" disabled={isDisabled} variant="default" startIcon={resourcePathArray.length > 0 @@ -717,7 +717,7 @@ onclick={() => { addResourcePath(scope.value, currentInput) }} - size="xs" + unifiedSize="sm" disabled={!currentInput.trim()} > Add diff --git a/frontend/src/lib/components/settings/WorkspaceOperatorSettings.svelte b/frontend/src/lib/components/settings/WorkspaceOperatorSettings.svelte index da7cd5a3de..b9ad80f63e 100644 --- a/frontend/src/lib/components/settings/WorkspaceOperatorSettings.svelte +++ b/frontend/src/lib/components/settings/WorkspaceOperatorSettings.svelte @@ -31,6 +31,7 @@ // Kept out of `operatorWorkspaceSettings` so the visibility table's "Enable all" never flips a // write right, and so these rows stay out of that table. let builderFlows = $state(false) + let builderApps = $state(false) // Withdrawable rather than granted: operators hold these until an admin turns them off. let manageSchedules = $state(true) let manageTriggers = $state(true) @@ -38,6 +39,7 @@ let originalSettings = $state({ ...untrack(() => operatorWorkspaceSettings), builder_flows: false, + builder_apps: false, manage_schedules: true, manage_triggers: true }) @@ -51,15 +53,24 @@ const settingsPayload = $derived({ ...operatorWorkspaceSettings, builder_flows: builderFlows, + builder_apps: builderApps, manage_schedules: manageSchedules, manage_triggers: manageTriggers }) - // The seat cost lands when the right is first granted, so confirm only on that transition. - const grantsBuilderRight = $derived(builderFlows && !originalSettings.builder_flows) + // The seat cost lands on the first right granted, so confirm only when going from neither to + // either. Adding the second one later is already paid for. + const grantsFirstBuilderRight = $derived( + (builderFlows || builderApps) && + !(originalSettings.builder_flows || originalSettings.builder_apps) + ) + + const grantedBuilderKinds = $derived( + [builderFlows && 'flows', builderApps && 'full-code apps'].filter(Boolean).join(' and ') + ) function onSaveClicked() { - if (grantsBuilderRight) { + if (grantsFirstBuilderRight) { confirmBuilderOpen = true } else { saveSettings() @@ -105,17 +116,20 @@ // would be saved here with the next unrelated change, builder rights among them. const { builder_flows: remoteFlows, + builder_apps: remoteApps, manage_schedules: remoteSchedules, manage_triggers: remoteTriggers, ...remoteVisibility } = settings.operator_settings ?? {} operatorWorkspaceSettings = { ...defaultVisibility, ...remoteVisibility } builderFlows = remoteFlows ?? false + builderApps = remoteApps ?? false manageSchedules = remoteSchedules ?? true manageTriggers = remoteTriggers ?? true originalSettings = { ...operatorWorkspaceSettings, builder_flows: builderFlows, + builder_apps: builderApps, manage_schedules: manageSchedules, manage_triggers: manageTriggers } @@ -155,8 +169,8 @@ <Section small - label="Build flows" - description="Let operators compose flows out of scripts and flows that are already deployed. They still cannot write code. Granting this makes each operator consume a full seat instead of half a seat." + label="Build flows and apps" + description="Let operators build flows out of deployed scripts and flows, and full-code apps whose frontend code they write. Apps always run sandboxed, and operators still cannot write backend scripts. Granting either right makes each operator consume a full seat instead of half a seat." wrapperClass="mb-6" class="flex flex-col gap-y-1" > @@ -165,6 +179,11 @@ options={{ right: 'Operators can build flows' }} size="xs" /> + <Toggle + bind:checked={builderApps} + options={{ right: 'Operators can build full-code apps' }} + size="xs" + /> </Section> <Section @@ -269,8 +288,8 @@ instance is billed. </span> <span> - They can create, edit and delete flows wherever their folder permissions already let them - write. Review those permissions before enabling. + They can create, edit and delete {grantedBuilderKinds} wherever their folder permissions already + let them write. Review those permissions before enabling. </span> </div> </ConfirmationModal> diff --git a/frontend/src/lib/components/sidebar/CriticalAlertModal.svelte b/frontend/src/lib/components/sidebar/CriticalAlertModal.svelte index 4a41c65a31..acc8165014 100644 --- a/frontend/src/lib/components/sidebar/CriticalAlertModal.svelte +++ b/frontend/src/lib/components/sidebar/CriticalAlertModal.svelte @@ -16,7 +16,6 @@ import List from '$lib/components/common/layout/List.svelte' import Toggle from '$lib/components/Toggle.svelte' import { BellOff, Bell, ExternalLink, Settings } from 'lucide-svelte' - import { base } from '$lib/base' import Notification from '$lib/components/common/alert/Notification.svelte' interface Props { @@ -71,7 +70,7 @@ await updateHasUnacknowledgedCriticalAlerts(false) checkForNewAlertsInterval = setInterval(() => { updateHasUnacknowledgedCriticalAlerts(true) - }, 15000) + }, 30000) }) onDestroy(() => { @@ -255,7 +254,7 @@ <Button size="xs" color="light" - href="{base}/?workspace=admins#superadmin-settings" + href="/?workspace=admins#superadmin-settings" target="_blank" > <div class="w-full"> @@ -270,7 +269,7 @@ <Button size="xs" color="light" - href="{base}/workspace_settings?tab=error_handler" + href="/workspace_settings?tab=error_handler" target="_blank" > Workspace Critical Alert Settings <ExternalLink size="16" /> @@ -283,7 +282,7 @@ <Button size="xs" variant="default" - href="{base}/workspace_settings?tab=error_handler" + href="/workspace_settings?tab=error_handler" target="_blank" > <List horizontal justify="between" gap="sm"> diff --git a/frontend/src/lib/components/sidebar/FavoriteMenu.svelte b/frontend/src/lib/components/sidebar/FavoriteMenu.svelte index 1c3191f0cb..c3d14d4c4d 100644 --- a/frontend/src/lib/components/sidebar/FavoriteMenu.svelte +++ b/frontend/src/lib/components/sidebar/FavoriteMenu.svelte @@ -10,6 +10,7 @@ flow: `/flows/get/${path}`, app: `/apps/get/${path}`, raw_app: `/apps_raw/get/${path}`, + agent: `/agents/get/${path}`, asset: '#' }[kind] } @@ -71,7 +72,7 @@ </script> <script lang="ts"> - import { CodeXml, LayoutDashboard, Table2, Star, Trash2 } from 'lucide-svelte' + import { Bot, CodeXml, LayoutDashboard, Table2, Star, Trash2 } from 'lucide-svelte' import BarsStaggered from '$lib/components/icons/BarsStaggered.svelte' import { Menu, MenuItem } from '$lib/components/meltComponents' import MenuButton from '$lib/components/sidebar/MenuButton.svelte' @@ -141,6 +142,8 @@ <BarsStaggered size={16} class="text-teal-500" /> {:else if favorite.kind == 'app' || favorite.kind == 'raw_app'} <LayoutDashboard size={16} class="text-orange-500" /> + {:else if favorite.kind == 'agent'} + <Bot size={16} class="text-violet-500" /> {:else if favorite.kind == 'asset'} <Table2 size={16} class="text-primary" /> {/if} diff --git a/frontend/src/lib/components/sidebar/FinishAccountSetup.svelte b/frontend/src/lib/components/sidebar/FinishAccountSetup.svelte index 8115f3a3d7..9a3080137a 100644 --- a/frontend/src/lib/components/sidebar/FinishAccountSetup.svelte +++ b/frontend/src/lib/components/sidebar/FinishAccountSetup.svelte @@ -1,6 +1,5 @@ <script lang="ts"> import type { Component } from 'svelte' - import { base } from '$lib/base' import { UserService } from '$lib/gen' import { sendUserToast } from '$lib/toast' import { Button } from '$lib/components/common' @@ -106,7 +105,7 @@ // Read by the OAuth callback: a provider asserting another address is refused // rather than opening a second account under it (see oauth2_ee.rs). document.cookie = `finish_setup=${encodeURIComponent(email)}; path=/; max-age=600; SameSite=Lax` - window.location.assign(`${base}/api/oauth/login/${login.type}`) + window.location.assign(`/api/oauth/login/${login.type}`) }} > Continue with {login.displayName} diff --git a/frontend/src/lib/components/sidebar/MenuLink.svelte b/frontend/src/lib/components/sidebar/MenuLink.svelte index 1c6b7ec715..ebe4a8b768 100644 --- a/frontend/src/lib/components/sidebar/MenuLink.svelte +++ b/frontend/src/lib/components/sidebar/MenuLink.svelte @@ -3,7 +3,6 @@ import type { MenubarMenuElements } from '@melt-ui/svelte' import { navigating, page } from '$app/stores' import Popover from '../Popover.svelte' - import { base } from '$app/paths' import { triggerableByAI } from '$lib/actions/triggerableByAI.svelte' import { goto } from '$app/navigation' import { twMerge } from 'tailwind-merge' @@ -40,7 +39,7 @@ let isSelected = $state(false) navigating.subscribe(() => { - if (href === `${base}/`) { + if (href === '/') { isSelected = $page.url.pathname === href } else { isSelected = $page.url.pathname.startsWith(href) diff --git a/frontend/src/lib/components/sidebar/SettingsMenu.svelte b/frontend/src/lib/components/sidebar/SettingsMenu.svelte index fed773c84c..95dc03992c 100644 --- a/frontend/src/lib/components/sidebar/SettingsMenu.svelte +++ b/frontend/src/lib/components/sidebar/SettingsMenu.svelte @@ -21,7 +21,6 @@ KeyRound, GraduationCap } from 'lucide-svelte' - import { base } from '$app/paths' import { goto } from '$lib/navigation' import { type Item } from '$lib/utils' import { logout } from '$lib/logoutKit' @@ -192,12 +191,12 @@ icon: Building, // The `workspace` query param switches the app to the target // workspace on arrival (full loads and client-side navs alike). - href: `${base}/workspace_settings?workspace=${workspaceSettingsTarget}` + href: `/workspace_settings?workspace=${workspaceSettingsTarget}` } : { displayName: `${currentWs?.name ?? $workspaceStore ?? 'Workspace'} settings`, icon: Building, - href: `${base}/workspace_settings` + href: '/workspace_settings' } ] : []), @@ -256,7 +255,7 @@ { displayName: 'Take the tour', icon: GraduationCap, - action: () => goto(`${base}/?${TOUR_PARAM}=${TOUR_PARAM_VALUE}`) + action: () => goto(`/?${TOUR_PARAM}=${TOUR_PARAM_VALUE}`) } ] : []), @@ -277,9 +276,9 @@ ]) const logsItems = $derived<Item[]>([ - { displayName: 'Audit logs', icon: Eye, href: `${base}/audit_logs` }, + { displayName: 'Audit logs', icon: Eye, href: '/audit_logs' }, ...($devopsRole - ? [{ displayName: 'Service logs', icon: Logs, href: `${base}/service_logs` }] + ? [{ displayName: 'Service logs', icon: Logs, href: '/service_logs' }] : []), ...($enterpriseLicense ? [ @@ -317,7 +316,7 @@ <MenuLink class="!text-xs" label="Workers" - href="{base}/workers" + href="/workers" icon={ServerCog} disabled={!sidebarPageAllowed($userStore?.operator, currentWs, 'workers')} {isCollapsed} @@ -363,7 +362,7 @@ <MenuLink class="!text-xs" label="Audit logs" - href="{base}/audit_logs" + href="/audit_logs" icon={Eye} disabled={!sidebarPageAllowed($userStore?.operator, currentWs, 'audit_logs')} {isCollapsed} diff --git a/frontend/src/lib/components/sidebar/SidebarContent.svelte b/frontend/src/lib/components/sidebar/SidebarContent.svelte index d8f27ff0c6..7187709d2c 100644 --- a/frontend/src/lib/components/sidebar/SidebarContent.svelte +++ b/frontend/src/lib/components/sidebar/SidebarContent.svelte @@ -41,7 +41,6 @@ import DiscordIcon from '../icons/brands/Discord.svelte' import ConfirmationModal from '../common/confirmationModal/ConfirmationModal.svelte' import { twMerge } from 'tailwind-merge' - import { base } from '$lib/base' import { page } from '$app/state' import SideBarNotification from './SideBarNotification.svelte' import KafkaIcon from '../icons/triggers/KafkaIcon.svelte' @@ -227,7 +226,7 @@ NAV_PAGES.filter((p) => p.label in MAIN_MENU_EXTRAS) .map((p) => ({ label: p.label, - href: p.path === '/' ? `${base}/` : `${base}${p.path}`, + href: p.path === '/' ? `/` : `${p.path}`, icon: p.icon, disabled: p.operatorKey ? !allows(p.operatorKey) : false, ...MAIN_MENU_EXTRAS[p.label] @@ -341,7 +340,7 @@ label: config?.serviceDisplayName || service, href: `/native_triggers/${service}`, icon: icon, - disabled: $userStore?.operator, + disabled: !allows('triggers'), kind: service, aiId: `sidebar-menu-link-${service}`, aiDescription: `Button to navigate to ${config?.serviceDisplayName || service} triggers` @@ -353,7 +352,7 @@ let triggerMenuLinks = $derived([ { label: 'Schedules', - href: `${base}/schedules`, + href: '/schedules', icon: Calendar, disabled: !SIDEBAR_SHOW_SCHEDULES || !allows('schedules'), aiId: 'sidebar-menu-link-schedules', @@ -368,6 +367,10 @@ return !page.url.pathname.includes(link.href) && !$usedTriggerKinds.includes(link.kind) }) ) + let showAddTriggerMenu = $derived(extraTriggerLinks.length > 0 && allows('triggers')) + let showTriggersGroup = $derived( + showAddTriggerMenu || triggerMenuLinks.some((link) => !link.disabled) + ) // Admins, superadmins, and fork creators reach workspace settings (the latter // for the fork members screen; see isForkOwner / backend authorize_fork_owner_add_user). const canManageWorkspace = $derived( @@ -399,7 +402,7 @@ ? [ { label: 'Workspace', - href: `${base}/workspace_settings`, + href: '/workspace_settings', icon: FolderCog, aiId: 'sidebar-menu-link-workspace', aiDescription: 'Button to navigate to workspace settings', @@ -437,7 +440,7 @@ }, { label: 'Workers', - href: `${base}/workers`, + href: '/workers', icon: ServerCog, disabled: !allows('workers'), aiId: 'sidebar-menu-link-workers', @@ -452,7 +455,7 @@ subItems: [ { label: 'Audit logs', - href: `${base}/audit_logs`, + href: '/audit_logs', icon: Eye, aiId: 'sidebar-menu-link-audit-logs', aiDescription: 'Button to navigate to audit logs' @@ -461,7 +464,7 @@ ? [ { label: 'Service logs', - href: `${base}/service_logs`, + href: '/service_logs', icon: Logs, aiId: 'sidebar-menu-link-service-logs', aiDescription: 'Button to navigate to service logs' @@ -486,7 +489,7 @@ } : { label: 'Audit logs', - href: `${base}/audit_logs`, + href: '/audit_logs', icon: Eye, disabled: !allows('audit_logs'), aiId: 'sidebar-menu-link-audit-logs', @@ -503,6 +506,8 @@ <MenuLink class="!text-xs" {...menuLink} {isCollapsed} /> {/each} </div> + {/if} + {#if showMain && showTriggersGroup} <div class="pt-4"> {#if isCollapsed} <div class="text-secondary text-[0.5rem] uppercase transition-opacity opacity-0"> @@ -530,7 +535,7 @@ {#each triggerMenuLinks as menuLink (menuLink.href ?? menuLink.label)} <MenuLink class="!text-xs" {...menuLink} {isCollapsed} /> {/each} - {#if extraTriggerLinks.length > 0 && allows('triggers')} + {#if showAddTriggerMenu} <Menu {createMenu} usePointerDownOutside> {#snippet triggr({ trigger })} <MeltButton diff --git a/frontend/src/lib/components/sidebar/WorkspacePickerBody.svelte b/frontend/src/lib/components/sidebar/WorkspacePickerBody.svelte index e25dc83286..c70fef70a4 100644 --- a/frontend/src/lib/components/sidebar/WorkspacePickerBody.svelte +++ b/frontend/src/lib/components/sidebar/WorkspacePickerBody.svelte @@ -13,9 +13,12 @@ workspaceUsageStore, clearWorkspaceFromStorage, globalForkModal, - enterpriseLicense + enterpriseLicense, + type UserWorkspace } from '$lib/stores' - import { Check, ChevronDown, ChevronRight, Plus, Settings } from 'lucide-svelte' + import { Check, ChevronDown, ChevronRight, Plus, Search, Settings } from 'lucide-svelte' + import TextInput from '$lib/components/text_input/TextInput.svelte' + import SearchItems from '$lib/components/SearchItems.svelte' import { forkAccentStyle } from '$lib/utils/forkColor' import { SvelteSet } from 'svelte/reactivity' import { CopyButton } from '$lib/components/common' @@ -24,7 +27,6 @@ import WorkspaceIcon from '$lib/components/workspace/WorkspaceIcon.svelte' import { fixupUrlAfterWorkspaceSwitch } from './workspaceSwitchUrl' import { goto } from '$lib/navigation' - import { base } from '$lib/base' import { page } from '$app/state' import { switchWorkspace } from '$lib/storeUtils' import MultiplayerMenu from './MultiplayerMenu.svelte' @@ -137,20 +139,23 @@ // (standalone pages such as svix webhook creation), so // there forks must stay directly selectable — list the full hierarchy // unconditionally. - const hierarchy = $derived($userWorkspaces ? buildWorkspaceHierarchy($userWorkspaces) : []) + const hierarchy = $derived( + $userWorkspaces ? buildWorkspaceHierarchy($userWorkspaces, $userStore?.email) : [] + ) const expandedFamilies = new SvelteSet<string>() // Root ids with at least one fork — only they get the expand chevron. // hierarchy is a DFS (parent before child), so a depth>0 row belongs to the // last depth-0 row seen. - const familiesWithForks = $derived.by(() => { + function rootsWithForks(rows: typeof hierarchy): Set<string> { const withForks = new Set<string>() let rootId: string | undefined - for (const h of hierarchy) { + for (const h of rows) { if (h.depth === 0) rootId = h.workspace.id else if (rootId) withForks.add(rootId) } return withForks - }) + } + const familiesWithForks = $derived(rootsWithForks(hierarchy)) // Gate for the "Workspace fork" entry pinned below the list (the global fork // modal carries its own base-workspace picker). Hidden on non-premium cloud, // in the admins workspace, or when forking is disabled. @@ -168,16 +173,54 @@ return ancestors.at(-1) ?? $userWorkspaces?.find((w) => w.id === id) }) + const SEARCH_THRESHOLD = 8 + const showSearch = $derived(($userWorkspaces?.length ?? 0) > SEARCH_THRESHOLD) + let searchFilter = $state('') + let searchMatches: (UserWorkspace & { marked?: string })[] | undefined = $state() + const searching = $derived(showSearch && searchFilter.trim() !== '') + const markedNames = $derived( + new Map(searching ? searchMatches?.map((w) => [w.id, w.marked]) : undefined) + ) + + // While searching, every family is open: a match is listed under the ancestors that lead to + // it, so a fork still reads as part of its family. + const searchedRows = $derived.by(() => { + const matched = new Set(searchMatches?.map((w) => w.id)) + const keep = new Set<string>() + const path: string[] = [] + for (const h of hierarchy) { + path.length = h.depth + path.push(h.workspace.id) + if (matched.has(h.workspace.id)) path.forEach((id) => keep.add(id)) + } + return hierarchy.filter((h) => keep.has(h.workspace.id)) + }) + + // A search opens every family that has a matching fork; the chevron can still close one. Kept + // apart from expandedFamilies so clearing the search restores the families as they were. + const collapsedInSearch = new SvelteSet<string>() + function isExpanded(rootId: string): boolean { + return searching ? !collapsedInSearch.has(rootId) : expandedFamilies.has(rootId) + } + function toggleFamily(rootId: string) { + const set = searching ? collapsedInSearch : expandedFamilies + if (set.has(rootId)) set.delete(rootId) + else set.add(rootId) + } + // Roots with at least one fork among the rows the list can show right now. + const expandableFamilies = $derived(searching ? rootsWithForks(searchedRows) : familiesWithForks) + const familyWorkspaces = $derived.by(() => { let rootId: string | undefined + const rows = searching ? searchedRows : hierarchy const visible = strictWorkspaceSelect - ? hierarchy - : hierarchy.filter((h) => { + ? rows + : rows.filter((h) => { if (h.depth === 0) { rootId = h.workspace.id return true } - return !!rootId && expandedFamilies.has(rootId) + return !!rootId && isExpanded(rootId) }) // The family the user is standing in leads the list, its forks travelling with it: the // workspace they are in is the one they look for first, and the one the tick is on. @@ -194,12 +237,112 @@ return [active, ...families].flatMap((f) => f.rows) }) + // With the search field shown, focus stays in it: the arrows move this highlight rather than + // melt's roving focus, which would take the keys away from the field. Until the user arrows or + // hovers, it rests on the best-ranked visible match (not the first row, which may only be a + // match's ancestor), so Enter's target is always the highlighted row. The highlight walks every + // element carrying `data-nav-id` — workspace rows, then the actions below them — in DOM order. + const ACTION_PREFIX = 'action:' + let rootEl: HTMLDivElement | undefined = $state() + let pickedId: string | undefined = $state() + const navIds = $derived( + familyWorkspaces.filter((h) => !h.workspace.disabled).map((h) => h.workspace.id) + ) + const highlightedId = $derived( + !showSearch + ? undefined + : pickedId && (pickedId.startsWith(ACTION_PREFIX) || navIds.includes(pickedId)) + ? pickedId + : searching + ? searchMatches?.find((w) => navIds.includes(w.id))?.id + : undefined + ) + + function actionNavId(action: string): string | undefined { + return showSearch ? ACTION_PREFIX + action : undefined + } + + function actionClass(action: string): string { + return twMerge(itemClass, highlightedId === ACTION_PREFIX + action && 'bg-surface-hover') + } + + function navElement(id: string): HTMLElement | null | undefined { + return rootEl?.querySelector<HTMLElement>(`[data-nav-id="${CSS.escape(id)}"]`) + } + + function moveHighlight(step: 1 | -1) { + const order = Array.from(rootEl?.querySelectorAll('[data-nav-id]') ?? []).map( + (el) => el.getAttribute('data-nav-id')! + ) + if (order.length === 0) return + const at = highlightedId ? order.indexOf(highlightedId) : -1 + const next = + at === -1 + ? step === 1 + ? 0 + : order.length - 1 + : Math.min(order.length - 1, Math.max(0, at + step)) + pickedId = order[next] + navElement(order[next])?.scrollIntoView({ block: 'nearest' }) + } + + function onSearchKeydown(e: KeyboardEvent) { + // An IME uses arrows, Enter and Escape to pick and confirm a candidate; those keys are its own. + if (e.isComposing || e.keyCode === 229) { + e.stopPropagation() + return + } + if (e.key === 'Escape') return + e.stopPropagation() + if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { + e.preventDefault() + moveHighlight(e.key === 'ArrowDown' ? 1 : -1) + } else if (e.key === 'Enter') { + const target = highlightedId + if (!target) return + e.preventDefault() + if (target.startsWith(ACTION_PREFIX)) { + navElement(target)?.querySelector<HTMLElement>('[role="menuitem"]')?.click() + return + } + closeMenu?.() + void tick().then(() => toggleSwitchWorkspace(target)) + } + } + + // A new query starts from its own best match with every matching family open. + function onSearchInput() { + pickedId = undefined + collapsedInSearch.clear() + } + + // melt focuses an item on pointermove and its menu on pointerleave; stopped here, before they + // reach the item, so hovering the list leaves focus in the search field. + function keepSearchFocus(e: PointerEvent) { + if (!showSearch) return + e.stopPropagation() + if (e.type === 'pointermove') { + const id = (e.target as HTMLElement | null) + ?.closest('[data-nav-id]') + ?.getAttribute('data-nav-id') + if (id) pickedId = id + } + } + + // melt still moves focus onto an item in other cases, the first one when the menu is opened from + // the keyboard among them; with the search shown, focus belongs to the field. + let searchWrapEl: HTMLDivElement | undefined = $state() + function returnFocusToSearch(e: FocusEvent) { + if (!showSearch || !(e.target as HTMLElement | null)?.closest('[role="menuitem"]')) return + searchWrapEl?.querySelector('input')?.focus() + } + // ArrowRight/ArrowLeft expand/collapse the keyboard-highlighted family (melt // stamps data-highlighted on the item; the row wrapper carries the workspace // id). Capture phase, so melt's menubar left/right (adjacent-menu switching) // doesn't fire when the keypress means expansion here. function onExpandKeydown(e: KeyboardEvent) { - if (strictWorkspaceSelect) return + if (strictWorkspaceSelect || e.target instanceof HTMLInputElement) return if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return // Scoped inside a row wrapper: the menubar trigger also carries // data-highlighted while its menu is open. @@ -235,212 +378,288 @@ // font-normal is explicit: href-less MenuItems render as <button>, which the // global stylesheet makes semibold, unlike the <a> the href entries get. const itemClass = - 'text-primary font-normal w-full flex flex-row gap-2 px-4 py-2 text-xs hover:bg-surface-hover hover:text-primary data-[highlighted]:bg-surface-hover data-[highlighted]:text-primary' + 'text-primary font-normal w-full flex flex-row gap-2 px-4 py-2 text-xs focus:outline-none hover:bg-surface-hover hover:text-primary data-[highlighted]:bg-surface-hover data-[highlighted]:text-primary' </script> <svelte:window onkeydowncapture={onExpandKeydown} /> -<div class="divide-y" role="none"> - <!-- The list scrolls internally so the sections below (+ Workspace, +<div + bind:this={rootEl} + role="none" + onpointermovecapture={keepSearchFocus} + onpointerleavecapture={keepSearchFocus} + onfocusincapture={returnFocusToSearch} +> + <div class="divide-y" role="none"> + {#if showSearch} + <SearchItems + filter={searchFilter} + items={$userWorkspaces} + bind:filteredItems={searchMatches} + f={(w) => w.name + ' (' + w.id + ')'} + /> + <!-- Keys typed here must not reach melt: its menu typeahead would focus the first item + starting with the typed letter. A native listener, because Svelte delegates `onkeydown` + to the root, which runs after melt's listener on the menu element. --> + <div + bind:this={searchWrapEl} + class="px-2 pt-1 pb-2" + role="none" + {@attach (el) => { + el.addEventListener('keydown', onSearchKeydown) + return () => el.removeEventListener('keydown', onSearchKeydown) + }} + > + <div class="relative"> + <TextInput + bind:value={searchFilter} + size="sm" + inputProps={{ + placeholder: 'Search workspaces...', + autofocus: true, + oninput: onSearchInput + }} + class="!pr-8" + /> + <Search + size={14} + class="text-secondary absolute right-2 top-1/2 -translate-y-1/2 pointer-events-none" + /> + </div> + </div> + {/if} + <!-- The list scrolls internally so the sections below (+ Workspace, Workspace fork, All workspaces) stay visible however long it gets. --> - <div class="py-1 overflow-y-auto max-h-[min(50vh,26rem)]"> - {#each familyWorkspaces as { workspace, depth, isForked, parentName }} - {@const isActive = $workspaceStore === workspace.id} - {@const forkAccent = isForked ? forkAccentStyle(workspace.color) : undefined} - <!-- Selection is a trailing tick (single-choice picker convention). A + <div class="py-1 overflow-y-auto max-h-[min(50vh,26rem)]"> + {#if searching && familyWorkspaces.length === 0} + <div class="px-3 py-2 text-xs text-secondary">No workspaces match your search</div> + {/if} + {#each familyWorkspaces as { workspace, depth, isForked, parentName, separatorBefore } (workspace.id)} + {@const isActive = $workspaceStore === workspace.id} + {@const forkAccent = isForked ? forkAccentStyle(workspace.color) : undefined} + <!-- A search filters out sibling forks, so the divider between the user's own forks + and the others would mark the wrong boundary. --> + {#if separatorBefore && !searching} + <div + class="my-1 border-t border-border-light" + style:margin-left={`${(depth - 1) * 16}px`} + role="separator" + ></div> + {/if} + <!-- Selection is a trailing tick (single-choice picker convention). A collapsed root carries the tick while one of its forks is active — the fork row is hidden and its family is the only trace of the selection; expanding moves the tick to the fork itself. --> - {@const isSelected = - isActive || - (!strictWorkspaceSelect && - depth === 0 && - lineageRoot?.id === workspace.id && - !expandedFamilies.has(workspace.id))} - {@const expandable = - !strictWorkspaceSelect && depth === 0 && familiesWithForks.has(workspace.id)} - <!-- The expand chevron sits OUTSIDE the melt item: melt activates items + {@const isSelected = + isActive || + (!strictWorkspaceSelect && + depth === 0 && + lineageRoot?.id === workspace.id && + !isExpanded(workspace.id) && + (!searching || searchedRows.some((h) => h.workspace.id === $workspaceStore)))} + {@const expandable = + !strictWorkspaceSelect && depth === 0 && expandableFamilies.has(workspace.id)} + <!-- The expand chevron sits OUTSIDE the melt item: melt activates items via document-level handlers, so a nested button can't stop the row's navigate-and-close with stopPropagation. As a sibling it toggles the family without selecting the row or closing the menu. --> - <!-- Hover/keyboard-highlight backgrounds live on the wrapper (the + <!-- Hover/keyboard-highlight backgrounds live on the wrapper (the highlight via :has(), since melt puts data-highlighted on the item) so they span the full row, chevron included; the chevron keeps only its own hover tint. The active workspace is marked by its row's check icon, not a background or text accent. --> - <div - data-workspace-id={workspace.id} - class={twMerge( - 'group flex items-center min-w-0 w-full', - workspace.disabled - ? '' - : 'hover:bg-surface-hover [&:has([data-highlighted])]:bg-surface-hover' - )} - > - <MenuItem + <div + data-workspace-id={workspace.id} + data-nav-id={showSearch && !workspace.disabled ? workspace.id : undefined} class={twMerge( - 'text-xs min-w-0 flex-1 overflow-hidden flex flex-col py-1.5 px-3', - workspace.disabled && 'opacity-50 cursor-not-allowed', - isActive ? 'cursor-default' : workspace.disabled ? '' : 'cursor-pointer' + 'group flex items-center min-w-0 w-full', + workspace.disabled + ? '' + : showSearch + ? highlightedId === workspace.id && 'bg-surface-hover' + : 'hover:bg-surface-hover [&:has([data-highlighted])]:bg-surface-hover' )} - href={workspace.disabled ? undefined : workspaceHref(workspace.id)} - onClick={(e) => onWorkspaceItemClick(e, workspace)} - {item} > - <div class="flex items-center justify-between gap-2 min-w-0 w-full"> - <div class="flex items-center gap-2 min-w-0" style:padding-left={`${depth * 16}px`}> - <WorkspaceIcon - workspaceColor={workspace.color} - {isForked} - isDevWorkspace={workspace.is_dev_workspace} - devWorkspaceLabel={workspace.dev_workspace_label} - {parentName} - padding="p-1" - /> - <div class="min-w-0 flex-1"> - <div class="flex items-center gap-1 min-w-0"> - <div - class="truncate text-left text-xs font-normal {forkAccent - ? 'text-[color:var(--fork-accent-text)] dark:text-[color:var(--fork-accent-text-dark)]' - : 'text-primary'}" - style={forkAccent} - title={workspace.name} - > - {workspace.name}{workspace.disabled ? ' (user disabled)' : ''} + <MenuItem + class={twMerge( + 'text-xs min-w-0 flex-1 overflow-hidden flex flex-col py-1.5 px-3 focus:outline-none', + workspace.disabled && 'opacity-50 cursor-not-allowed', + isActive ? 'cursor-default' : workspace.disabled ? '' : 'cursor-pointer' + )} + href={workspace.disabled ? undefined : workspaceHref(workspace.id)} + onClick={(e) => onWorkspaceItemClick(e, workspace)} + {item} + > + <div class="flex items-center justify-between gap-2 min-w-0 w-full"> + <div class="flex items-center gap-2 min-w-0" style:padding-left={`${depth * 16}px`}> + <WorkspaceIcon + workspaceColor={workspace.color} + {isForked} + isDevWorkspace={workspace.is_dev_workspace} + devWorkspaceLabel={workspace.dev_workspace_label} + {parentName} + padding="p-1" + /> + <div class="min-w-0 flex-1"> + <div class="flex items-center gap-1 min-w-0"> + <div + class="truncate text-left text-xs font-normal {forkAccent + ? 'text-[color:var(--fork-accent-text)] dark:text-[color:var(--fork-accent-text-dark)]' + : 'text-primary'}" + style={forkAccent} + title={workspace.name} + > + {#if markedNames.get(workspace.id)} + <!-- SearchItems escapes the text; only its <mark> tags are markup. --> + {@html markedNames.get(workspace.id)} + {:else} + {workspace.name} + {/if}{workspace.disabled ? ' (user disabled)' : ''} + </div> + {#if workspace.is_dev_workspace} + <DevWorkspaceBadge + label={workspace.dev_workspace_label} + color={workspace.color} + fallbackClass="dark:bg-surface-accent-primary text-white dark:text-white" + class="text-3xs px-1 py-0" + /> + {/if} </div> - {#if workspace.is_dev_workspace} - <DevWorkspaceBadge - label={workspace.dev_workspace_label} - color={workspace.color} - fallbackClass="dark:bg-surface-accent-primary text-white dark:text-white" - class="text-3xs px-1 py-0" - /> + {#if ambiguousNames.has(workspace.name) && !markedNames.has(workspace.id)} + <div class="truncate text-left text-2xs text-tertiary" title={workspace.id}> + {workspace.id} + </div> {/if} </div> - {#if ambiguousNames.has(workspace.name)} - <div class="truncate text-left text-2xs text-tertiary" title={workspace.id}> - {workspace.id} - </div> - {/if} </div> + {#if isSelected} + <Check size={14} class="shrink-0 ml-2 text-accent" /> + {/if} </div> - {#if isSelected} - <Check size={14} class="shrink-0 ml-2 text-accent" /> - {/if} - </div> - </MenuItem> - <!-- Hover-revealed like the fork picker's rows; a flex sibling of the melt + </MenuItem> + <!-- Hover-revealed like the fork picker's rows; a flex sibling of the melt item (nested buttons are invalid HTML) that always occupies its slot so nothing shifts on hover. --> - <div - class="shrink-0 opacity-0 group-hover:opacity-100 focus-within:opacity-100 transition-opacity" - > - <CopyButton value={workspace.id} title={`Copy id: ${workspace.id}`} /> - </div> - {#if expandable} - {@const expanded = expandedFamilies.has(workspace.id)} - <button - type="button" - title={expanded ? 'Hide forks' : 'Show forks'} - aria-expanded={expanded} - class="shrink-0 mr-1 px-2 self-stretch flex items-center rounded text-tertiary hover:bg-surface-hover hover:text-primary" - onclick={() => { - if (expanded) expandedFamilies.delete(workspace.id) - else expandedFamilies.add(workspace.id) - }} + <div + class="shrink-0 opacity-0 group-hover:opacity-100 focus-within:opacity-100 transition-opacity" > - {#if expanded} - <ChevronDown size={14} /> - {:else} - <ChevronRight size={14} /> - {/if} - </button> - {:else} - <!-- Reserve the expand-chevron's slot on fork-less rows so the hover copy + <CopyButton value={workspace.id} title={`Copy id: ${workspace.id}`} /> + </div> + {#if expandable} + {@const expanded = isExpanded(workspace.id)} + <!-- mousedown is cancelled so the click leaves focus in the search field. --> + <button + type="button" + title={expanded ? 'Hide forks' : 'Show forks'} + aria-expanded={expanded} + class="shrink-0 mr-1 px-2 self-stretch flex items-center rounded text-tertiary hover:bg-surface-hover hover:text-primary" + onmousedown={(e) => showSearch && e.preventDefault()} + onclick={() => toggleFamily(workspace.id)} + > + {#if expanded} + <ChevronDown size={14} /> + {:else} + <ChevronRight size={14} /> + {/if} + </button> + {:else} + <!-- Reserve the expand-chevron's slot on fork-less rows so the hover copy button lines up with the forked rows' and never sits flush against the menu's right edge. Matches the chevron's px-2 (30px) + mr-1. --> - <div class="shrink-0 mr-1 w-[30px]" aria-hidden="true"></div> + <div class="shrink-0 mr-1 w-[30px]" aria-hidden="true"></div> + {/if} + </div> + {/each} + </div> + {#if (isCloudHosted() || $superadmin || canForkHere) && !strictWorkspaceSelect} + <div class="py-1" role="none"> + {#if isCloudHosted() || $superadmin} + <div role="none" data-nav-id={actionNavId('create')}> + <MenuItem href="/user/create_workspace" class={actionClass('create')} {item}> + <Plus size={16} /> + Workspace + </MenuItem> + </div> + {/if} + {#if canForkHere} + <div role="none" data-nav-id={actionNavId('fork')}> + <MenuItem + class={actionClass('fork')} + onClick={() => (globalForkModal.val = { opened: true })} + {item} + > + <Plus size={16} /> + Workspace fork + </MenuItem> + </div> {/if} </div> - {/each} + {/if} + {#if canManageWorkspace && !strictWorkspaceSelect} + <div class="py-1" role="none" data-nav-id={actionNavId('settings')}> + <MenuItem + href="/workspace_settings?workspace={$workspaceStore}" + class={actionClass('settings')} + {item} + > + <Settings size={16} /> + {(activeWorkspace && ambiguousNames.has(activeWorkspace.name) + ? activeWorkspace.id + : activeWorkspace?.name) ?? $workspaceStore} settings + </MenuItem> + </div> + {/if} + {#if !strictWorkspaceSelect} + <div class="py-1" role="none" data-nav-id={actionNavId('all')}> + <MenuItem + href="/user/workspaces" + onClick={() => clearWorkspaceFromStorage()} + class={actionClass('all')} + {item} + > + All workspaces + </MenuItem> + </div> + {/if} </div> - {#if (isCloudHosted() || $superadmin || canForkHere) && !strictWorkspaceSelect} + {#if isCloudHosted() && $isPremiumStore === false && !strictWorkspaceSelect} <div class="py-1" role="none"> - {#if isCloudHosted() || $superadmin} - <MenuItem href="{base}/user/create_workspace" class={itemClass} {item}> - <Plus size={16} /> - Workspace - </MenuItem> + {#if $workspaceStore != 'demo'} + <span class="text-secondary block w-full text-left px-4 py-2 text-xs"> + {$workspaceUsageStore ?? '—'}/1000 free workspace execs + <Tooltip small> + {#snippet text()} + {EXECUTIONS_HINT} + {/snippet} + </Tooltip> + </span> + <div class="w-full bg-gray-200 h-1"> + <div + class="bg-blue-400 h-1" + style="width: {Math.min($workspaceUsageStore ?? 0, 1000) / 10}%" + ></div> + </div> {/if} - {#if canForkHere} - <MenuItem class={itemClass} onClick={() => (globalForkModal.val = { opened: true })} {item}> - <Plus size={16} /> - Workspace fork - </MenuItem> + {#if $userStore?.is_admin} + <div role="none" data-nav-id={actionNavId('upgrade')}> + <MenuItem + class={twMerge( + 'text-secondary block font-normal w-full text-left px-4 py-2 text-sm focus:outline-none hover:bg-gray-100 hover:text-gray-900', + 'data-[highlighted]:bg-gray-100 data-[highlighted]:text-gray-900', + highlightedId === ACTION_PREFIX + 'upgrade' && 'bg-gray-100 text-gray-900' + )} + onClick={() => { + goto('/workspace_settings?tab=premium') + }} + {item} + > + Upgrade + </MenuItem> + </div> {/if} </div> {/if} - {#if canManageWorkspace && !strictWorkspaceSelect} - <div class="py-1" role="none"> - <MenuItem - href="{base}/workspace_settings?workspace={$workspaceStore}" - class={itemClass} - {item} - > - <Settings size={16} /> - {(activeWorkspace && ambiguousNames.has(activeWorkspace.name) - ? activeWorkspace.id - : activeWorkspace?.name) ?? $workspaceStore} settings - </MenuItem> - </div> - {/if} - {#if !strictWorkspaceSelect} - <div class="py-1" role="none"> - <MenuItem - href="{base}/user/workspaces" - onClick={() => clearWorkspaceFromStorage()} - class={itemClass} - {item} - > - All workspaces - </MenuItem> - </div> - {/if} </div> -{#if isCloudHosted() && $isPremiumStore === false && !strictWorkspaceSelect} - <div class="py-1" role="none"> - {#if $workspaceStore != 'demo'} - <span class="text-secondary block w-full text-left px-4 py-2 text-xs"> - {$workspaceUsageStore ?? '—'}/1000 free workspace execs - <Tooltip small> - {#snippet text()} - {EXECUTIONS_HINT} - {/snippet} - </Tooltip> - </span> - <div class="w-full bg-gray-200 h-1"> - <div - class="bg-blue-400 h-1" - style="width: {Math.min($workspaceUsageStore ?? 0, 1000) / 10}%" - ></div> - </div> - {/if} - {#if $userStore?.is_admin} - <MenuItem - class={twMerge( - 'text-secondary block font-normal w-full text-left px-4 py-2 text-sm hover:bg-gray-100 hover:text-gray-900', - 'data-[highlighted]:bg-gray-100 data-[highlighted]:text-gray-900' - )} - onClick={() => { - goto('/workspace_settings?tab=premium') - }} - {item} - > - Upgrade - </MenuItem> - {/if} - </div> -{/if} {#if $enterpriseLicense && !strictWorkspaceSelect} <MultiplayerMenu /> {/if} diff --git a/frontend/src/lib/components/sidebar/WorkspaceScopeHeader.svelte b/frontend/src/lib/components/sidebar/WorkspaceScopeHeader.svelte index aae6e4ce2a..bd5f4e96e4 100644 --- a/frontend/src/lib/components/sidebar/WorkspaceScopeHeader.svelte +++ b/frontend/src/lib/components/sidebar/WorkspaceScopeHeader.svelte @@ -8,7 +8,6 @@ } from '$lib/stores' import { switchWorkspace } from '$lib/storeUtils' import { fixupUrlAfterWorkspaceSwitch } from './workspaceSwitchUrl' - import { base } from '$lib/base' import { workspaceAIClients } from '$lib/components/copilot/lib' import WorkspaceFamilyPicker from '$lib/components/sessions/WorkspaceFamilyPicker.svelte' import WorkspaceScopeTrigger from '$lib/components/WorkspaceScopeTrigger.svelte' @@ -50,7 +49,7 @@ const canManageWorkspace = $derived( $userStore?.is_admin || $superadmin || isForkOwner(currentWs, $userStore?.email) ) - const settingsHref = $derived(canManageWorkspace ? `${base}/workspace_settings` : undefined) + const settingsHref = $derived(canManageWorkspace ? '/workspace_settings' : undefined) const settingsLabel = $derived(`${currentWs?.name ?? effectiveId ?? 'Workspace'} settings`) function switchWorkspaceDirect(id: string) { diff --git a/frontend/src/lib/components/sidebar/navHandlePlacement.svelte.ts b/frontend/src/lib/components/sidebar/navHandlePlacement.svelte.ts index 5fb7b43860..8648961ef6 100644 --- a/frontend/src/lib/components/sidebar/navHandlePlacement.svelte.ts +++ b/frontend/src/lib/components/sidebar/navHandlePlacement.svelte.ts @@ -6,6 +6,13 @@ let opener: (() => void) | undefined // Closing it once the pointer is off both the handle and the card, which the layout owns because // the card is its markup. let hoverClose: { schedule: () => void; cancel: () => void } | undefined +type CardState = { + isOpen: () => boolean + isPinned: () => boolean + pin: () => void + close: () => void +} +let card: CardState | undefined // Where the card's top edge goes: the header's bottom edge, so the two meet in a line rather than // the card starting at whatever height the control that opened it happens to have. Measured at open @@ -21,10 +28,34 @@ export const navHandleSlot = { get cardTop(): number { return cardTop }, - /** The root layout owns the card, so it registers how to open and hover-close it. */ - setOpener(open: () => void, close?: { schedule: () => void; cancel: () => void }) { + /** The card is open and pinned, so the handle shows as selected. Reactive. */ + get pinned(): boolean { + return !!card?.isOpen() && card.isPinned() + }, + /** The root layout owns the card, so it registers how to open, pin, close and hover-close it. */ + setOpener( + open: () => void, + close?: { schedule: () => void; cancel: () => void }, + state?: CardState + ) { opener = open hoverClose = close + card = state + }, + /** + * A click on the handle pins the card, opening it first if it is closed: a pinned card stays + * when the pointer leaves, until a press on the page, Esc, or the next click here closes it. A + * card the pointer opened is not pinned yet, so the click that follows the hover pins it — and + * a touch tap, which sends that mouseenter just before its click, pins it too. + */ + toggle(anchor?: Element | null) { + if (card?.isOpen() && card.isPinned()) { + card.close() + return + } + if (!card?.isOpen()) this.open(anchor) + hoverClose?.cancel() + card?.pin() }, /** Pointer left the handle: close, unless it lands on the card before the delay is up. */ scheduleClose() { diff --git a/frontend/src/lib/components/sidebar/navPages.test.ts b/frontend/src/lib/components/sidebar/navPages.test.ts index 6e68912a15..e2e849ac6b 100644 --- a/frontend/src/lib/components/sidebar/navPages.test.ts +++ b/frontend/src/lib/components/sidebar/navPages.test.ts @@ -2,21 +2,17 @@ import { describe, it, expect } from 'vitest' import { navPageFor } from './navPages' describe('navPageFor', () => { - it('names the page a route belongs to, under the app base', () => { - expect(navPageFor('/base/runs', '/base')?.label).toBe('Runs') - }) - it('keeps an item route on its page', () => { - expect(navPageFor('/runs/f/demo/x', '')?.label).toBe('Runs') + expect(navPageFor('/runs/f/demo/x')?.label).toBe('Runs') }) it('does not let Home swallow every route', () => { - expect(navPageFor('/audit_logs', '')?.label).toBe('Audit logs') - expect(navPageFor('/', '')?.label).toBe('Home') + expect(navPageFor('/audit_logs')?.label).toBe('Audit logs') + expect(navPageFor('/')?.label).toBe('Home') }) it('falls back to the first segment for a route the table does not name', () => { - expect(navPageFor('/service_logs/x', '')).toMatchObject({ + expect(navPageFor('/service_logs/x')).toMatchObject({ label: 'Service logs', path: '/service_logs' }) diff --git a/frontend/src/lib/components/sidebar/navPages.ts b/frontend/src/lib/components/sidebar/navPages.ts index b9dc2eff63..385b93abcc 100644 --- a/frontend/src/lib/components/sidebar/navPages.ts +++ b/frontend/src/lib/components/sidebar/navPages.ts @@ -51,8 +51,7 @@ export const NAV_PAGES: NavPage[] = [ * The page a route belongs to. Longest match wins, so `/runs/f/demo/x` is still Runs, and a route * the table does not name falls back to its first segment (`/service_logs` → "Service logs"). */ -export function navPageFor(pathname: string, base: string): NavPage | undefined { - const path = pathname.startsWith(base) ? pathname.slice(base.length) || '/' : pathname +export function navPageFor(path: string): NavPage | undefined { const match = NAV_PAGES.filter( (p) => p.path === path || (p.path !== '/' && path.startsWith(p.path + '/')) ).sort((a, b) => b.path.length - a.path.length)[0] diff --git a/frontend/src/lib/components/sidebar/workspaceMenuHref.ts b/frontend/src/lib/components/sidebar/workspaceMenuHref.ts index 589326c0f6..707104955d 100644 --- a/frontend/src/lib/components/sidebar/workspaceMenuHref.ts +++ b/frontend/src/lib/components/sidebar/workspaceMenuHref.ts @@ -1,5 +1,3 @@ -import { base } from '$lib/base' - // Href for a workspace-switch link in the sidebar WorkspaceMenu: stay on the // current path and just swap the `workspace` query param, so a modifier/middle // click (open in new tab, which bypasses the onClick fast-path) lands on the @@ -20,7 +18,7 @@ export function workspaceMenuHref(args: { landOnHome?: boolean }): string { if (args.landOnHome) { - return `${base}/?workspace=${encodeURIComponent(args.id)}` + return `/?workspace=${encodeURIComponent(args.id)}` } const params = new URLSearchParams(args.searchParams) params.set('workspace', args.id) diff --git a/frontend/src/lib/components/triggers/CaptureSection.svelte b/frontend/src/lib/components/triggers/CaptureSection.svelte index 51382e1a62..4fa2fab5fb 100644 --- a/frontend/src/lib/components/triggers/CaptureSection.svelte +++ b/frontend/src/lib/components/triggers/CaptureSection.svelte @@ -31,7 +31,6 @@ import { formatDateShort } from '$lib/utils' import DisplayResult from '$lib/components/DisplayResult.svelte' import DisplayResultControlBar from '$lib/components/DisplayResultControlBar.svelte' - import { base } from '$lib/base' import Description from '$lib/components/Description.svelte' import { twMerge } from 'tailwind-merge' import { FlaskConical } from 'lucide-svelte' @@ -463,7 +462,6 @@ {#if displayResult && toolbarLocation === 'external'} <DisplayResultControlBar - {base} result={selectedCapture?.main_args} disableTooltips={false} on:open-drawer={() => { diff --git a/frontend/src/lib/components/triggers/TriggerEditorToolbar.svelte b/frontend/src/lib/components/triggers/TriggerEditorToolbar.svelte index ab8b850fa2..b59a925c84 100644 --- a/frontend/src/lib/components/triggers/TriggerEditorToolbar.svelte +++ b/frontend/src/lib/components/triggers/TriggerEditorToolbar.svelte @@ -10,7 +10,7 @@ import type { TriggerMode } from '$lib/gen' import TriggerModeToggle from './TriggerModeToggle.svelte' import OpenInSessionButton from '$lib/components/sessions/OpenInSessionButton.svelte' - import { stripBase, TRIGGER_PAGES, SCHEDULES_PATH } from '$lib/components/sessions/previewPaths' + import { barePath, TRIGGER_PAGES, SCHEDULES_PATH } from '$lib/components/sessions/previewPaths' import { pageDrawerSessionSource } from '../sessions/pageDrawerSession' import { page } from '$app/state' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' @@ -40,6 +40,7 @@ * editor has to pass it: every other editor renders with a `trigger`, * whose `type` is the same value. */ triggerKind?: TriggerType + saveLabel?: string } let { @@ -60,7 +61,8 @@ suspendedJobsModal, disableSuspendedMode = false, triggerPath, - triggerKind + triggerKind, + saveLabel = 'Save' }: Props = $props() const operatingWorkspace = useOperatingWorkspace() const wsId = $derived($operatingWorkspace) @@ -72,7 +74,7 @@ // when it renders in a script/flow editor's Triggers panel, which has the // editor's own button. A trigger being created has no path to deep-link at. const triggerPagePath = $derived.by(() => { - const route = stripBase(page.url.pathname) + const route = barePath(page.url.pathname) if (route === SCHEDULES_PATH) return route return Object.values(TRIGGER_PAGES).some((p) => p.path === route) ? route : undefined }) @@ -120,7 +122,7 @@ }} loading={isLoading} > - Save + {saveLabel} </Button> {/if} {:else} diff --git a/frontend/src/lib/components/triggers/TriggerList.svelte b/frontend/src/lib/components/triggers/TriggerList.svelte index 3a529b7597..1ccbd21d0e 100644 --- a/frontend/src/lib/components/triggers/TriggerList.svelte +++ b/frontend/src/lib/components/triggers/TriggerList.svelte @@ -1,6 +1,5 @@ <script lang="ts"> import { onDestroy, untrack } from 'svelte' - import { base } from '$app/paths' import { page } from '$app/stores' import { AzureTriggerService, @@ -73,7 +72,7 @@ import MqttIcon from '$lib/components/icons/MqttIcon.svelte' import NatsIcon from '$lib/components/icons/NatsIcon.svelte' import TriggerModeToggle from './TriggerModeToggle.svelte' - import { useTriggerLock } from '$lib/operatorWriteRights' + import { useEditRights, useTriggerLock } from '$lib/operatorWriteRights' import { getHttpRoute } from './http/utils' import { getEmailAddress, getEmailDomain } from './email/utils' import { TRIGGER_LIST_CONFIG, type TriggerRow } from './triggerListConfig' @@ -84,6 +83,7 @@ useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' const triggerLock = useTriggerLock() + const editRights = useEditRights() let { triggerKind }: { triggerKind: TriggerKind } = $props() @@ -148,7 +148,7 @@ } function openLink(href: string) { - if (hosted) hosted.openLink(`${base}${href}`) + if (hosted) hosted.openLink(href) else goto(href) } @@ -697,7 +697,7 @@ {@const effectiveMode = draft_only ? 'disabled' : mode} {@const live = isLive(row)} {@const copy = copyUrl(row)} - {@const canEdit = canWrite && !$triggerLock} + {@const canEdit = editRights.canEditItem('trigger', path, extra_perms)} <div class={twMerge( @@ -824,7 +824,7 @@ { displayName: 'Audit logs', icon: Eye, - href: `${base}/audit_logs?resource=${path}` + href: `/audit_logs?resource=${path}` }, { displayName: 'Permissions', diff --git a/frontend/src/lib/components/triggers/TriggerRetriesAndErrorHandler.svelte b/frontend/src/lib/components/triggers/TriggerRetriesAndErrorHandler.svelte index 86dbf31e46..f71205bc13 100644 --- a/frontend/src/lib/components/triggers/TriggerRetriesAndErrorHandler.svelte +++ b/frontend/src/lib/components/triggers/TriggerRetriesAndErrorHandler.svelte @@ -1,9 +1,10 @@ <script lang="ts"> - import type { ErrorHandler, Retry } from '$lib/gen' + import type { Retry } from '$lib/gen' import { enterpriseLicense } from '$lib/stores' import { emptyString } from '$lib/utils' import Alert from '../common/alert/Alert.svelte' import ErrorOrRecoveryHandler from '../ErrorOrRecoveryHandler.svelte' + import type { HandlerDraft } from '../handlerDraft.svelte' import FlowRetries from '../flows/content/FlowRetries.svelte' import Tooltip from '../Tooltip.svelte' @@ -11,18 +12,14 @@ optionTabSelected, itemKind, can_write, - errorHandlerSelected = $bindable(), - error_handler_path = $bindable(), - error_handler_args = $bindable(), + errorHandler = $bindable(), retry = $bindable(), workspace = undefined }: { optionTabSelected: 'error_handler' | 'retries' | string itemKind: 'script' | 'flow' can_write: boolean - errorHandlerSelected: ErrorHandler - error_handler_path: string | undefined - error_handler_args: Record<string, any> + errorHandler: HandlerDraft retry: Retry | undefined workspace?: string } = $props() @@ -42,12 +39,9 @@ errorOrRecovery="error" showScriptHelpText={true} {workspace} - bind:handlerSelected={errorHandlerSelected} - bind:handlerPath={error_handler_path} + bind:draft={errorHandler} toggleText="Alert channel on error" customScriptTemplate="/scripts/add?hub=hub%2F13953%2Fwindmill%2Ftrigger_error_handler_template" - customHandlerKind="script" - bind:handlerExtraArgs={error_handler_args} > {#snippet customTabTooltip()} <Tooltip> diff --git a/frontend/src/lib/components/triggers/amqp/AmqpTriggerEditor.svelte b/frontend/src/lib/components/triggers/amqp/AmqpTriggerEditor.svelte index 9c3ec78ae3..055e9b3be3 100644 --- a/frontend/src/lib/components/triggers/amqp/AmqpTriggerEditor.svelte +++ b/frontend/src/lib/components/triggers/amqp/AmqpTriggerEditor.svelte @@ -21,6 +21,21 @@ drawer?.openNew(is_flow, initial_script_path, defaultValues) } + /** Edit a trigger that exists only as the caller's draft; Save hands the config back. */ + export async function openDraft( + scriptPath: string, + defaults: Record<string, any>, + saved: Record<string, any> | undefined, + onSaveDraft: (cfg: Record<string, any>) => boolean + ) { + open = true + await tickPainted() + drawer?.openNew(false, scriptPath, defaults as any, { + onSaveDraft, + draftConfig: saved + }) + } + let drawer: AmqpTriggerEditorInner | undefined = $state() </script> diff --git a/frontend/src/lib/components/triggers/amqp/AmqpTriggerEditorInner.svelte b/frontend/src/lib/components/triggers/amqp/AmqpTriggerEditorInner.svelte index 7346e285f6..7295ca0c35 100644 --- a/frontend/src/lib/components/triggers/amqp/AmqpTriggerEditorInner.svelte +++ b/frontend/src/lib/components/triggers/amqp/AmqpTriggerEditorInner.svelte @@ -11,8 +11,8 @@ import Path from '$lib/components/Path.svelte' import TriggerRunnablePicker from '$lib/components/triggers/TriggerRunnablePicker.svelte' import { usedTriggerKinds } from '$lib/stores' - import { canWrite, capitalize, emptyString, sendUserToast } from '$lib/utils' - import { useTriggerLock } from '$lib/operatorWriteRights' + import { capitalize, emptyString, sendUserToast } from '$lib/utils' + import { useEditRights } from '$lib/operatorWriteRights' import { withForkConflictRetry } from '$lib/utils/forkConflict' import Section from '$lib/components/Section.svelte' import { Loader2 } from 'lucide-svelte' @@ -22,7 +22,6 @@ type AmqpExchange, type AmqpOptions, type Retry, - type ErrorHandler, type TriggerMode } from '$lib/gen' import AmqpEditorConfigSection from './AmqpEditorConfigSection.svelte' @@ -30,7 +29,8 @@ import TriggerEditorToolbar from '../TriggerEditorToolbar.svelte' import PermissionedAsLine from '../PermissionedAsLine.svelte' import { saveAmqpTriggerFromCfg } from './utils' - import { getHandlerType, handleConfigChange, type Trigger } from '../utils' + import { handleConfigChange, type Trigger } from '../utils' + import { handlerDraftFromStored, handlerDraftToStored } from '../../handlerDraft.svelte' import Tabs from '$lib/components/common/tabs/Tabs.svelte' import Tab from '$lib/components/common/tabs/Tab.svelte' import TriggerRetriesAndErrorHandler from '../TriggerRetriesAndErrorHandler.svelte' @@ -46,7 +46,7 @@ useOperatingUser, useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' - const triggerLock = useTriggerLock() + const editRights = useEditRights() interface Props { useDrawer?: boolean @@ -112,8 +112,9 @@ // The acting user in the operating workspace arrives asynchronously, and an unknown user // refuses — so the editor stays read-only until the lookup lands, which is the safe answer. const can_write = $derived( - (permsPath === undefined || canWrite(permsPath, permsForWrite ?? {}, actingUser)) && - !$triggerLock + permsPath === undefined + ? editRights.roleCanAuthor('trigger') + : editRights.canEditItem('trigger', permsPath, permsForWrite) ) let drawerLoading = $state(true) let showLoading = $state(false) @@ -126,9 +127,10 @@ let permissionedAs = $state<string | undefined>(undefined) let selectedPermissionedAs = $state<string | undefined>(undefined) let preservePermissionedAs = $state(false) - let errorHandlerSelected: ErrorHandler = $state('slack') - let error_handler_path: string | undefined = $state() - let error_handler_args: Record<string, any> = $state({}) + let errorHandler = $state(handlerDraftFromStored('error', undefined)) + const storedErrorHandler = $derived(handlerDraftToStored(errorHandler)) + const error_handler_path = $derived(storedErrorHandler.path) + const error_handler_args = $derived(storedErrorHandler.args) let retry: Retry | undefined = $state() let suspendedJobsModal = $state<TriggerSuspendedJobsModal | null>(null) let originalConfig = $state<Record<string, any> | undefined>(undefined) @@ -172,14 +174,20 @@ is_flow = itemKind === 'flow' }) + // Set by `openNew(…, { onSaveDraft })`: the caller keeps the trigger as its own + // draft, so Save hands it the config instead of writing it. + let saveDraftHandler: ((cfg: Record<string, any>) => boolean) | undefined = $state(undefined) + export async function openEdit( ePath: string, isFlow: boolean, defaultConfig?: Record<string, any>, fixedScriptPath_?: string ) { + saveDraftHandler = undefined // A `whoami` that failed earlier would otherwise pin this workspace to "unknown user". operatingUser.forgetFailures() + editRights.forgetFailures() let loadingTimeout = setTimeout(() => { showLoading = true }, 100) // Do not show loading spinner for the first 100ms @@ -212,8 +220,14 @@ export async function openNew( nis_flow: boolean, fixedScriptPath_?: string, - defaultValues?: Record<string, any> + defaultValues?: Record<string, any>, + opts: { + onSaveDraft?: (cfg: Record<string, any>) => boolean + /** A config this editor saved before, re-applied over the defaults. */ + draftConfig?: Record<string, any> + } = {} ) { + saveDraftHandler = opts.onSaveDraft let loadingTimeout = setTimeout(() => { showLoading = true }, 100) @@ -235,14 +249,18 @@ edit = false dirtyPath = false mode = defaultValues?.mode ?? 'enabled' - error_handler_path = defaultValues?.error_handler_path ?? undefined - error_handler_args = defaultValues?.error_handler_args ?? {} + errorHandler = handlerDraftFromStored( + 'error', + defaultValues?.error_handler_path, + 'script', + defaultValues?.error_handler_args + ) retry = defaultValues?.retry ?? undefined - errorHandlerSelected = getHandlerType(error_handler_path ?? '') permissionedAs = undefined selectedPermissionedAs = undefined preservePermissionedAs = false originalConfig = undefined + if (opts.draftConfig) await loadTriggerConfig(opts.draftConfig) } finally { clearTimeout(loadingTimeout) drawerLoading = false @@ -266,10 +284,13 @@ mode = cfg?.mode ?? 'enabled' permsPath = cfg?.path permsForWrite = cfg?.extra_perms - error_handler_path = cfg?.error_handler_path - error_handler_args = cfg?.error_handler_args ?? {} + errorHandler = handlerDraftFromStored( + 'error', + cfg?.error_handler_path, + 'script', + cfg?.error_handler_args + ) retry = cfg?.retry - errorHandlerSelected = getHandlerType(error_handler_path ?? '') permissionedAs = cfg?.permissioned_as selectedPermissionedAs = cfg?.permissioned_as preservePermissionedAs = !!cfg?.permissioned_as @@ -335,6 +356,11 @@ } async function updateTrigger(): Promise<void> { + if (saveDraftHandler) { + if (!saveDraftHandler($state.snapshot(getSaveCfg()))) return + drawer?.closeDrawer() + return + } deploymentLoading = true const previousPath = initialPath const cfg = getSaveCfg() @@ -431,7 +457,9 @@ ? can_write ? `Edit AMQP trigger ${initialPath}` : `AMQP trigger ${initialPath}` - : 'New AMQP trigger'} + : saveDraftHandler + ? 'Draft AMQP trigger' + : 'New AMQP trigger'} on:close={() => (inline ? onClose?.() : drawer?.closeDrawer())} > {#snippet actions()} @@ -489,6 +517,7 @@ isLoading={deploymentLoading} {isDeployed} onUpdate={updateTrigger} + saveLabel={saveDraftHandler ? 'Save draft' : undefined} {onReset} {onDelete} onToggleMode={handleToggleMode} @@ -645,9 +674,7 @@ {optionTabSelected} {itemKind} {can_write} - bind:errorHandlerSelected - bind:error_handler_path - bind:error_handler_args + bind:errorHandler bind:retry /> {/if} diff --git a/frontend/src/lib/components/triggers/azure/AzureTriggerEditorInner.svelte b/frontend/src/lib/components/triggers/azure/AzureTriggerEditorInner.svelte index 4394a5878f..e0c2008be8 100644 --- a/frontend/src/lib/components/triggers/azure/AzureTriggerEditorInner.svelte +++ b/frontend/src/lib/components/triggers/azure/AzureTriggerEditorInner.svelte @@ -9,18 +9,12 @@ import DrawerContent from '$lib/components/common/drawer/DrawerContent.svelte' import Path from '$lib/components/Path.svelte' import { usedTriggerKinds } from '$lib/stores' - import { canWrite, capitalize, emptyString, sendUserToast } from '$lib/utils' - import { useTriggerLock } from '$lib/operatorWriteRights' + import { capitalize, emptyString, sendUserToast } from '$lib/utils' + import { useEditRights } from '$lib/operatorWriteRights' import { withForkConflictRetry } from '$lib/utils/forkConflict' import { Loader2 } from 'lucide-svelte' import Label from '$lib/components/Label.svelte' - import { - AzureTriggerService, - type AzureMode, - type Retry, - type ErrorHandler, - type TriggerMode - } from '$lib/gen' + import { AzureTriggerService, type AzureMode, type Retry, type TriggerMode } from '$lib/gen' import Section from '$lib/components/Section.svelte' import ScriptPicker from '$lib/components/ScriptPicker.svelte' import Required from '$lib/components/Required.svelte' @@ -29,13 +23,14 @@ import TriggerEditorToolbar from '../TriggerEditorToolbar.svelte' import PermissionedAsLine from '../PermissionedAsLine.svelte' import { saveAzureTriggerFromCfg } from './utils' - import { getHandlerType, handleConfigChange, type Trigger } from '../utils' + import { handleConfigChange, type Trigger } from '../utils' + import { handlerDraftFromStored, handlerDraftToStored } from '../../handlerDraft.svelte' import { deepEqual } from 'fast-equals' import { useTriggerDraftSync } from '../useTriggerDraftSync.svelte' import LocalDraftBanner from '$lib/components/LocalDraftBanner.svelte' import TriggerSuspendedJobsAlert from '../TriggerSuspendedJobsAlert.svelte' import TriggerSuspendedJobsModal from '../TriggerSuspendedJobsModal.svelte' - import { base } from '$lib/base' + import { apiBaseUrl } from '$lib/apiBaseUrl.svelte' import Tabs from '$lib/components/common/tabs/Tabs.svelte' import Tab from '$lib/components/common/tabs/Tab.svelte' import TriggerRetriesAndErrorHandler from '../TriggerRetriesAndErrorHandler.svelte' @@ -45,7 +40,7 @@ useOperatingWorkspace, useOperatingWorkspaceHref } from '$lib/components/operatingWorkspace.svelte' - const triggerLock = useTriggerLock() + const editRights = useEditRights() let drawer: Drawer | undefined = $state(undefined) let initialPath = $state('') @@ -65,8 +60,9 @@ // The acting user in the operating workspace arrives asynchronously, and an unknown user // refuses — so the editor stays read-only until the lookup lands, which is the safe answer. const can_write = $derived( - (permsPath === undefined || canWrite(permsPath, permsForWrite ?? {}, actingUser)) && - !$triggerLock + permsPath === undefined + ? editRights.roleCanAuthor('trigger') + : editRights.canEditItem('trigger', permsPath, permsForWrite) ) let drawerLoading = $state(true) @@ -83,12 +79,13 @@ let permissionedAs = $state<string | undefined>(undefined) let selectedPermissionedAs = $state<string | undefined>(undefined) let preservePermissionedAs = $state(false) - let base_endpoint = $derived(`${window.location.origin}${base}`) + let base_endpoint = $derived(apiBaseUrl()) let optionTabSelected: 'error_handler' | 'retries' = $state('error_handler') - let errorHandlerSelected: ErrorHandler = $state('slack') - let error_handler_path: string | undefined = $state() - let error_handler_args: Record<string, any> = $state({}) + let errorHandler = $state(handlerDraftFromStored('error', undefined)) + const storedErrorHandler = $derived(handlerDraftToStored(errorHandler)) + const error_handler_path = $derived(storedErrorHandler.path) + const error_handler_args = $derived(storedErrorHandler.args) let retry: Retry | undefined = $state() let suspendedJobsModal = $state<TriggerSuspendedJobsModal | null>(null) let originalConfig = $state<Record<string, any> | undefined>(undefined) @@ -160,6 +157,7 @@ ) { // A `whoami` that failed earlier would otherwise pin this workspace to "unknown user". operatingUser.forgetFailures() + editRights.forgetFailures() drawerLoading = true try { drawer?.openDrawer() @@ -209,10 +207,13 @@ edit = false dirtyPath = false mode = defaultValues?.mode ?? 'enabled' - error_handler_path = defaultValues?.error_handler_path ?? undefined - error_handler_args = defaultValues?.error_handler_args ?? {} + errorHandler = handlerDraftFromStored( + 'error', + defaultValues?.error_handler_path, + 'script', + defaultValues?.error_handler_args + ) retry = defaultValues?.retry ?? undefined - errorHandlerSelected = getHandlerType(error_handler_path ?? '') permissionedAs = undefined selectedPermissionedAs = undefined preservePermissionedAs = false @@ -265,10 +266,13 @@ mode = cfg?.mode ?? 'enabled' permsPath = cfg?.path permsForWrite = cfg?.extra_perms - error_handler_path = cfg?.error_handler_path - error_handler_args = cfg?.error_handler_args ?? {} + errorHandler = handlerDraftFromStored( + 'error', + cfg?.error_handler_path, + 'script', + cfg?.error_handler_args + ) retry = cfg?.retry - errorHandlerSelected = getHandlerType(error_handler_path ?? '') permissionedAs = cfg?.permissioned_as selectedPermissionedAs = cfg?.permissioned_as preservePermissionedAs = !!cfg?.permissioned_as @@ -320,7 +324,9 @@ topic_name, subscription_name, event_type_filters, - base_endpoint, + // The capture URL shown to the user stays on the browsing origin, so the + // endpoint registered for it must too. + base_endpoint: window.location.origin, path } } @@ -566,9 +572,7 @@ {optionTabSelected} {itemKind} {can_write} - bind:errorHandlerSelected - bind:error_handler_path - bind:error_handler_args + bind:errorHandler bind:retry /> </div> diff --git a/frontend/src/lib/components/triggers/email/EmailTriggerEditor.svelte b/frontend/src/lib/components/triggers/email/EmailTriggerEditor.svelte index 101b84f770..57ed70f6e7 100644 --- a/frontend/src/lib/components/triggers/email/EmailTriggerEditor.svelte +++ b/frontend/src/lib/components/triggers/email/EmailTriggerEditor.svelte @@ -27,6 +27,21 @@ drawer?.openNew(is_flow, initial_script_path, defaultValues) } + /** Edit a trigger that exists only as the caller's draft; Save hands the config back. */ + export async function openDraft( + scriptPath: string, + defaults: Record<string, any>, + saved: Record<string, any> | undefined, + onSaveDraft: (cfg: Record<string, any>) => boolean + ) { + open = true + await tickPainted() + drawer?.openNew(false, scriptPath, defaults as any, { + onSaveDraft, + draftConfig: saved + }) + } + let drawer: EmailTriggerEditorInner | undefined = $state() </script> diff --git a/frontend/src/lib/components/triggers/email/EmailTriggerEditorInner.svelte b/frontend/src/lib/components/triggers/email/EmailTriggerEditorInner.svelte index 042b914b93..38a8243855 100644 --- a/frontend/src/lib/components/triggers/email/EmailTriggerEditorInner.svelte +++ b/frontend/src/lib/components/triggers/email/EmailTriggerEditorInner.svelte @@ -11,22 +11,22 @@ import TriggerRunnablePicker from '$lib/components/triggers/TriggerRunnablePicker.svelte' import { EmailTriggerService, - type ErrorHandler, type EmailTrigger, type NewEmailTrigger, type Retry, type TriggerMode } from '$lib/gen' import { usedTriggerKinds } from '$lib/stores' - import { canWrite, capitalize, emptyString, sendUserToast } from '$lib/utils' - import { useTriggerLock } from '$lib/operatorWriteRights' + import { capitalize, emptyString, sendUserToast } from '$lib/utils' + import { useEditRights } from '$lib/operatorWriteRights' import Section from '$lib/components/Section.svelte' import { Loader2 } from 'lucide-svelte' import Label from '$lib/components/Label.svelte' import EmailTriggerEditorConfigSection from './EmailTriggerEditorConfigSection.svelte' import TriggerEditorToolbar from '../TriggerEditorToolbar.svelte' import PermissionedAsLine from '../PermissionedAsLine.svelte' - import { getHandlerType, handleConfigChange } from '../utils' + import { handleConfigChange } from '../utils' + import { handlerDraftFromStored, handlerDraftToStored } from '../../handlerDraft.svelte' import { untrack } from 'svelte' import Tabs from '$lib/components/common/tabs/Tabs.svelte' import Tab from '$lib/components/common/tabs/Tab.svelte' @@ -43,7 +43,7 @@ useOperatingWorkspace, useOperatingWorkspaceHref } from '$lib/components/operatingWorkspace.svelte' - const triggerLock = useTriggerLock() + const editRights = useEditRights() let { useDrawer = true, @@ -91,12 +91,15 @@ // The acting user in the operating workspace arrives asynchronously, and an unknown user // refuses — so the editor stays read-only until the lookup lands, which is the safe answer. const can_write = $derived( - (permsPath === undefined || canWrite(permsPath, permsForWrite ?? {}, actingUser)) && - !$triggerLock + permsPath === undefined + ? editRights.roleCanAuthor('trigger') + : editRights.canEditItem('trigger', permsPath, permsForWrite) ) let extraPerms = $state<Record<string, boolean> | undefined>(undefined) - let error_handler_path: string | undefined = $state() - let error_handler_args: Record<string, any> = $state({}) + let errorHandler = $state(handlerDraftFromStored('error', undefined)) + const storedErrorHandler = $derived(handlerDraftToStored(errorHandler)) + const error_handler_path = $derived(storedErrorHandler.path) + const error_handler_args = $derived(storedErrorHandler.args) let retry: Retry | undefined = $state() let mode = $state<TriggerMode>('enabled') // Component references @@ -107,7 +110,6 @@ let selectedPermissionedAs = $state<string | undefined>(undefined) let preservePermissionedAs = $state(false) let optionTabSelected: 'error_handler' | 'retries' = $state('error_handler') - let errorHandlerSelected: ErrorHandler = $state('slack') let suspendedJobsModal = $state<TriggerSuspendedJobsModal | null>(null) let originalConfig = $state<NewEmailTrigger | undefined>(undefined) @@ -139,14 +141,20 @@ is_flow = itemKind === 'flow' }) + // Set by `openNew(…, { onSaveDraft })`: the caller keeps the trigger as its own + // draft, so Save hands it the config instead of writing it. + let saveDraftHandler: ((cfg: Record<string, any>) => boolean) | undefined = $state(undefined) + export async function openEdit( ePath: string, isFlow: boolean, defaultConfig?: Partial<NewEmailTrigger>, fixedScriptPath_?: string ) { + saveDraftHandler = undefined // A `whoami` that failed earlier would otherwise pin this workspace to "unknown user". operatingUser.forgetFailures() + editRights.forgetFailures() drawerLoading = true let loader = setTimeout(() => { showLoader = true @@ -188,8 +196,14 @@ export async function openNew( nis_flow: boolean, fixedScriptPath_?: string, - defaultValues?: Partial<EmailTrigger> + defaultValues?: Partial<EmailTrigger>, + opts: { + onSaveDraft?: (cfg: Record<string, any>) => boolean + /** A config this editor saved before, re-applied over the defaults. */ + draftConfig?: Record<string, any> + } = {} ) { + saveDraftHandler = opts.onSaveDraft drawerLoading = true let loader = setTimeout(() => { showLoader = true @@ -209,15 +223,19 @@ dirtyPath = false workspaced_local_part = defaultValues?.workspaced_local_part ?? false - error_handler_path = defaultValues?.error_handler_path ?? undefined - error_handler_args = defaultValues?.error_handler_args ?? {} + errorHandler = handlerDraftFromStored( + 'error', + defaultValues?.error_handler_path, + 'script', + defaultValues?.error_handler_args + ) retry = defaultValues?.retry ?? undefined - errorHandlerSelected = getHandlerType(error_handler_path ?? '') mode = defaultValues?.mode ?? 'enabled' permissionedAs = undefined selectedPermissionedAs = undefined preservePermissionedAs = false originalConfig = undefined + if (opts.draftConfig) await loadTriggerConfig(opts.draftConfig as Partial<EmailTrigger>) } finally { clearTimeout(loader) drawerLoading = false @@ -237,10 +255,13 @@ extraPerms = cfg?.extra_perms ?? undefined permsPath = path permsForWrite = cfg?.extra_perms ?? {} - error_handler_path = cfg?.error_handler_path - error_handler_args = cfg?.error_handler_args ?? {} + errorHandler = handlerDraftFromStored( + 'error', + cfg?.error_handler_path, + 'script', + cfg?.error_handler_args + ) retry = cfg?.retry - errorHandlerSelected = getHandlerType(error_handler_path ?? '') mode = cfg?.mode ?? 'enabled' permissionedAs = cfg?.permissioned_as selectedPermissionedAs = cfg?.permissioned_as @@ -276,6 +297,11 @@ } async function triggerScript(): Promise<void> { + if (saveDraftHandler) { + if (!saveDraftHandler($state.snapshot(getEmailTriggerConfig()))) return + drawer?.closeDrawer() + return + } if (customSaveBehavior) { customSaveBehavior(emailConfig) drawer?.closeDrawer() @@ -476,9 +502,7 @@ {optionTabSelected} {itemKind} {can_write} - bind:errorHandlerSelected - bind:error_handler_path - bind:error_handler_args + bind:errorHandler bind:retry /> </div> @@ -502,6 +526,7 @@ {edit} isLoading={deploymentLoading} onUpdate={triggerScript} + saveLabel={saveDraftHandler ? 'Save draft' : undefined} {onReset} {onDelete} {isDeployed} @@ -521,7 +546,9 @@ ? can_write ? `Edit email trigger ${initialPath}` : `Email trigger ${initialPath}` - : 'New email trigger'} + : saveDraftHandler + ? 'Draft email trigger' + : 'New email trigger'} on:close={() => (inline ? onClose?.() : drawer?.closeDrawer())} > {#snippet actions()} diff --git a/frontend/src/lib/components/triggers/gcp/GcpCapture.svelte b/frontend/src/lib/components/triggers/gcp/GcpCapture.svelte index a77d12ebef..b6ba7bfa28 100644 --- a/frontend/src/lib/components/triggers/gcp/GcpCapture.svelte +++ b/frontend/src/lib/components/triggers/gcp/GcpCapture.svelte @@ -3,7 +3,6 @@ import CaptureSection from '../CaptureSection.svelte' import { Url } from '$lib/components/common' import { fade } from 'svelte/transition' - import { base } from '$lib/base' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' const operatingWorkspace = useOperatingWorkspace() @@ -32,7 +31,7 @@ if (!captureInfo) { return } - return `${window.location.origin}${base}/api/w/${$operatingWorkspace}/capture_u/gcp/${ + return `${window.location.origin}/api/w/${$operatingWorkspace}/capture_u/gcp/${ captureInfo.isFlow ? 'flow' : 'script' }/${captureInfo.path}` } diff --git a/frontend/src/lib/components/triggers/gcp/GcpTriggerEditor.svelte b/frontend/src/lib/components/triggers/gcp/GcpTriggerEditor.svelte index f86706e8ab..9c3111b0fb 100644 --- a/frontend/src/lib/components/triggers/gcp/GcpTriggerEditor.svelte +++ b/frontend/src/lib/components/triggers/gcp/GcpTriggerEditor.svelte @@ -22,6 +22,21 @@ drawer?.openNew(is_flow, initial_script_path, defaultValues) } + /** Edit a trigger that exists only as the caller's draft; Save hands the config back. */ + export async function openDraft( + scriptPath: string, + defaults: Record<string, any>, + saved: Record<string, any> | undefined, + onSaveDraft: (cfg: Record<string, any>) => boolean + ) { + open = true + await tickPainted() + drawer?.openNew(false, scriptPath, defaults as any, { + onSaveDraft, + draftConfig: saved + }) + } + let drawer: GcpTriggerEditorInner | undefined = $state() </script> diff --git a/frontend/src/lib/components/triggers/gcp/GcpTriggerEditorConfigSection.svelte b/frontend/src/lib/components/triggers/gcp/GcpTriggerEditorConfigSection.svelte index d7868a650a..a33573a1d1 100644 --- a/frontend/src/lib/components/triggers/gcp/GcpTriggerEditorConfigSection.svelte +++ b/frontend/src/lib/components/triggers/gcp/GcpTriggerEditorConfigSection.svelte @@ -13,7 +13,7 @@ } from '$lib/gen' import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte' import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte' - import { base } from '$lib/base' + import { apiBaseUrl } from '$lib/apiBaseUrl.svelte' import Toggle from '$lib/components/Toggle.svelte' import { Button, Url } from '$lib/components/common' @@ -28,23 +28,17 @@ useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' - // Declared before `DEFAULT_PUSH_CONFIG` / the `base_endpoint` prop default, - // which call `getBaseUrl()` (a `wsId` reader) during component init. const operatingWorkspace = useOperatingWorkspace() const operatingUser = useOperatingUser() const actingUser = $derived(operatingUser.current) const wsId = $derived($operatingWorkspace) + const base_endpoint = $derived(`${apiBaseUrl()}/api/gcp/w/${wsId!}`) let topic_items: string[] = $state([]) let subscription_items: string[] = $state([]) let loadingTopic = $state(false) let loadingSubscription = $state(false) - const DEFAULT_PUSH_CONFIG: PushConfig = { - audience: getBaseUrl(), - authenticate: false - } - async function loadAllPubSubTopicsFromProject() { // Listing is admin-only under application default credentials, and a non-admin viewing an // inherited trigger cannot change the topic anyway, so asking would only raise a 403 toast. @@ -117,7 +111,6 @@ delivery_type?: DeliveryType | undefined delivery_config: PushConfig | undefined subscription_mode?: SubscriptionMode - base_endpoint?: string path?: string showTestingBadge?: boolean cloud_subscription_id?: string @@ -139,7 +132,6 @@ delivery_type = $bindable('pull'), delivery_config = $bindable(), subscription_mode = $bindable('create_update'), - base_endpoint = $bindable(getBaseUrl()), auto_acknowledge_msg = $bindable(true), ack_deadline = $bindable(), path = '', @@ -199,17 +191,9 @@ if (!delivery_type) { delivery_type = 'pull' } else if (delivery_type === 'push' && !delivery_config) { - delivery_config = DEFAULT_PUSH_CONFIG + delivery_config = { audience: base_endpoint, authenticate: false } } }) - function getBaseUrl() { - return `${window.location.origin}${base}/api/gcp/w/${wsId!}` - } - - $effect(() => { - !base_endpoint && (base_endpoint = getBaseUrl()) - }) - $effect(() => { if (emptyStringTrimmed(subscription_id) && !emptyStringTrimmed(path)) { subscription_id = `windmill-${wsId!}-${path.replaceAll('/', '_')}` diff --git a/frontend/src/lib/components/triggers/gcp/GcpTriggerEditorInner.svelte b/frontend/src/lib/components/triggers/gcp/GcpTriggerEditorInner.svelte index 481395a138..486711bd6c 100644 --- a/frontend/src/lib/components/triggers/gcp/GcpTriggerEditorInner.svelte +++ b/frontend/src/lib/components/triggers/gcp/GcpTriggerEditorInner.svelte @@ -9,8 +9,8 @@ import DrawerContent from '$lib/components/common/drawer/DrawerContent.svelte' import Path from '$lib/components/Path.svelte' import { usedTriggerKinds } from '$lib/stores' - import { canWrite, capitalize, emptyString, sendUserToast } from '$lib/utils' - import { useTriggerLock } from '$lib/operatorWriteRights' + import { capitalize, emptyString, sendUserToast } from '$lib/utils' + import { useEditRights } from '$lib/operatorWriteRights' import { withForkConflictRetry } from '$lib/utils/forkConflict' import { Loader2 } from 'lucide-svelte' import Label from '$lib/components/Label.svelte' @@ -20,7 +20,6 @@ type PushConfig, type SubscriptionMode, type Retry, - type ErrorHandler, type TriggerMode } from '$lib/gen' import Section from '$lib/components/Section.svelte' @@ -30,13 +29,14 @@ import TriggerEditorToolbar from '../TriggerEditorToolbar.svelte' import PermissionedAsLine from '../PermissionedAsLine.svelte' import { saveGcpTriggerFromCfg } from './utils' - import { getHandlerType, handleConfigChange, type Trigger } from '../utils' + import { handleConfigChange, type Trigger } from '../utils' + import { handlerDraftFromStored, handlerDraftToStored } from '../../handlerDraft.svelte' import { deepEqual } from 'fast-equals' import { useTriggerDraftSync } from '../useTriggerDraftSync.svelte' import LocalDraftBanner from '$lib/components/LocalDraftBanner.svelte' import TriggerSuspendedJobsAlert from '../TriggerSuspendedJobsAlert.svelte' import TriggerSuspendedJobsModal from '../TriggerSuspendedJobsModal.svelte' - import { base } from '$lib/base' + import { apiBaseUrl } from '$lib/apiBaseUrl.svelte' import Tabs from '$lib/components/common/tabs/Tabs.svelte' import Tab from '$lib/components/common/tabs/Tab.svelte' import TriggerRetriesAndErrorHandler from '../TriggerRetriesAndErrorHandler.svelte' @@ -48,7 +48,7 @@ useOperatingWorkspace, useOperatingWorkspaceHref } from '$lib/components/operatingWorkspace.svelte' - const triggerLock = useTriggerLock() + const editRights = useEditRights() let drawer: Drawer | undefined = $state(undefined) let initialPath = $state('') @@ -69,8 +69,9 @@ // The acting user in the operating workspace arrives asynchronously, and an unknown user // refuses — so the editor stays read-only until the lookup lands, which is the safe answer. const can_write = $derived( - (permsPath === undefined || canWrite(permsPath, permsForWrite ?? {}, actingUser)) && - !$triggerLock + permsPath === undefined + ? editRights.roleCanAuthor('trigger') + : editRights.canEditItem('trigger', permsPath, permsForWrite) ) let drawerLoading = $state(true) let topic_id: string = $state('') @@ -88,13 +89,14 @@ let permissionedAs = $state<string | undefined>(undefined) let selectedPermissionedAs = $state<string | undefined>(undefined) let preservePermissionedAs = $state(false) - let base_endpoint = $derived(`${window.location.origin}${base}`) + let base_endpoint = $derived(apiBaseUrl()) let auto_acknowledge_msg = $state(true) let ack_deadline: number | undefined = $state() let optionTabSelected: 'settings' | 'error_handler' | 'retries' = $state('error_handler') - let errorHandlerSelected: ErrorHandler = $state('slack') - let error_handler_path: string | undefined = $state() - let error_handler_args: Record<string, any> = $state({}) + let errorHandler = $state(handlerDraftFromStored('error', undefined)) + const storedErrorHandler = $derived(handlerDraftToStored(errorHandler)) + const error_handler_path = $derived(storedErrorHandler.path) + const error_handler_args = $derived(storedErrorHandler.args) let retry: Retry | undefined = $state() let suspendedJobsModal = $state<TriggerSuspendedJobsModal | null>(null) let originalConfig = $state<Record<string, any> | undefined>(undefined) @@ -163,14 +165,20 @@ ) const captureConfig = $derived.by(untrack(() => isEditor) ? getGcpCaptureConfig : () => ({})) + // Set by `openNew(…, { onSaveDraft })`: the caller keeps the trigger as its own + // draft, so Save hands it the config instead of writing it. + let saveDraftHandler: ((cfg: Record<string, any>) => boolean) | undefined = $state(undefined) + export async function openEdit( ePath: string, isFlow: boolean, defaultValues?: Record<string, any>, fixedScriptPath_?: string ) { + saveDraftHandler = undefined // A `whoami` that failed earlier would otherwise pin this workspace to "unknown user". operatingUser.forgetFailures() + editRights.forgetFailures() drawerLoading = true try { drawer?.openDrawer() @@ -201,8 +209,14 @@ export async function openNew( nis_flow: boolean, fixedScriptPath_?: string, - defaultValues?: Record<string, any> + defaultValues?: Record<string, any>, + opts: { + onSaveDraft?: (cfg: Record<string, any>) => boolean + /** A config this editor saved before, re-applied over the defaults. */ + draftConfig?: Record<string, any> + } = {} ) { + saveDraftHandler = opts.onSaveDraft drawerLoading = true try { drawer?.openDrawer() @@ -234,16 +248,20 @@ edit = false dirtyPath = false mode = defaultValues?.mode ?? 'enabled' - error_handler_path = defaultValues?.error_handler_path ?? undefined - error_handler_args = defaultValues?.error_handler_args ?? {} + errorHandler = handlerDraftFromStored( + 'error', + defaultValues?.error_handler_path, + 'script', + defaultValues?.error_handler_args + ) retry = defaultValues?.retry ?? undefined auto_acknowledge_msg = defaultValues?.auto_acknowledge_msg ?? true ack_deadline = defaultValues?.ack_deadline - errorHandlerSelected = getHandlerType(error_handler_path ?? '') permissionedAs = undefined selectedPermissionedAs = undefined preservePermissionedAs = false originalConfig = undefined + if (opts.draftConfig) await loadTriggerConfig(opts.draftConfig) } finally { drawerLoading = false } @@ -295,18 +313,26 @@ topic_id = cfg?.topic_id ?? '' permsPath = cfg?.path permsForWrite = cfg?.extra_perms - error_handler_path = cfg?.error_handler_path - error_handler_args = cfg?.error_handler_args ?? {} + errorHandler = handlerDraftFromStored( + 'error', + cfg?.error_handler_path, + 'script', + cfg?.error_handler_args + ) retry = cfg?.retry auto_acknowledge_msg = cfg?.auto_acknowledge_msg ?? true ack_deadline = cfg?.ack_deadline - errorHandlerSelected = getHandlerType(error_handler_path ?? '') permissionedAs = cfg?.permissioned_as selectedPermissionedAs = cfg?.permissioned_as preservePermissionedAs = !!cfg?.permissioned_as } async function updateTrigger(): Promise<void> { + if (saveDraftHandler) { + if (!saveDraftHandler($state.snapshot(getGcpConfig()))) return + drawer?.closeDrawer() + return + } deploymentLoading = true const previousPath = initialPath const cfg = gcpConfig @@ -359,7 +385,9 @@ subscription_id, delivery_type, delivery_config, - base_endpoint, + // The capture URL shown to the user stays on the browsing origin, so the + // endpoint registered for it must too. + base_endpoint: window.location.origin, auto_acknowledge_msg, ack_deadline, topic_id, @@ -441,7 +469,9 @@ ? can_write ? `Edit GCP Pub/Sub trigger ${initialPath}` : `GCP Pub/Sub trigger ${initialPath}` - : 'New GCP Pub/Sub trigger'} + : saveDraftHandler + ? 'Draft GCP Pub/Sub trigger' + : 'New GCP Pub/Sub trigger'} on:close={() => (inline ? onClose?.() : drawer?.closeDrawer())} > {#snippet actions()} @@ -498,6 +528,7 @@ {allowDraft} {isDeployed} onUpdate={updateTrigger} + saveLabel={saveDraftHandler ? 'Save draft' : undefined} {onReset} {onDelete} onToggleMode={handleToggleMode} @@ -677,9 +708,7 @@ {optionTabSelected} {itemKind} {can_write} - bind:errorHandlerSelected - bind:error_handler_path - bind:error_handler_args + bind:errorHandler bind:retry /> {/if} diff --git a/frontend/src/lib/components/triggers/http/OpenAPISpecGenerator.svelte b/frontend/src/lib/components/triggers/http/OpenAPISpecGenerator.svelte index b0cc491393..024086552c 100644 --- a/frontend/src/lib/components/triggers/http/OpenAPISpecGenerator.svelte +++ b/frontend/src/lib/components/triggers/http/OpenAPISpecGenerator.svelte @@ -15,7 +15,7 @@ import SimpleEditor from '$lib/components/SimpleEditor.svelte' import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte' import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte' - import { base } from '$lib/base' + import { apiBaseUrl } from '$lib/apiBaseUrl.svelte' import Label from '$lib/components/Label.svelte' import Tooltip from '$lib/components/Tooltip.svelte' import { ClipboardCopy, Download, Trash } from 'lucide-svelte' @@ -136,7 +136,7 @@ obj = { openapi_spec_format: lang, info, - url: `${window.location.origin}${base}`, + url: apiBaseUrl(), http_route_filters: getHttpRouteFilters(), webhook_filters: getWebhookFilters() } @@ -155,7 +155,7 @@ requestBody: { openapi_spec_format, info, - url: `${window.location.origin}${base}`, + url: apiBaseUrl(), http_route_filters: getHttpRouteFilters(), webhook_filters: getWebhookFilters() } @@ -225,7 +225,7 @@ {/snippet} <CopyableCodeBlock code={`token=${emptyString(token) ? '' : token}; \\ -curl -X POST "${window.location.origin}${base}/api/w/${$operatingWorkspace!}/openapi/generate" \\ +curl -X POST "${apiBaseUrl()}/api/w/${$operatingWorkspace!}/openapi/generate" \\ -H "Authorization: Bearer $token" \\ -H "Content-Type: application/json" \\ -d '${JSON.stringify(obj)}'`} diff --git a/frontend/src/lib/components/triggers/http/RouteCapture.svelte b/frontend/src/lib/components/triggers/http/RouteCapture.svelte index 5cbe3570dc..45cc886693 100644 --- a/frontend/src/lib/components/triggers/http/RouteCapture.svelte +++ b/frontend/src/lib/components/triggers/http/RouteCapture.svelte @@ -3,7 +3,6 @@ import CopyableCodeBlock from '$lib/components/details/CopyableCodeBlock.svelte' import { bash } from 'svelte-highlight/languages' // import { page } from '$app/state' - import { base } from '$lib/base' import type { CaptureInfo } from '../CaptureSection.svelte' import CaptureSection from '../CaptureSection.svelte' import { isObject } from '$lib/utils' @@ -36,7 +35,7 @@ const wsId = $derived($operatingWorkspace) let captureURL = $derived( - `${location.origin}${base}/api/w/${wsId}/capture_u/http/${ + `${location.origin}/api/w/${wsId}/capture_u/http/${ captureInfo?.isFlow ? 'flow' : 'script' }/${captureInfo?.path.replaceAll('/', '.')}/${route_path ?? ''}` ) diff --git a/frontend/src/lib/components/triggers/http/RouteEditorInner.svelte b/frontend/src/lib/components/triggers/http/RouteEditorInner.svelte index 395f518349..786137eab4 100644 --- a/frontend/src/lib/components/triggers/http/RouteEditorInner.svelte +++ b/frontend/src/lib/components/triggers/http/RouteEditorInner.svelte @@ -15,21 +15,14 @@ SettingService, VariableService, type AuthenticationMethod, - type ErrorHandler, type HttpTrigger, type NewHttpTrigger, type Retry, type TriggerMode } from '$lib/gen' import { usedTriggerKinds } from '$lib/stores' - import { - canWrite, - capitalize, - emptyString, - generateRandomString, - sendUserToast - } from '$lib/utils' - import { useTriggerLock } from '$lib/operatorWriteRights' + import { capitalize, emptyString, generateRandomString, sendUserToast } from '$lib/utils' + import { useEditRights } from '$lib/operatorWriteRights' import Section from '$lib/components/Section.svelte' import { Loader2, Pipette, Plus } from 'lucide-svelte' import Label from '$lib/components/Label.svelte' @@ -63,7 +56,8 @@ import TestingBadge from '../testingBadge.svelte' import TriggerEditorToolbar from '../TriggerEditorToolbar.svelte' import PermissionedAsLine from '../PermissionedAsLine.svelte' - import { getHandlerType, handleConfigChange } from '../utils' + import { handleConfigChange } from '../utils' + import { handlerDraftFromStored, handlerDraftToStored } from '../../handlerDraft.svelte' import autosize from '$lib/autosize' import { untrack } from 'svelte' import Tabs from '$lib/components/common/tabs/Tabs.svelte' @@ -82,7 +76,7 @@ useOperatingWorkspace, useOperatingWorkspaceHref } from '$lib/components/operatingWorkspace.svelte' - const triggerLock = useTriggerLock() + const editRights = useEditRights() let { useDrawer = true, @@ -165,14 +159,17 @@ // The acting user in the operating workspace arrives asynchronously, and an unknown user // refuses — so the editor stays read-only until the lookup lands, which is the safe answer. const can_write = $derived( - (permsPath === undefined || canWrite(permsPath, permsForWrite ?? {}, actingUser)) && - !$triggerLock + permsPath === undefined + ? editRights.roleCanAuthor('trigger') + : editRights.canEditItem('trigger', permsPath, permsForWrite) ) let extraPerms = $state<Record<string, boolean> | undefined>(undefined) let summary: string | undefined = $state() let routeDescription: string | undefined = $state() - let error_handler_path: string | undefined = $state() - let error_handler_args: Record<string, any> = $state({}) + let errorHandler = $state(handlerDraftFromStored('error', undefined)) + const storedErrorHandler = $derived(handlerDraftToStored(errorHandler)) + const error_handler_path = $derived(storedErrorHandler.path) + const error_handler_args = $derived(storedErrorHandler.args) let retry: Retry | undefined = $state() // Component references let s3FilePicker = $state<S3FilePicker | undefined>(undefined) @@ -186,7 +183,6 @@ let selectedPermissionedAs = $state<string | undefined>(undefined) let preservePermissionedAs = $state(false) let optionTabSelected: 'request_options' | 'error_handler' | 'retries' = $state('request_options') - let errorHandlerSelected: ErrorHandler = $state('slack') let suspendedJobsModal = $state<TriggerSuspendedJobsModal | null>(null) let originalConfig = $state<NewHttpTrigger | undefined>(undefined) @@ -278,6 +274,7 @@ ) { // A `whoami` that failed earlier would otherwise pin this workspace to "unknown user". operatingUser.forgetFailures() + editRights.forgetFailures() drawerLoading = true let loader = setTimeout(() => { showLoader = true @@ -353,10 +350,13 @@ allowed_origins = defaultValues?.allowed_origins ?? undefined summary = defaultValues?.summary ?? '' routeDescription = defaultValues?.description ?? '' - error_handler_path = defaultValues?.error_handler_path ?? undefined - error_handler_args = defaultValues?.error_handler_args ?? {} + errorHandler = handlerDraftFromStored( + 'error', + defaultValues?.error_handler_path, + 'script', + defaultValues?.error_handler_args + ) retry = defaultValues?.retry ?? undefined - errorHandlerSelected = getHandlerType(error_handler_path ?? '') permissionedAs = undefined selectedPermissionedAs = undefined preservePermissionedAs = false @@ -401,10 +401,13 @@ extraPerms = cfg?.extra_perms ?? undefined permsPath = path permsForWrite = cfg?.extra_perms ?? {} - error_handler_path = cfg?.error_handler_path - error_handler_args = cfg?.error_handler_args ?? {} + errorHandler = handlerDraftFromStored( + 'error', + cfg?.error_handler_path, + 'script', + cfg?.error_handler_args + ) retry = cfg?.retry - errorHandlerSelected = getHandlerType(error_handler_path ?? '') permissionedAs = cfg?.permissioned_as selectedPermissionedAs = cfg?.permissioned_as preservePermissionedAs = !!cfg?.permissioned_as @@ -1040,9 +1043,7 @@ {optionTabSelected} {itemKind} {can_write} - bind:errorHandlerSelected - bind:error_handler_path - bind:error_handler_args + bind:errorHandler bind:retry /> {/if} diff --git a/frontend/src/lib/components/triggers/http/utils.ts b/frontend/src/lib/components/triggers/http/utils.ts index ed03ef86aa..cc4d366be4 100644 --- a/frontend/src/lib/components/triggers/http/utils.ts +++ b/frontend/src/lib/components/triggers/http/utils.ts @@ -1,4 +1,4 @@ -import { base } from '$lib/base' +import { apiBaseUrl } from '$lib/apiBaseUrl.svelte' import { isCloudHosted } from '$lib/cloud' import { random_adj } from '$lib/components/random_positive_adjetive' import type { HttpMethod, NewHttpTrigger } from '$lib/gen' @@ -33,8 +33,7 @@ export function allowedOriginRejection(origin: string): string | undefined { if (origin === '') return 'An origin must not be empty' if (origin.length > MAX_ALLOWED_ORIGIN_LEN) return `'${origin.slice(0, 40)}…' is longer than any origin a browser sends` - if (origin.includes(',')) - return `'${origin}' must not contain a comma, which separates entries` + if (origin.includes(',')) return `'${origin}' must not contain a comma, which separates entries` if (origin.toLowerCase() === 'null') return `'null' is what a sandboxed iframe sends, so it would allow any page that can open one` if (!/^[\x21-\x7e]+$/.test(origin)) @@ -85,8 +84,7 @@ export function allowedOriginWarning(origin: string): string | undefined { if (rest.startsWith(':')) return `'${origin}' has no host` // An unclosed bracket would otherwise leave `portStart` at zero, which reads // as "no port" and lets the entry through unremarked. - if (rest.startsWith('[') && !rest.includes(']')) - return `'${origin}' has an unclosed IPv6 host` + if (rest.startsWith('[') && !rest.includes(']')) return `'${origin}' has an unclosed IPv6 host` const portStart = rest.startsWith('[') ? rest.indexOf(']') + 1 : rest.indexOf(':') // A trailing colon is a port, an empty one — distinct from having none. const port = portStart > 0 && rest[portStart] === ':' ? rest.slice(portStart + 1) : undefined @@ -160,7 +158,7 @@ export function getHttpRoute( workspaced_route: boolean, workspace_id: string ) { - return `${location.origin}${base}/api/${route_prefix}/${ + return `${apiBaseUrl()}/api/${route_prefix}/${ isCloudHosted() || workspaced_route ? workspace_id + '/' : '' }${route_path ?? ''}` } diff --git a/frontend/src/lib/components/triggers/kafka/KafkaTriggerEditor.svelte b/frontend/src/lib/components/triggers/kafka/KafkaTriggerEditor.svelte index 73d32c0d52..0769c8ed0e 100644 --- a/frontend/src/lib/components/triggers/kafka/KafkaTriggerEditor.svelte +++ b/frontend/src/lib/components/triggers/kafka/KafkaTriggerEditor.svelte @@ -21,6 +21,21 @@ drawer?.openNew(is_flow, initial_script_path, defaultValues) } + /** Edit a trigger that exists only as the caller's draft; Save hands the config back. */ + export async function openDraft( + scriptPath: string, + defaults: Record<string, any>, + saved: Record<string, any> | undefined, + onSaveDraft: (cfg: Record<string, any>) => boolean + ) { + open = true + await tickPainted() + drawer?.openNew(false, scriptPath, defaults as any, { + onSaveDraft, + draftConfig: saved + }) + } + let drawer: KafkaTriggerEditorInner | undefined = $state() </script> diff --git a/frontend/src/lib/components/triggers/kafka/KafkaTriggerEditorInner.svelte b/frontend/src/lib/components/triggers/kafka/KafkaTriggerEditorInner.svelte index 3136f74c47..17a17f98e8 100644 --- a/frontend/src/lib/components/triggers/kafka/KafkaTriggerEditorInner.svelte +++ b/frontend/src/lib/components/triggers/kafka/KafkaTriggerEditorInner.svelte @@ -10,10 +10,10 @@ import DrawerContent from '$lib/components/common/drawer/DrawerContent.svelte' import Path from '$lib/components/Path.svelte' import TriggerRunnablePicker from '$lib/components/triggers/TriggerRunnablePicker.svelte' - import { KafkaTriggerService, type ErrorHandler, type Retry, type TriggerMode } from '$lib/gen' + import { KafkaTriggerService, type Retry, type TriggerMode } from '$lib/gen' import { usedTriggerKinds } from '$lib/stores' - import { canWrite, capitalize, emptyString, sendUserToast } from '$lib/utils' - import { useTriggerLock } from '$lib/operatorWriteRights' + import { capitalize, emptyString, sendUserToast } from '$lib/utils' + import { useEditRights } from '$lib/operatorWriteRights' import { withForkConflictRetry } from '$lib/utils/forkConflict' import Section from '$lib/components/Section.svelte' import { Loader2, RotateCcw } from 'lucide-svelte' @@ -23,7 +23,8 @@ import TriggerEditorToolbar from '../TriggerEditorToolbar.svelte' import PermissionedAsLine from '../PermissionedAsLine.svelte' import { saveKafkaTriggerFromCfg } from './utils' - import { getHandlerType, handleConfigChange, type Trigger } from '../utils' + import { handleConfigChange, type Trigger } from '../utils' + import { handlerDraftFromStored, handlerDraftToStored } from '../../handlerDraft.svelte' import Tabs from '$lib/components/common/tabs/Tabs.svelte' import Tab from '$lib/components/common/tabs/Tab.svelte' import TriggerRetriesAndErrorHandler from '../TriggerRetriesAndErrorHandler.svelte' @@ -42,7 +43,7 @@ useOperatingWorkspace, useOperatingWorkspaceHref } from '$lib/components/operatingWorkspace.svelte' - const triggerLock = useTriggerLock() + const editRights = useEditRights() interface Props { useDrawer?: boolean @@ -108,8 +109,9 @@ // The acting user in the operating workspace arrives asynchronously, and an unknown user // refuses — so the editor stays read-only until the lookup lands, which is the safe answer. const can_write = $derived( - (permsPath === undefined || canWrite(permsPath, permsForWrite ?? {}, actingUser)) && - !$triggerLock + permsPath === undefined + ? editRights.roleCanAuthor('trigger') + : editRights.canEditItem('trigger', permsPath, permsForWrite) ) let drawerLoading = $state(true) let showLoading = $state(false) @@ -126,9 +128,10 @@ let preservePermissionedAs = $state(false) let resetLoading = $state(false) let optionTabSelected: 'error_handler' | 'retries' = $state('error_handler') - let errorHandlerSelected: ErrorHandler = $state('slack') - let error_handler_path: string | undefined = $state() - let error_handler_args: Record<string, any> = $state({}) + let errorHandler = $state(handlerDraftFromStored('error', undefined)) + const storedErrorHandler = $derived(handlerDraftToStored(errorHandler)) + const error_handler_path = $derived(storedErrorHandler.path) + const error_handler_args = $derived(storedErrorHandler.args) let retry: Retry | undefined = $state() let filters: FilterNode[] = $state([]) let filterLogic = $state<'and' | 'or'>('and') @@ -174,14 +177,20 @@ is_flow = itemKind === 'flow' }) + // Set by `openNew(…, { onSaveDraft })`: the caller keeps the trigger as its own + // draft, so Save hands it the config instead of writing it. + let saveDraftHandler: ((cfg: Record<string, any>) => boolean) | undefined = $state(undefined) + export async function openEdit( ePath: string, isFlow: boolean, defaultConfig?: Record<string, any>, fixedScriptPath_?: string ) { + saveDraftHandler = undefined // A `whoami` that failed earlier would otherwise pin this workspace to "unknown user". operatingUser.forgetFailures() + editRights.forgetFailures() let loadingTimeout = setTimeout(() => { showLoading = true }, 100) // Do not show loading spinner for the first 100ms @@ -217,8 +226,14 @@ export async function openNew( nis_flow: boolean, fixedScriptPath_?: string, - nDefaultValues?: Record<string, any> + nDefaultValues?: Record<string, any>, + opts: { + onSaveDraft?: (cfg: Record<string, any>) => boolean + /** A config this editor saved before, re-applied over the defaults. */ + draftConfig?: Record<string, any> + } = {} ) { + saveDraftHandler = opts.onSaveDraft let loadingTimeout = setTimeout(() => { showLoading = true }, 100) // Do not show loading spinner for the first 100ms @@ -241,17 +256,21 @@ path = nDefaultValues?.path ?? '' initialPath = '' dirtyPath = false - error_handler_path = nDefaultValues?.error_handler_path ?? undefined - error_handler_args = nDefaultValues?.error_handler_args ?? {} + errorHandler = handlerDraftFromStored( + 'error', + nDefaultValues?.error_handler_path, + 'script', + nDefaultValues?.error_handler_args + ) retry = nDefaultValues?.retry ?? undefined filters = nDefaultValues?.filters ?? [] filterLogic = 'and' - errorHandlerSelected = getHandlerType(error_handler_path ?? '') mode = nDefaultValues?.mode ?? 'enabled' permissionedAs = undefined selectedPermissionedAs = undefined preservePermissionedAs = false originalConfig = undefined + if (opts.draftConfig) await loadTriggerConfig(opts.draftConfig) } finally { clearTimeout(loadingTimeout) drawerLoading = false @@ -277,12 +296,15 @@ extra_perms = cfg?.extra_perms permsPath = path permsForWrite = cfg?.extra_perms - error_handler_path = cfg?.error_handler_path - error_handler_args = cfg?.error_handler_args ?? {} + errorHandler = handlerDraftFromStored( + 'error', + cfg?.error_handler_path, + 'script', + cfg?.error_handler_args + ) retry = cfg?.retry filters = cfg?.filters ?? [] filterLogic = cfg?.filter_logic ?? 'and' - errorHandlerSelected = getHandlerType(error_handler_path ?? '') permissionedAs = cfg?.permissioned_as selectedPermissionedAs = cfg?.permissioned_as preservePermissionedAs = !!cfg?.permissioned_as @@ -334,6 +356,11 @@ } async function updateTrigger(): Promise<void> { + if (saveDraftHandler) { + if (!saveDraftHandler($state.snapshot(getSaveCfg()))) return + drawer?.closeDrawer() + return + } deploymentLoading = true const previousPath = initialPath const cfg = getSaveCfg() @@ -453,7 +480,9 @@ ? can_write ? `Edit Kafka trigger ${initialPath}` : `Kafka trigger ${initialPath}` - : 'New Kafka trigger'} + : saveDraftHandler + ? 'Draft Kafka trigger' + : 'New Kafka trigger'} on:close={() => (inline ? onClose?.() : drawer?.closeDrawer())} > {#snippet actions()} @@ -511,6 +540,7 @@ {isDeployed} {saveDisabled} onUpdate={updateTrigger} + saveLabel={saveDraftHandler ? 'Save draft' : undefined} {onReset} {onDelete} onToggleMode={handleToggleMode} @@ -697,9 +727,7 @@ {optionTabSelected} {itemKind} {can_write} - bind:errorHandlerSelected - bind:error_handler_path - bind:error_handler_args + bind:errorHandler bind:retry /> </div> diff --git a/frontend/src/lib/components/triggers/mqtt/MqttTriggerEditor.svelte b/frontend/src/lib/components/triggers/mqtt/MqttTriggerEditor.svelte index fea56a3750..c8300ee81e 100644 --- a/frontend/src/lib/components/triggers/mqtt/MqttTriggerEditor.svelte +++ b/frontend/src/lib/components/triggers/mqtt/MqttTriggerEditor.svelte @@ -21,6 +21,21 @@ drawer?.openNew(is_flow, initial_script_path, defaultValues) } + /** Edit a trigger that exists only as the caller's draft; Save hands the config back. */ + export async function openDraft( + scriptPath: string, + defaults: Record<string, any>, + saved: Record<string, any> | undefined, + onSaveDraft: (cfg: Record<string, any>) => boolean + ) { + open = true + await tickPainted() + drawer?.openNew(false, scriptPath, defaults as any, { + onSaveDraft, + draftConfig: saved + }) + } + let drawer: MqttTriggerEditorInner | undefined = $state() </script> diff --git a/frontend/src/lib/components/triggers/mqtt/MqttTriggerEditorInner.svelte b/frontend/src/lib/components/triggers/mqtt/MqttTriggerEditorInner.svelte index d21fb1ff44..5c1fb4aaf0 100644 --- a/frontend/src/lib/components/triggers/mqtt/MqttTriggerEditorInner.svelte +++ b/frontend/src/lib/components/triggers/mqtt/MqttTriggerEditorInner.svelte @@ -11,8 +11,8 @@ import Path from '$lib/components/Path.svelte' import TriggerRunnablePicker from '$lib/components/triggers/TriggerRunnablePicker.svelte' import { usedTriggerKinds } from '$lib/stores' - import { canWrite, capitalize, emptyString, sendUserToast } from '$lib/utils' - import { useTriggerLock } from '$lib/operatorWriteRights' + import { capitalize, emptyString, sendUserToast } from '$lib/utils' + import { useEditRights } from '$lib/operatorWriteRights' import { withForkConflictRetry } from '$lib/utils/forkConflict' import Section from '$lib/components/Section.svelte' import { Loader2 } from 'lucide-svelte' @@ -24,7 +24,6 @@ type MqttV5Config, type MqttSubscribeTopic, type Retry, - type ErrorHandler, type TriggerMode } from '$lib/gen' import MqttEditorConfigSection from './MqttEditorConfigSection.svelte' @@ -32,7 +31,8 @@ import TriggerEditorToolbar from '../TriggerEditorToolbar.svelte' import PermissionedAsLine from '../PermissionedAsLine.svelte' import { saveMqttTriggerFromCfg } from './utils' - import { getHandlerType, handleConfigChange, type Trigger } from '../utils' + import { handleConfigChange, type Trigger } from '../utils' + import { handlerDraftFromStored, handlerDraftToStored } from '../../handlerDraft.svelte' import Tabs from '$lib/components/common/tabs/Tabs.svelte' import Tab from '$lib/components/common/tabs/Tab.svelte' import TriggerRetriesAndErrorHandler from '../TriggerRetriesAndErrorHandler.svelte' @@ -51,7 +51,7 @@ useOperatingWorkspace, useOperatingWorkspaceHref } from '$lib/components/operatingWorkspace.svelte' - const triggerLock = useTriggerLock() + const editRights = useEditRights() interface Props { useDrawer?: boolean @@ -118,8 +118,9 @@ // The acting user in the operating workspace arrives asynchronously, and an unknown user // refuses — so the editor stays read-only until the lookup lands, which is the safe answer. const can_write = $derived( - (permsPath === undefined || canWrite(permsPath, permsForWrite ?? {}, actingUser)) && - !$triggerLock + permsPath === undefined + ? editRights.roleCanAuthor('trigger') + : editRights.canEditItem('trigger', permsPath, permsForWrite) ) let drawerLoading = $state(true) let showLoading = $state(false) @@ -134,9 +135,10 @@ let permissionedAs = $state<string | undefined>(undefined) let selectedPermissionedAs = $state<string | undefined>(undefined) let preservePermissionedAs = $state(false) - let errorHandlerSelected: ErrorHandler = $state('slack') - let error_handler_path: string | undefined = $state() - let error_handler_args: Record<string, any> = $state({}) + let errorHandler = $state(handlerDraftFromStored('error', undefined)) + const storedErrorHandler = $derived(handlerDraftToStored(errorHandler)) + const error_handler_path = $derived(storedErrorHandler.path) + const error_handler_args = $derived(storedErrorHandler.args) let retry: Retry | undefined = $state() let suspendedJobsModal = $state<TriggerSuspendedJobsModal | null>(null) let originalConfig = $state<Record<string, any> | undefined>(undefined) @@ -169,14 +171,20 @@ is_flow = itemKind === 'flow' }) + // Set by `openNew(…, { onSaveDraft })`: the caller keeps the trigger as its own + // draft, so Save hands it the config instead of writing it. + let saveDraftHandler: ((cfg: Record<string, any>) => boolean) | undefined = $state(undefined) + export async function openEdit( ePath: string, isFlow: boolean, defaultConfig?: Record<string, any>, fixedScriptPath_?: string ) { + saveDraftHandler = undefined // A `whoami` that failed earlier would otherwise pin this workspace to "unknown user". operatingUser.forgetFailures() + editRights.forgetFailures() let loadingTimeout = setTimeout(() => { showLoading = true }, 100) // Do not show loading spinner for the first 100ms @@ -212,8 +220,14 @@ export async function openNew( nis_flow: boolean, fixedScriptPath_?: string, - defaultValues?: Record<string, any> + defaultValues?: Record<string, any>, + opts: { + onSaveDraft?: (cfg: Record<string, any>) => boolean + /** A config this editor saved before, re-applied over the defaults. */ + draftConfig?: Record<string, any> + } = {} ) { + saveDraftHandler = opts.onSaveDraft let loadingTimeout = setTimeout(() => { showLoading = true }, 100) @@ -234,10 +248,13 @@ client_version = defaultValues?.client_version ?? 'v5' client_id = defaultValues?.client_id ?? '' mode = defaultValues?.mode ?? 'enabled' - error_handler_path = defaultValues?.error_handler_path ?? undefined - error_handler_args = defaultValues?.error_handler_args ?? {} + errorHandler = handlerDraftFromStored( + 'error', + defaultValues?.error_handler_path, + 'script', + defaultValues?.error_handler_args + ) retry = defaultValues?.retry ?? undefined - errorHandlerSelected = getHandlerType(error_handler_path ?? '') v3_config = defaultValues?.v3_config ?? DEFAULT_V3_CONFIG v5_config = defaultValues?.v5_config ?? DEFAULT_V5_CONFIG activateV5Options.topic_alias_maximum = Boolean(defaultValues?.v5_config?.topic_alias_maximum) @@ -248,6 +265,7 @@ selectedPermissionedAs = undefined preservePermissionedAs = false originalConfig = undefined + if (opts.draftConfig) await loadTriggerConfig(opts.draftConfig) } finally { clearTimeout(loadingTimeout) drawerLoading = false @@ -272,10 +290,13 @@ client_id = cfg?.client_id ?? '' permsPath = cfg?.path permsForWrite = cfg?.extra_perms - error_handler_path = cfg?.error_handler_path - error_handler_args = cfg?.error_handler_args ?? {} + errorHandler = handlerDraftFromStored( + 'error', + cfg?.error_handler_path, + 'script', + cfg?.error_handler_args + ) retry = cfg?.retry - errorHandlerSelected = getHandlerType(error_handler_path ?? '') activateV5Options.topic_alias_maximum = Boolean(v5_config.topic_alias_maximum) activateV5Options.session_expiry_interval = Boolean(v5_config.session_expiry_interval) permissionedAs = cfg?.permissioned_as @@ -347,6 +368,11 @@ } async function updateTrigger(): Promise<void> { + if (saveDraftHandler) { + if (!saveDraftHandler($state.snapshot(getSaveCfg()))) return + drawer?.closeDrawer() + return + } deploymentLoading = true const previousPath = initialPath const cfg = getSaveCfg() @@ -427,7 +453,9 @@ ? can_write ? `Edit MQTT trigger ${initialPath}` : `MQTT trigger ${initialPath}` - : 'New MQTT trigger'} + : saveDraftHandler + ? 'Draft MQTT trigger' + : 'New MQTT trigger'} on:close={() => (inline ? onClose?.() : drawer?.closeDrawer())} > {#snippet actions()} @@ -485,6 +513,7 @@ isLoading={deploymentLoading} {isDeployed} onUpdate={updateTrigger} + saveLabel={saveDraftHandler ? 'Save draft' : undefined} {onReset} {onDelete} onToggleMode={handleToggleMode} @@ -728,9 +757,7 @@ {optionTabSelected} {itemKind} {can_write} - bind:errorHandlerSelected - bind:error_handler_path - bind:error_handler_args + bind:errorHandler bind:retry /> {/if} diff --git a/frontend/src/lib/components/triggers/native/NativeTriggerEditor.svelte b/frontend/src/lib/components/triggers/native/NativeTriggerEditor.svelte index 3a4be41a04..9e8dc592e9 100644 --- a/frontend/src/lib/components/triggers/native/NativeTriggerEditor.svelte +++ b/frontend/src/lib/components/triggers/native/NativeTriggerEditor.svelte @@ -9,8 +9,8 @@ saveNativeTriggerFromCfg } from './utils' import { usedTriggerKinds } from '$lib/stores' - import { canWrite, emptyString, sendUserToast } from '$lib/utils' - import { useTriggerLock } from '$lib/operatorWriteRights' + import { emptyString, sendUserToast } from '$lib/utils' + import { useEditRights, useTriggerLock } from '$lib/operatorWriteRights' import { Button } from '$lib/components/common' import TextInput from '$lib/components/text_input/TextInput.svelte' import Drawer from '$lib/components/common/drawer/Drawer.svelte' @@ -37,6 +37,7 @@ const operatingWorkspace = useOperatingWorkspace() const operatingUser = useOperatingUser() const actingUser = $derived(operatingUser.current) + const editRights = useEditRights() interface Props { service: NativeServiceName @@ -119,9 +120,9 @@ // Derived, not snapshotted at load: the acting user's role arrives on its own schedule, and // a trigger that loaded first would otherwise stay read-only until reopened. const can_write = $derived( - (writeVerdict ?? - (permsScriptPath === undefined || canWrite(permsScriptPath, {}, actingUser))) && - !$triggerLock + writeVerdict === undefined && permsScriptPath !== undefined + ? editRights.canEditItem('trigger', permsScriptPath, {}) + : writeVerdict !== false && editRights.roleCanAuthor('trigger') ) let originalConfig = $state<Record<string, any> | undefined>(undefined) let initialConfig = $state<Record<string, any> | undefined>(undefined) diff --git a/frontend/src/lib/components/triggers/native/NativeTriggerTable.svelte b/frontend/src/lib/components/triggers/native/NativeTriggerTable.svelte index e45f3f9eab..e6bf8928bc 100644 --- a/frontend/src/lib/components/triggers/native/NativeTriggerTable.svelte +++ b/frontend/src/lib/components/triggers/native/NativeTriggerTable.svelte @@ -3,9 +3,8 @@ import type { NativeServiceName, TriggerMode } from '$lib/gen/types.gen' import type { ExtendedNativeTrigger } from './utils' import { getServiceConfig } from './utils' - import { canWrite, sendUserToast } from '$lib/utils' - import { useTriggerLock } from '$lib/operatorWriteRights' - import { userStore } from '$lib/stores' + import { sendUserToast } from '$lib/utils' + import { useEditRights, useTriggerLock } from '$lib/operatorWriteRights' import TriggerModeToggle from '$lib/components/triggers/TriggerModeToggle.svelte' import Skeleton from '$lib/components/common/skeleton/Skeleton.svelte' import Button from '$lib/components/common/button/Button.svelte' @@ -19,6 +18,7 @@ import GoogleCalendarIcon from '$lib/components/icons/GoogleCalendarIcon.svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' const triggerLock = useTriggerLock() + const editRights = useEditRights() const operatingWorkspace = useOperatingWorkspace() @@ -111,7 +111,7 @@ {#each triggers as trigger (trigger.external_id)} {@const isFlow = trigger.is_flow} {@const href = `${isFlow ? '/flows/get' : '/scripts/get'}/${trigger.script_path}`} - {@const canEdit = canWrite(trigger.script_path, {}, $userStore) && !$triggerLock} + {@const canEdit = editRights.canEditItem('trigger', trigger.script_path, {})} <div class="hover:bg-surface-hover w-full items-center px-4 py-2 gap-4 first-of-type:!border-t-0 first-of-type:rounded-t-md last-of-type:rounded-b-md flex flex-col" > diff --git a/frontend/src/lib/components/triggers/nats/NatsTriggerEditor.svelte b/frontend/src/lib/components/triggers/nats/NatsTriggerEditor.svelte index aa5585a7b6..add8b43d75 100644 --- a/frontend/src/lib/components/triggers/nats/NatsTriggerEditor.svelte +++ b/frontend/src/lib/components/triggers/nats/NatsTriggerEditor.svelte @@ -21,6 +21,21 @@ drawer?.openNew(is_flow, initial_script_path, defaultValues) } + /** Edit a trigger that exists only as the caller's draft; Save hands the config back. */ + export async function openDraft( + scriptPath: string, + defaults: Record<string, any>, + saved: Record<string, any> | undefined, + onSaveDraft: (cfg: Record<string, any>) => boolean + ) { + open = true + await tickPainted() + drawer?.openNew(false, scriptPath, defaults as any, { + onSaveDraft, + draftConfig: saved + }) + } + let drawer: NatsTriggerEditorInner | undefined = $state() </script> diff --git a/frontend/src/lib/components/triggers/nats/NatsTriggerEditorInner.svelte b/frontend/src/lib/components/triggers/nats/NatsTriggerEditorInner.svelte index 3fe3fbbc8a..e0ba992e12 100644 --- a/frontend/src/lib/components/triggers/nats/NatsTriggerEditorInner.svelte +++ b/frontend/src/lib/components/triggers/nats/NatsTriggerEditorInner.svelte @@ -9,10 +9,10 @@ import DrawerContent from '$lib/components/common/drawer/DrawerContent.svelte' import Path from '$lib/components/Path.svelte' import TriggerRunnablePicker from '$lib/components/triggers/TriggerRunnablePicker.svelte' - import { NatsTriggerService, type ErrorHandler, type Retry, type TriggerMode } from '$lib/gen' + import { NatsTriggerService, type Retry, type TriggerMode } from '$lib/gen' import { usedTriggerKinds } from '$lib/stores' - import { canWrite, capitalize, emptyString, sendUserToast } from '$lib/utils' - import { useTriggerLock } from '$lib/operatorWriteRights' + import { capitalize, emptyString, sendUserToast } from '$lib/utils' + import { useEditRights } from '$lib/operatorWriteRights' import { withForkConflictRetry } from '$lib/utils/forkConflict' import Section from '$lib/components/Section.svelte' import { Loader2 } from 'lucide-svelte' @@ -22,7 +22,8 @@ import TriggerEditorToolbar from '../TriggerEditorToolbar.svelte' import PermissionedAsLine from '../PermissionedAsLine.svelte' import { saveNatsTriggerFromCfg } from './utils' - import { getHandlerType, handleConfigChange, type Trigger } from '../utils' + import { handleConfigChange, type Trigger } from '../utils' + import { handlerDraftFromStored, handlerDraftToStored } from '../../handlerDraft.svelte' import Tabs from '$lib/components/common/tabs/Tabs.svelte' import Tab from '$lib/components/common/tabs/Tab.svelte' import TriggerRetriesAndErrorHandler from '../TriggerRetriesAndErrorHandler.svelte' @@ -37,7 +38,7 @@ useOperatingWorkspace, useOperatingWorkspaceHref } from '$lib/components/operatingWorkspace.svelte' - const triggerLock = useTriggerLock() + const editRights = useEditRights() interface Props { useDrawer?: boolean @@ -103,8 +104,9 @@ // The acting user in the operating workspace arrives asynchronously, and an unknown user // refuses — so the editor stays read-only until the lookup lands, which is the safe answer. const can_write = $derived( - (permsPath === undefined || canWrite(permsPath, permsForWrite ?? {}, actingUser)) && - !$triggerLock + permsPath === undefined + ? editRights.roleCanAuthor('trigger') + : editRights.canEditItem('trigger', permsPath, permsForWrite) ) let drawerLoading = $state(true) let showLoading = $state(false) @@ -127,9 +129,10 @@ let preservePermissionedAs = $state(false) let isValid = $state(false) let optionTabSelected: 'error_handler' | 'retries' = $state('error_handler') - let errorHandlerSelected: ErrorHandler = $state('slack') - let error_handler_path: string | undefined = $state() - let error_handler_args: Record<string, any> = $state({}) + let errorHandler = $state(handlerDraftFromStored('error', undefined)) + const storedErrorHandler = $derived(handlerDraftToStored(errorHandler)) + const error_handler_path = $derived(storedErrorHandler.path) + const error_handler_args = $derived(storedErrorHandler.args) let retry: Retry | undefined = $state() let mode = $state<TriggerMode>('enabled') @@ -157,14 +160,20 @@ is_flow = itemKind === 'flow' }) + // Set by `openNew(…, { onSaveDraft })`: the caller keeps the trigger as its own + // draft, so Save hands it the config instead of writing it. + let saveDraftHandler: ((cfg: Record<string, any>) => boolean) | undefined = $state(undefined) + export async function openEdit( ePath: string, isFlow: boolean, defaultConfig?: Record<string, any>, fixedScriptPath_?: string ) { + saveDraftHandler = undefined // A `whoami` that failed earlier would otherwise pin this workspace to "unknown user". operatingUser.forgetFailures() + editRights.forgetFailures() let loadingTimeout = setTimeout(() => { showLoading = true }, 100) // Do not show loading spinner for the first 100ms @@ -206,8 +215,14 @@ export async function openNew( nis_flow: boolean, fixedScriptPath_?: string, - nDefaultValues?: Record<string, any> + nDefaultValues?: Record<string, any>, + opts: { + onSaveDraft?: (cfg: Record<string, any>) => boolean + /** A config this editor saved before, re-applied over the defaults. */ + draftConfig?: Record<string, any> + } = {} ) { + saveDraftHandler = opts.onSaveDraft let loadingTimeout = setTimeout(() => { showLoading = true }, 100) @@ -233,14 +248,18 @@ dirtyPath = false defaultValues = nDefaultValues mode = nDefaultValues?.mode ?? 'enabled' - error_handler_path = nDefaultValues?.error_handler_path ?? undefined - error_handler_args = nDefaultValues?.error_handler_args ?? {} + errorHandler = handlerDraftFromStored( + 'error', + nDefaultValues?.error_handler_path, + 'script', + nDefaultValues?.error_handler_args + ) retry = nDefaultValues?.retry ?? undefined - errorHandlerSelected = getHandlerType(error_handler_path ?? '') permissionedAs = undefined selectedPermissionedAs = undefined preservePermissionedAs = false originalConfig = undefined + if (opts.draftConfig) await loadTriggerConfig(opts.draftConfig) } finally { clearTimeout(loadingTimeout) drawerLoading = false @@ -266,10 +285,13 @@ mode = cfg?.mode ?? 'enabled' permsPath = cfg?.path permsForWrite = cfg?.extra_perms - error_handler_path = cfg?.error_handler_path - error_handler_args = cfg?.error_handler_args ?? {} + errorHandler = handlerDraftFromStored( + 'error', + cfg?.error_handler_path, + 'script', + cfg?.error_handler_args + ) retry = cfg?.retry - errorHandlerSelected = getHandlerType(error_handler_path ?? '') permissionedAs = cfg?.permissioned_as selectedPermissionedAs = cfg?.permissioned_as preservePermissionedAs = !!cfg?.permissioned_as @@ -326,6 +348,11 @@ } async function updateTrigger(): Promise<void> { + if (saveDraftHandler) { + if (!saveDraftHandler($state.snapshot(getSaveCfg()))) return + drawer?.closeDrawer() + return + } deploymentLoading = true const previousPath = initialPath const cfg = natsConfig @@ -424,7 +451,9 @@ ? can_write ? `Edit NATS trigger ${initialPath}` : `NATS trigger ${initialPath}` - : 'New NATS trigger'} + : saveDraftHandler + ? 'Draft NATS trigger' + : 'New NATS trigger'} on:close={() => (inline ? onClose?.() : drawer?.closeDrawer())} > {#snippet actions()} @@ -481,6 +510,7 @@ isLoading={deploymentLoading} {isDeployed} onUpdate={updateTrigger} + saveLabel={saveDraftHandler ? 'Save draft' : undefined} {onReset} {onDelete} {cloudDisabled} @@ -597,9 +627,7 @@ {optionTabSelected} {itemKind} {can_write} - bind:errorHandlerSelected - bind:error_handler_path - bind:error_handler_args + bind:errorHandler bind:retry /> </div> diff --git a/frontend/src/lib/components/triggers/postgres/PostgresTriggerEditor.svelte b/frontend/src/lib/components/triggers/postgres/PostgresTriggerEditor.svelte index 66702a54ab..c9ec98881c 100644 --- a/frontend/src/lib/components/triggers/postgres/PostgresTriggerEditor.svelte +++ b/frontend/src/lib/components/triggers/postgres/PostgresTriggerEditor.svelte @@ -21,6 +21,21 @@ drawer?.openNew(is_flow, initial_script_path, defaultValues) } + /** Edit a trigger that exists only as the caller's draft; Save hands the config back. */ + export async function openDraft( + scriptPath: string, + defaults: Record<string, any>, + saved: Record<string, any> | undefined, + onSaveDraft: (cfg: Record<string, any>) => boolean + ) { + open = true + await tickPainted() + drawer?.openNew(false, scriptPath, defaults as any, undefined, { + onSaveDraft, + draftConfig: saved + }) + } + let drawer: PostgresTriggerEditorInner | undefined = $state() </script> diff --git a/frontend/src/lib/components/triggers/postgres/PostgresTriggerEditorInner.svelte b/frontend/src/lib/components/triggers/postgres/PostgresTriggerEditorInner.svelte index 9025ed57a0..68ee8816b7 100644 --- a/frontend/src/lib/components/triggers/postgres/PostgresTriggerEditorInner.svelte +++ b/frontend/src/lib/components/triggers/postgres/PostgresTriggerEditorInner.svelte @@ -12,15 +12,14 @@ import TriggerRunnablePicker from '$lib/components/triggers/TriggerRunnablePicker.svelte' import { PostgresTriggerService, - type ErrorHandler, type Language, type Relations, type Retry, type TriggerMode } from '$lib/gen' import { usedTriggerKinds } from '$lib/stores' - import { canWrite, emptyString, emptyStringTrimmed, sendUserToast } from '$lib/utils' - import { useTriggerLock } from '$lib/operatorWriteRights' + import { emptyString, emptyStringTrimmed, sendUserToast } from '$lib/utils' + import { useEditRights } from '$lib/operatorWriteRights' import { withForkConflictRetry } from '$lib/utils/forkConflict' import Section from '$lib/components/Section.svelte' import { Loader2 } from 'lucide-svelte' @@ -37,12 +36,12 @@ import RelationPicker from './RelationPicker.svelte' import { invalidRelations, savePostgresTriggerFromCfg } from './utils' import CheckPostgresRequirement from './CheckPostgresRequirement.svelte' - import { base } from '$lib/base' import { untrack, type Snippet } from 'svelte' import TriggerEditorToolbar from '../TriggerEditorToolbar.svelte' import PermissionedAsLine from '../PermissionedAsLine.svelte' import TestingBadge from '../testingBadge.svelte' - import { getHandlerType, handleConfigChange, type Trigger } from '../utils' + import { handleConfigChange, type Trigger } from '../utils' + import { handlerDraftFromStored, handlerDraftToStored } from '../../handlerDraft.svelte' import TriggerRetriesAndErrorHandler from '../TriggerRetriesAndErrorHandler.svelte' import TriggerAdvancedBadges from '../TriggerAdvancedBadges.svelte' import { fade } from 'svelte/transition' @@ -59,7 +58,7 @@ useOperatingWorkspace, useOperatingWorkspaceHref } from '$lib/components/operatingWorkspace.svelte' - const triggerLock = useTriggerLock() + const editRights = useEditRights() interface Props { useDrawer?: boolean @@ -124,8 +123,9 @@ // The acting user in the operating workspace arrives asynchronously, and an unknown user // refuses — so the editor stays read-only until the lookup lands, which is the safe answer. const can_write = $derived( - (permsPath === undefined || canWrite(permsPath, permsForWrite ?? {}, actingUser)) && - !$triggerLock + permsPath === undefined + ? editRights.roleCanAuthor('trigger') + : editRights.canEditItem('trigger', permsPath, permsForWrite) ) let drawerLoading: boolean = $state(true) let showLoading: boolean = $state(false) @@ -154,9 +154,10 @@ let creatingPublication: boolean = $state(false) let pg14: boolean = $derived(postgresVersion.startsWith('14')) let optionTabSelected: 'error_handler' | 'retries' = $state('error_handler') - let errorHandlerSelected: ErrorHandler = $state('slack') - let error_handler_path: string | undefined = $state() - let error_handler_args: Record<string, any> = $state({}) + let errorHandler = $state(handlerDraftFromStored('error', undefined)) + const storedErrorHandler = $derived(handlerDraftToStored(errorHandler)) + const error_handler_path = $derived(storedErrorHandler.path) + const error_handler_args = $derived(storedErrorHandler.args) let retry: Retry | undefined = $state() let mode = $state<TriggerMode>('enabled') @@ -258,14 +259,20 @@ is_flow = itemKind === 'flow' }) + // Set by `openNew(…, { onSaveDraft })`: the caller keeps the trigger as its own + // draft, so Save hands it the config instead of writing it. + let saveDraftHandler: ((cfg: Record<string, any>) => boolean) | undefined = $state(undefined) + export async function openEdit( ePath: string, isFlow: boolean, defaultConfig?: Record<string, any>, fixedScriptPath_?: string ) { + saveDraftHandler = undefined // A `whoami` that failed earlier would otherwise pin this workspace to "unknown user". operatingUser.forgetFailures() + editRights.forgetFailures() let loadingTimeout = setTimeout(() => { showLoading = true }, 100) // Do not show loading spinner for the first 100ms @@ -307,8 +314,14 @@ nis_flow: boolean, fixedScriptPath_?: string, defaultValues?: Record<string, any>, - newDraft?: boolean + newDraft?: boolean, + opts: { + onSaveDraft?: (cfg: Record<string, any>) => boolean + /** A config this editor saved before, re-applied over the defaults. */ + draftConfig?: Record<string, any> + } = {} ) { + saveDraftHandler = opts.onSaveDraft let loadingTimeout = setTimeout(() => { showLoading = true }, 100) // Do not show loading spinner for the first 100ms @@ -343,15 +356,19 @@ table_to_track: [] } ] - error_handler_path = defaultValues?.error_handler_path ?? undefined - error_handler_args = defaultValues?.error_handler_args ?? {} + errorHandler = handlerDraftFromStored( + 'error', + defaultValues?.error_handler_path, + 'script', + defaultValues?.error_handler_args + ) retry = defaultValues?.retry ?? undefined - errorHandlerSelected = getHandlerType(error_handler_path ?? '') mode = defaultValues?.mode ?? 'enabled' permissionedAs = undefined selectedPermissionedAs = undefined preservePermissionedAs = false originalConfig = undefined + if (opts.draftConfig) await loadTriggerConfig(opts.draftConfig) } finally { clearTimeout(loadingTimeout) drawerLoading = false @@ -398,10 +415,13 @@ permsForWrite = cfg?.extra_perms transaction_to_track = [...cfg?.publication?.transaction_to_track] relations = cfg?.publication?.table_to_track ?? [] - error_handler_path = cfg?.error_handler_path - error_handler_args = cfg?.error_handler_args ?? {} + errorHandler = handlerDraftFromStored( + 'error', + cfg?.error_handler_path, + 'script', + cfg?.error_handler_args + ) retry = cfg?.retry - errorHandlerSelected = getHandlerType(error_handler_path ?? '') mode = cfg?.mode ?? 'enabled' permissionedAs = cfg?.permissioned_as selectedPermissionedAs = cfg?.permissioned_as @@ -477,6 +497,11 @@ } async function updateTrigger(): Promise<void> { + if (saveDraftHandler) { + if (!saveDraftHandler($state.snapshot(getSaveCfg()))) return + drawer?.closeDrawer() + return + } const cfg = postgresConfig if (!cfg) { return @@ -518,7 +543,7 @@ postgres_resource_path } }) - window.open(operatingHref(`${base}/scripts/add?id=${templateId}`)) + window.open(operatingHref(`/scripts/add?id=${templateId}`)) loading = false } catch (error) { loading = false @@ -608,7 +633,9 @@ ? can_write ? `Edit Postgres trigger ${initialPath}` : `Postgres trigger ${initialPath}` - : 'New Postgres trigger'} + : saveDraftHandler + ? 'Draft Postgres trigger' + : 'New Postgres trigger'} on:close={() => (inline ? onClose?.() : drawer?.closeDrawer())} > {#snippet actions()}{@render actionsSnippet()}{/snippet} @@ -663,6 +690,7 @@ isLoading={deploymentLoading} {isDeployed} onUpdate={updateTrigger} + saveLabel={saveDraftHandler ? 'Save draft' : undefined} {onReset} {onDelete} {mode} @@ -1007,9 +1035,7 @@ {optionTabSelected} {itemKind} {can_write} - bind:errorHandlerSelected - bind:error_handler_path - bind:error_handler_args + bind:errorHandler bind:retry /> </div> diff --git a/frontend/src/lib/components/triggers/scheduled/ScheduledPollPanel.svelte b/frontend/src/lib/components/triggers/scheduled/ScheduledPollPanel.svelte index 8f582107e4..2865ba8fd5 100644 --- a/frontend/src/lib/components/triggers/scheduled/ScheduledPollPanel.svelte +++ b/frontend/src/lib/components/triggers/scheduled/ScheduledPollPanel.svelte @@ -1,6 +1,5 @@ <script lang="ts"> import Label from '$lib/components/Label.svelte' - import { base } from '$lib/base' import Description from '$lib/components/Description.svelte' </script> @@ -17,7 +16,7 @@ 1. Choose a trigger script using the script picker that will poll for new events regularly <img class="shadow-lg rounded" alt="script picker" - src="{base}/script-picker.png" + src="/script-picker.png" width="400" /> </li> @@ -26,7 +25,7 @@ 2. Add logic to process each new event <img class="shadow-lg rounded" alt="create action" - src="{base}/create_action.png" + src="/create_action.png" width="500" /> </li> diff --git a/frontend/src/lib/components/triggers/schedules/ScheduleAdvancedOptions.svelte b/frontend/src/lib/components/triggers/schedules/ScheduleAdvancedOptions.svelte new file mode 100644 index 0000000000..675d232629 --- /dev/null +++ b/frontend/src/lib/components/triggers/schedules/ScheduleAdvancedOptions.svelte @@ -0,0 +1,598 @@ +<script lang="ts" module> + import { SettingService, type Retry } from '$lib/gen' + import { + handlerDraftFromStored, + handlerDraftToStored, + type HandlerDraft, + type HandlerMode + } from '$lib/components/handlerDraft.svelte' + + export type ScheduleAdvancedState = { + errorHandler: HandlerDraft + wsErrorHandlerMuted: boolean + failedTimes: number + failedExact: boolean + recoveryHandler: HandlerDraft + recoveredTimes: number + successHandler: HandlerDraft + retry: Retry | undefined + dynamicSkipPath: string | undefined + tag: string | undefined + } + + /** A schedule handler stored as `<script|flow>/<path>`, or none (shown on the Slack tab). */ + export function scheduleHandlerDraft( + mode: HandlerMode, + fullPath?: string | null, + args?: Record<string, any> | null + ): HandlerDraft { + const [kind, ...path] = (fullPath ?? '').split('/') + return handlerDraftFromStored(mode, path.join('/'), kind === 'flow' ? 'flow' : 'script', args, { + emptySelected: 'slack' + }) + } + + /** The `<script|flow>/<path>` a schedule stores, with its extra args. */ + export function scheduleHandlerStored(draft: HandlerDraft) { + const { path, kind, args } = handlerDraftToStored(draft) + return { path: path ? `${kind}/${path}` : undefined, args } + } + + export function emptyScheduleAdvanced(): ScheduleAdvancedState { + return { + errorHandler: scheduleHandlerDraft('error'), + wsErrorHandlerMuted: false, + failedTimes: 1, + failedExact: false, + recoveryHandler: scheduleHandlerDraft('recovery'), + recoveredTimes: 1, + successHandler: scheduleHandlerDraft('success'), + retry: undefined, + dynamicSkipPath: undefined, + tag: undefined + } + } + + /** The Advanced tabs of a new schedule: the workspace's default error, recovery + * and success handlers, where it sets them. */ + export async function loadDefaultScheduleAdvanced(wsId: string): Promise<ScheduleAdvancedState> { + const a = emptyScheduleAdvanced() + const [err, rec, suc] = (await Promise.all( + ['error', 'recovery', 'success'].map((k) => + SettingService.getGlobal({ key: `default_${k}_handler_${wsId}` }) + ) + )) as any[] + if (err) { + a.wsErrorHandlerMuted = err.wsErrorHandlerMuted + a.errorHandler = scheduleHandlerDraft( + 'error', + err.errorHandlerPath, + err.errorHandlerExtraArgs + ) + a.failedTimes = err.failedTimes + a.failedExact = err.failedExact + } + if (rec) { + a.recoveryHandler = scheduleHandlerDraft( + 'recovery', + rec.recoveryHandlerPath, + rec.recoveryHandlerExtraArgs + ) + a.recoveredTimes = rec.recoveredTimes + } + if (suc) { + a.successHandler = scheduleHandlerDraft( + 'success', + suc.successHandlerPath, + suc.successHandlerExtraArgs + ) + } + return a + } + + /** The schedule fields the Advanced tabs own, as the schedule API takes them. */ + export function scheduleAdvancedCfg(a: ScheduleAdvancedState) { + const error = scheduleHandlerStored(a.errorHandler) + const recovery = scheduleHandlerStored(a.recoveryHandler) + const success = scheduleHandlerStored(a.successHandler) + return { + on_failure: error.path, + on_failure_times: a.failedTimes, + on_failure_exact: a.failedExact, + on_failure_extra_args: error.path ? error.args : undefined, + on_recovery: recovery.path, + on_recovery_times: a.recoveredTimes, + on_recovery_extra_args: recovery.args, + on_success: success.path, + on_success_extra_args: success.args, + ws_error_handler_muted: a.wsErrorHandlerMuted, + retry: a.retry, + tag: a.tag, + dynamic_skip: a.dynamicSkipPath + } + } +</script> + +<script lang="ts"> + import { Alert, Button, Tab, Tabs } from '$lib/components/common' + import ErrorOrRecoveryHandler from '$lib/components/ErrorOrRecoveryHandler.svelte' + import Toggle from '$lib/components/Toggle.svelte' + import Tooltip from '$lib/components/Tooltip.svelte' + import Dropdown from '$lib/components/DropdownV2.svelte' + import ScriptPicker from '$lib/components/ScriptPicker.svelte' + import Section from '$lib/components/Section.svelte' + import Label from '$lib/components/Label.svelte' + import WorkerTagPicker from '$lib/components/WorkerTagPicker.svelte' + import FlowRetries from '$lib/components/flows/content/FlowRetries.svelte' + import { ScheduleService } from '$lib/gen' + import { enterpriseLicense } from '$lib/stores' + import { emptyString, sendUserToast } from '$lib/utils' + import { Loader2, Save } from 'lucide-svelte' + + // The schedule drawer's Advanced tabs, shared with editors that configure a + // schedule before it exists (the pipeline editor's create wizard). + interface Props { + wsId: string | undefined + itemKind: 'flow' | 'script' + canWrite: boolean + loading?: boolean + errorHandler: HandlerDraft + wsErrorHandlerMuted: boolean + failedTimes: number + failedExact: boolean + recoveryHandler: HandlerDraft + recoveredTimes: number + successHandler: HandlerDraft + retry: Retry | undefined + dynamicSkipPath: string | undefined + tag: string | undefined + } + + let { + wsId, + itemKind, + canWrite, + loading = false, + errorHandler = $bindable(), + wsErrorHandlerMuted = $bindable(), + failedTimes = $bindable(), + failedExact = $bindable(), + recoveryHandler = $bindable(), + recoveredTimes = $bindable(), + successHandler = $bindable(), + retry = $bindable(), + dynamicSkipPath = $bindable(), + tag = $bindable() + }: Props = $props() + + let optionTabSelected: + | 'error_handler' + | 'recovery_handler' + | 'success_handler' + | 'retries' + | 'dynamic_skip' + | 'tag' = $state('error_handler') + + // Carry the acting workspace onto "create from template" routes, so the script is created + // in the workspace this schedule lives in. + const wsParam = $derived(wsId ? `&workspace=${encodeURIComponent(wsId)}` : '') + + const errorHandlerPath = $derived(scheduleHandlerStored(errorHandler).path) + const recoveryHandlerPath = $derived(scheduleHandlerStored(recoveryHandler).path) + + async function saveAsDefaultErrorHandler(overrideExisting: boolean) { + if (!$enterpriseLicense) { + sendUserToast(`Setting default error handler is an enterprise edition feature`, true) + return + } + if (wsId) { + const handler = scheduleHandlerStored(errorHandler) + await ScheduleService.setDefaultErrorOrRecoveryHandler({ + workspace: wsId!, + requestBody: { + handler_type: 'error', + override_existing: overrideExisting, + path: handler.path, + extra_args: handler.args, + number_of_occurence: failedTimes, + number_of_occurence_exact: failedExact, + workspace_handler_muted: wsErrorHandlerMuted + } + }) + if (handler.path !== undefined) { + sendUserToast(`Default error handler saved to ${handler.path}`, false) + } else { + sendUserToast(`Default error handler reset`, false) + } + } + } + + async function saveAsDefaultRecoveryHandler(overrideExisting: boolean) { + if (!$enterpriseLicense) { + sendUserToast(`Setting default recovery handler is an enterprise edition feature`, true) + return + } + if (wsId) { + const handler = scheduleHandlerStored(recoveryHandler) + await ScheduleService.setDefaultErrorOrRecoveryHandler({ + workspace: wsId!, + requestBody: { + handler_type: 'recovery', + override_existing: overrideExisting, + path: handler.path, + extra_args: handler.args, + number_of_occurence: recoveredTimes + } + }) + if (handler.path !== undefined) { + sendUserToast(`Default recovery handler saved to ${handler.path}`, false) + } else { + sendUserToast(`Default recovery handler reset`, false) + } + } + } + + async function saveAsDefaultSuccessHandler(overrideExisting: boolean) { + if (!$enterpriseLicense) { + sendUserToast(`Setting default success handler is an enterprise edition feature`, true) + return + } + if (wsId) { + const handler = scheduleHandlerStored(successHandler) + await ScheduleService.setDefaultErrorOrRecoveryHandler({ + workspace: wsId!, + requestBody: { + handler_type: 'success', + override_existing: overrideExisting, + path: handler.path, + extra_args: handler.args, + number_of_occurence: recoveredTimes + } + }) + if (handler.path !== undefined) { + sendUserToast(`Default success handler saved to ${handler.path}`, false) + } else { + sendUserToast(`Default success handler reset`, false) + } + } + } +</script> + +<div class="flex flex-col gap-2 min-h-96"> + {#if !loading} + <Tabs bind:selected={optionTabSelected}> + <Tab value="error_handler" label="Error Handler" /> + <Tab value="recovery_handler" label="Recovery Handler" /> + <Tab value="success_handler" label="Success Handler" /> + <Tab value="retries" label="Retries" /> + <Tab value="dynamic_skip" label="Dynamic skip" /> + {#if itemKind === 'script'} + <Tab value="tag" label="Custom tag" /> + {/if} + </Tabs> + {#if optionTabSelected === 'error_handler'} + <Section label="Error handler"> + {#snippet header()} + <div class="flex flex-row gap-2"> + {#if !$enterpriseLicense}<span class="text-xs text-secondary">(ee only)</span>{/if} + </div> + {/snippet} + {#snippet action()} + <div class="flex flex-row items-center gap-1 text-xs text-secondary"> + <Dropdown + disabled={!canWrite} + items={[ + { + displayName: `Override future schedules only`, + action: () => saveAsDefaultErrorHandler(false) + }, + { + displayName: 'Override all existing', + type: 'delete', + action: () => saveAsDefaultErrorHandler(true) + } + ]} + > + {#snippet buttonReplacement()} + <Save size={12} class="mr-1" /> + Set as default + {/snippet} + </Dropdown> + </div> + {/snippet} + <div class="flex flex-row py-2"> + <Toggle + size="xs" + disabled={!canWrite || !$enterpriseLicense} + bind:checked={wsErrorHandlerMuted} + options={{ right: 'Mute workspace error handler for this schedule' }} + /> + </div> + + <ErrorOrRecoveryHandler + workspace={wsId} + isEditable={canWrite} + errorOrRecovery="error" + showScriptHelpText={true} + bind:draft={errorHandler} + toggleText="Alert channel on error" + customScriptTemplate="/scripts/add?hub=hub%2F19743%2Fwindmill%2Fschedule_error_handler_template" + > + {#snippet customTabTooltip()} + <Tooltip> + <div class="flex gap-20 items-start mt-3"> + <div class="text-xs" + >The following args will be passed to the error handler: + <ul class="mt-1 ml-2"> + <li + ><b>workspace_id</b>: The ID of the workspace that the schedule belongs to.</li + > + <li><b>job_id</b>: The UUID of the job that errored.</li> + <li><b>path</b>: The path of the script or flow that failed.</li> + <li><b>is_flow</b>: Whether the runnable is a flow.</li> + <li><b>schedule_path</b>: The path of the schedule.</li> + <li><b>error</b>: The error details.</li> + <li + ><b>failed_times</b>: Minimum number of times the schedule failed before + calling the error handler.</li + > + <li><b>started_at</b>: The start datetime of the latest job that failed.</li> + </ul> + </div> + </div> + </Tooltip> + {/snippet} + </ErrorOrRecoveryHandler> + <div class="flex flex-row items-center justify-between"> + <div class="flex flex-row items-center mt-4 font-semibold text-xs gap-2"> + <p class={emptyString(errorHandlerPath) ? 'text-primary' : ''}> + Triggered when schedule failed</p + > + <select + class="!w-14" + bind:value={failedExact} + disabled={!canWrite || !$enterpriseLicense || emptyString(errorHandlerPath)} + > + <option value={false}>>=</option> + <option value={true}>==</option> + </select> + <input + type="number" + class="!w-14 text-center {emptyString(errorHandlerPath) ? 'text-primary' : ''}" + bind:value={failedTimes} + disabled={!canWrite || !$enterpriseLicense} + min="1" + /> + <p class={emptyString(errorHandlerPath) ? 'text-primary' : ''} + >time{failedTimes > 1 ? 's in a row' : ''}</p + > + </div> + </div> + </Section> + {:else if optionTabSelected === 'recovery_handler'} + {@const disabled = !canWrite || emptyString($enterpriseLicense)} + <Section label="Recovery handler"> + {#snippet header()} + <div class="flex flex-row gap-2"> + {#if !$enterpriseLicense}<span class="text-xs text-secondary">(ee only)</span>{/if} + </div> + {/snippet} + {#snippet action()} + <div class="flex flex-row items-center text-secondary text-xs gap-2"> + defaults + <Dropdown + {disabled} + items={[ + { + displayName: `Override future schedules only`, + action: () => saveAsDefaultRecoveryHandler(false) + }, + { + displayName: 'Override all existing', + type: 'delete', + action: () => saveAsDefaultRecoveryHandler(true) + } + ]} + > + {#snippet buttonReplacement()} + <Save size={12} class="mr-1" /> + Set as default + {/snippet} + </Dropdown> + </div> + {/snippet} + <ErrorOrRecoveryHandler + workspace={wsId} + isEditable={!disabled} + errorOrRecovery="recovery" + bind:draft={recoveryHandler} + toggleText="Alert channel when error recovered" + customScriptTemplate="/scripts/add?hub=hub%2F9082%2Fwindmill%2Fschedule_recovery_handler_template" + > + {#snippet customTabTooltip()} + <Tooltip> + <div class="flex gap-20 items-start mt-3"> + <div class="text-xs" + >The following args will be passed to the recovery handler: + <ul class="mt-1 ml-2"> + <li><b>path</b>: The path of the script or flow that recovered.</li> + <li><b>is_flow</b>: Whether the runnable is a flow.</li> + <li><b>schedule_path</b>: The path of the schedule.</li> + <li><b>error</b>: The error of the last job that errored</li> + <li><b>error_started_at</b>: The start datetime of the last job that errored</li + > + <li + ><b>success_times</b>: The number of times the schedule succeeded before + calling the recovery handler.</li + > + <li><b>success_result</b>: The result of the latest successful job</li> + <li + ><b>success_started_at</b>: The start datetime of the latest successful job</li + > + </ul> + </div> + </div> + </Tooltip> + {/snippet} + </ErrorOrRecoveryHandler> + <div class="flex flex-row items-center justify-between"> + <div + class="flex flex-row items-center mt-5 font-semibold text-xs {emptyString( + recoveryHandlerPath + ) + ? 'text-primary' + : ''}" + > + <p>Triggered when schedule recovered</p> + <input + type="number" + class="!w-14 mx-2 text-center" + bind:value={recoveredTimes} + min="1" + {disabled} + /> + <p>time{recoveredTimes > 1 ? 's in a row' : ''}</p> + </div> + </div> + </Section> + {:else if optionTabSelected === 'success_handler'} + {@const disabled = !canWrite || emptyString($enterpriseLicense)} + <Section label="Success handler"> + {#snippet header()} + <div class="flex flex-row gap-2"> + {#if !$enterpriseLicense}<span class="text-xs text-secondary">(ee only)</span>{/if} + </div> + {/snippet} + {#snippet action()} + <div class="flex flex-row items-center text-secondary text-xs gap-2"> + defaults + <Dropdown + {disabled} + items={[ + { + displayName: `Override future schedules only`, + action: () => saveAsDefaultSuccessHandler(false) + }, + { + displayName: 'Override all existing', + type: 'delete', + action: () => saveAsDefaultSuccessHandler(true) + } + ]} + > + {#snippet buttonReplacement()} + <Save size={12} class="mr-1" /> + Set as default + {/snippet} + </Dropdown> + </div> + {/snippet} + <ErrorOrRecoveryHandler + workspace={wsId} + isEditable={!disabled} + errorOrRecovery="success" + bind:draft={successHandler} + toggleText="Alert channel when successful" + customScriptTemplate="/scripts/add?hub=hub%2F9071%2Fwindmill%2Fschedule_success_handler_template" + > + {#snippet customTabTooltip()} + <Tooltip> + <div class="flex gap-20 items-start mt-3"> + <div class="text-xs" + >The following args will be passed to the success handler: + <ul class="mt-1 ml-2"> + <li><b>path</b>: The path of the script or flow that succeeded.</li> + <li><b>is_flow</b>: Whether the runnable is a flow.</li> + <li><b>schedule_path</b>: The path of the schedule.</li> + <li><b>success_result</b>: The result of the successful job</li> + <li><b>success_started_at</b>: The start datetime of the successful job</li> + </ul> + </div> + </div> + </Tooltip> + {/snippet} + </ErrorOrRecoveryHandler> + </Section> + {:else if optionTabSelected === 'retries'} + {@const disabled = !canWrite || emptyString($enterpriseLicense)} + <Section label="Retries"> + {#snippet header()} + <div class="flex flex-row gap-2"> + {#if !$enterpriseLicense}<span class="text-xs text-secondary">(ee only)</span>{/if} + </div> + <Tooltip> + If defined, upon error this schedule will be retried with a delay and a maximum number + of attempts as defined below. + <br /> + This is only available for individual script. For flows, retries can be set on each flow + step in the flow editor. + </Tooltip> + {/snippet} + {#if itemKind !== 'script'} + <Alert type="info" title="Only available for scripts" class="mb-2"> + Error Handler and Retries are only available for scripts. For flows, use the built-in <a + href="https://www.windmill.dev/docs/flows/flow_error_handler" + target="_blank">error handler</a + > + and <a href="https://www.windmill.dev/docs/flows/retries" target="_blank">retries</a>. + </Alert> + {:else} + <FlowRetries bind:flowModuleRetry={retry} disabled={itemKind !== 'script' || disabled} /> + {/if} + </Section> + {:else if optionTabSelected === 'dynamic_skip'} + <Section label="Dynamic skip"> + {#snippet header()} + <Tooltip> + Optional script to filter scheduled dates. Receives the proposed datetime and returns + boolean. True = run on this date, False = skip to next occurrence. + </Tooltip> + {/snippet} + <div class="flex flex-col gap-6"> + <Label label="Dynamic skip script"> + <div class="flex flex-row"> + <ScriptPicker + workspace={wsId} + disabled={!canWrite} + bind:scriptPath={dynamicSkipPath} + kinds={['script']} + allowRefresh={canWrite} + clearable + /> + {#if !dynamicSkipPath} + <Button + btnClasses="ml-4 whitespace-nowrap" + variant="default" + size="xs" + href="/scripts/add?hub=hub%2F19822%2Fwindmill%2Fdynamic_skip_template{wsParam}" + disabled={!canWrite} + target="_blank" + > + Create from template + </Button> + {/if} + </div> + </Label> + <Alert type="info" size="xs" title="Handler requirements"> + Handler must return a boolean value. Return true to execute the scheduled job, false to + skip. + </Alert> + </div> + </Section> + {:else if optionTabSelected === 'tag'} + <Section + label="Custom script tag" + tooltip="When set, the script tag will be overridden by this tag" + > + <WorkerTagPicker + bind:tag + workspaceId={wsId} + popupPlacement="top-end" + disabled={!canWrite} + /> + </Section> + {/if} + {:else} + <Loader2 class="animate-spin" /> + {/if} +</div> diff --git a/frontend/src/lib/components/triggers/schedules/ScheduleEditor.svelte b/frontend/src/lib/components/triggers/schedules/ScheduleEditor.svelte index 78e569d3f3..295498f428 100644 --- a/frontend/src/lib/components/triggers/schedules/ScheduleEditor.svelte +++ b/frontend/src/lib/components/triggers/schedules/ScheduleEditor.svelte @@ -1,6 +1,7 @@ <script lang="ts"> import { tickPainted } from '$lib/utils/paint' import type ScheduleEditorInner from './ScheduleEditorInner.svelte' + import type { Schedule } from '$lib/gen' let { onUpdate }: { onUpdate?: (path?: string) => void } = $props() @@ -29,6 +30,17 @@ drawer?.openNew(is_flow, initial_script_path, undefined, schedule_path, fixedScriptPath) } + /** Edit a schedule that exists only as the caller's draft; Save hands it back. */ + export async function openDraft( + cfg: Schedule, + onSaveDraft: (cfg: Record<string, any>) => boolean + ) { + open = true + await loadInner() + await tickPainted() + drawer?.openNew(false, cfg.script_path, cfg, undefined, cfg.script_path, { onSaveDraft }) + } + let drawer: ScheduleEditorInner | undefined = $state() </script> diff --git a/frontend/src/lib/components/triggers/schedules/ScheduleEditorInner.svelte b/frontend/src/lib/components/triggers/schedules/ScheduleEditorInner.svelte index 1563407150..df09a81671 100644 --- a/frontend/src/lib/components/triggers/schedules/ScheduleEditorInner.svelte +++ b/frontend/src/lib/components/triggers/schedules/ScheduleEditorInner.svelte @@ -1,11 +1,19 @@ <script lang="ts"> - import { Alert, Badge, Button, ButtonType, Tab, Tabs } from '$lib/components/common' + import { Alert, Badge, Button, ButtonType } from '$lib/components/common' import { clearPageDrawerAnchor, setPageDrawerAnchor } from '$lib/components/sessions/pageDrawerSession' import { SCHEDULES_PATH } from '$lib/components/sessions/previewPaths' import TriggerAdvancedBadges from '../TriggerAdvancedBadges.svelte' + import ScheduleAdvancedOptions, { + emptyScheduleAdvanced, + loadDefaultScheduleAdvanced, + scheduleAdvancedCfg, + scheduleHandlerDraft, + scheduleHandlerStored + } from './ScheduleAdvancedOptions.svelte' + import type { HandlerDraft } from '$lib/components/handlerDraft.svelte' import Drawer from '$lib/components/common/drawer/Drawer.svelte' import DrawerContent from '$lib/components/common/drawer/DrawerContent.svelte' import CronInput from '$lib/components/CronInput.svelte' @@ -15,36 +23,25 @@ import ScriptPicker from '$lib/components/ScriptPicker.svelte' import { loadSchema } from '$lib/infer' import PipelineLockedRunnableInfo from '$lib/components/triggers/PipelineLockedRunnableInfo.svelte' - import ErrorOrRecoveryHandler, { - handlerFullPath - } from '$lib/components/ErrorOrRecoveryHandler.svelte' import Toggle from '$lib/components/Toggle.svelte' import Tooltip from '$lib/components/Tooltip.svelte' - import Dropdown from '$lib/components/DropdownV2.svelte' import { FlowService, ScheduleService, type Script, ScriptService, type Flow, - SettingService, type Retry, - type Schedule, - type ErrorHandler + type Schedule } from '$lib/gen' - import { enterpriseLicense } from '$lib/stores' - import { canWrite, emptyString, formatCron, sendUserToast, cronV1toV2 } from '$lib/utils' - import { useScheduleLock } from '$lib/operatorWriteRights' - import { base } from '$lib/base' + import { emptyString, formatCron, sendUserToast, cronV1toV2 } from '$lib/utils' + import { useEditRights } from '$lib/operatorWriteRights' import Section from '$lib/components/Section.svelte' - import { List, Loader2, Save, AlertTriangle } from 'lucide-svelte' + import { List, Loader2, AlertTriangle } from 'lucide-svelte' import autosize from '$lib/autosize' import TriggerEditorToolbar from '$lib/components/triggers/TriggerEditorToolbar.svelte' import { saveScheduleFromCfg } from '$lib/components/flows/scheduleUtils' import DateTimeInput from '$lib/components/DateTimeInput.svelte' - import FlowRetries from '$lib/components/flows/content/FlowRetries.svelte' - import Label from '$lib/components/Label.svelte' - import WorkerTagPicker from '$lib/components/WorkerTagPicker.svelte' import { runScheduleNow } from '../scheduled/utils' import { handleConfigChange } from '../utils' import { withForkConflictRetry } from '$lib/utils/forkConflict' @@ -55,7 +52,7 @@ import PermissionedAsLine from '../PermissionedAsLine.svelte' import { useActingUser } from '$lib/actingUser.svelte' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' - const scheduleLock = useScheduleLock() + const editRights = useEditRights() let { useDrawer = true, @@ -74,12 +71,6 @@ trigger = undefined } = $props() - let optionTabSelected: - | 'error_handler' - | 'recovery_handler' - | 'success_handler' - | 'retries' - | 'dynamic_skip' = $state('error_handler') let initialPath = $state('') let edit = $state(true) let schedule: string = $state('0 0 12 * *') @@ -91,19 +82,11 @@ let paused_until: string | undefined = $state(undefined) let itemKind: 'flow' | 'script' = $state('script') let is_flow: boolean = $derived.by(() => itemKind === 'flow') - let errorHandleritemKind: 'flow' | 'script' = $state('script') let wsErrorHandlerMuted: boolean = $state(false) - let errorHandlerPath: string | undefined = $state(undefined) - let errorHandlerSelected: ErrorHandler = $state('slack') - let errorHandlerExtraArgs: Record<string, any> = $state({}) - let recoveryHandlerPath: string | undefined = $state(undefined) - let recoveryHandlerSelected: ErrorHandler = $state('slack') - let recoveryHandlerItemKind: 'flow' | 'script' = $state('script') - let recoveryHandlerExtraArgs: Record<string, any> = $state({}) - let successHandlerPath: string | undefined = $state(undefined) - let successHandlerSelected: ErrorHandler = $state('slack') - let successHandlerItemKind: 'flow' | 'script' = $state('script') - let successHandlerExtraArgs: Record<string, any> = $state({}) + let errorHandler: HandlerDraft = $state(scheduleHandlerDraft('error')) + let recoveryHandler: HandlerDraft = $state(scheduleHandlerDraft('recovery')) + let successHandler: HandlerDraft = $state(scheduleHandlerDraft('success')) + const errorHandlerPath = $derived(scheduleHandlerStored(errorHandler).path) let failedTimes = $state(1) let failedExact = $state(false) let recoveredTimes = $state(1) @@ -139,6 +122,10 @@ let isValid = $state(true) let allowSchedule = $derived(isValid && validCRON && script_path != '') let deploymentLoading = $state(false) + // Set by `openNew({ onSaveDraft })`: the caller keeps the schedule as its own + // draft, so Save hands it the config instead of writing it, and nothing may + // autosave a workspace trigger draft for a path that is not deployed. + let saveDraftHandler: ((cfg: Record<string, any>) => boolean) | undefined = $state(undefined) let permissionedAs = $state<string | undefined>(undefined) let selectedPermissionedAs = $state<string | undefined>(undefined) let preservePermissionedAs = $state(false) @@ -150,7 +137,9 @@ const acting = useActingUser(() => wsId) const actingUser = $derived(acting.current) const can_write = $derived( - (permsPath === undefined || canWrite(permsPath, extraPerms, actingUser)) && !$scheduleLock + permsPath === undefined + ? editRights.roleCanAuthor('schedule') + : editRights.canEditItem('schedule', permsPath, extraPerms) ) // Editing the runnable is closed to operators, and an unresolved acting user is no // evidence that this one isn't. @@ -159,19 +148,16 @@ !allowSchedule || pathError != '' || emptyString(script_path) || - (errorHandlerSelected == 'slack' && - !emptyString(errorHandlerPath) && - emptyString(errorHandlerExtraArgs['channel'])) || + (errorHandler.selected == 'slack' && + !!errorHandler.slack.path && + emptyString(errorHandler.slack.args['channel'])) || !can_write ) - // Carry the acting workspace onto "create from template" routes, so the script is created - // in the workspace this schedule lives in. - const wsParam = $derived(wsId ? `&workspace=${encodeURIComponent(wsId)}` : '') const scheduleCfg = $derived.by(getScheduleCfg) const draftSync = useTriggerDraftSync({ itemKind: 'trigger_schedule', - path: () => initialPath, + path: () => (saveDraftHandler ? '' : initialPath), workspace: () => wsId, drawerLoading: () => drawerLoading, getCfg: () => scheduleCfg, @@ -190,6 +176,8 @@ }, 100) // Do not show loading spinner for the first 100ms drawerLoading = true acting.forgetFailures() + editRights.forgetFailures() + saveDraftHandler = undefined try { drawer?.openDrawer() setPageDrawerAnchor(SCHEDULES_PATH, ePath) @@ -214,111 +202,27 @@ } } + function setScheduleHandlers(s: Partial<Schedule>) { + errorHandler = scheduleHandlerDraft('error', s.on_failure, s.on_failure_extra_args) + failedTimes = s.on_failure ? (s.on_failure_times ?? 1) : 1 + failedExact = s.on_failure ? (s.on_failure_exact ?? false) : false + recoveryHandler = scheduleHandlerDraft('recovery', s.on_recovery, s.on_recovery_extra_args) + recoveredTimes = s.on_recovery ? (s.on_recovery_times ?? 1) : 1 + successHandler = scheduleHandlerDraft('success', s.on_success, s.on_success_extra_args) + } + async function setScheduleHandler(s?: Schedule) { if (s) { - if (s.on_failure) { - let splitted = s.on_failure.split('/') - errorHandleritemKind = splitted[0] as 'flow' | 'script' - errorHandlerPath = splitted.slice(1)?.join('/') - failedTimes = s.on_failure_times ?? 1 - failedExact = s.on_failure_exact ?? false - errorHandlerExtraArgs = s.on_failure_extra_args ?? {} - errorHandlerSelected = getHandlerType('error', errorHandlerPath) - } else { - errorHandlerPath = undefined - errorHandleritemKind = 'script' - errorHandlerExtraArgs = {} - failedExact = false - failedTimes = 1 - errorHandlerSelected = 'slack' - } - if (s.on_recovery) { - let splitted = s.on_recovery.split('/') - recoveryHandlerItemKind = splitted[0] as 'flow' | 'script' - recoveryHandlerPath = splitted.slice(1)?.join('/') - recoveredTimes = s.on_recovery_times ?? 1 - recoveryHandlerExtraArgs = s.on_recovery_extra_args ?? {} - recoveryHandlerSelected = getHandlerType('recovery', recoveryHandlerPath) - } else { - recoveryHandlerPath = undefined - recoveryHandlerItemKind = 'script' - recoveredTimes = 1 - recoveryHandlerSelected = 'slack' - recoveryHandlerExtraArgs = {} - } - if (s.on_success) { - let splitted = s.on_success.split('/') - successHandlerItemKind = splitted[0] as 'flow' | 'script' - successHandlerPath = splitted.slice(1)?.join('/') - successHandlerExtraArgs = s.on_success_extra_args ?? {} - successHandlerSelected = getHandlerType('success', successHandlerPath) - } else { - successHandlerPath = undefined - successHandlerItemKind = 'script' - successHandlerSelected = 'slack' - successHandlerExtraArgs = {} - } + setScheduleHandlers(s) } else { - let defaultErrorHandlerMaybe = undefined - let defaultRecoveryHandlerMaybe = undefined - let defaultSuccessHandlerMaybe = undefined - if (wsId) { - defaultErrorHandlerMaybe = (await SettingService.getGlobal({ - key: 'default_error_handler_' + wsId! - })) as any - defaultRecoveryHandlerMaybe = (await SettingService.getGlobal({ - key: 'default_recovery_handler_' + wsId! - })) as any - defaultSuccessHandlerMaybe = (await SettingService.getGlobal({ - key: 'default_success_handler_' + wsId! - })) as any - } - - if (defaultErrorHandlerMaybe !== undefined && defaultErrorHandlerMaybe !== null) { - wsErrorHandlerMuted = defaultErrorHandlerMaybe['wsErrorHandlerMuted'] - let splitted = (defaultErrorHandlerMaybe['errorHandlerPath'] as string).split('/') - errorHandleritemKind = splitted[0] as 'flow' | 'script' - errorHandlerPath = splitted.slice(1)?.join('/') - errorHandlerExtraArgs = defaultErrorHandlerMaybe['errorHandlerExtraArgs'] - errorHandlerSelected = getHandlerType('error', errorHandlerPath) - failedTimes = defaultErrorHandlerMaybe['failedTimes'] - failedExact = defaultErrorHandlerMaybe['failedExact'] - } else { - wsErrorHandlerMuted = false - errorHandlerPath = undefined - errorHandleritemKind = 'script' - errorHandlerExtraArgs = {} - errorHandlerSelected = 'slack' - failedTimes = 1 - failedExact = false - } - if (defaultRecoveryHandlerMaybe !== undefined && defaultRecoveryHandlerMaybe !== null) { - let splitted = (defaultRecoveryHandlerMaybe['recoveryHandlerPath'] as string).split('/') - recoveryHandlerItemKind = splitted[0] as 'flow' | 'script' - recoveryHandlerPath = splitted.slice(1)?.join('/') - recoveryHandlerExtraArgs = defaultRecoveryHandlerMaybe['recoveryHandlerExtraArgs'] - recoveryHandlerSelected = getHandlerType('recovery', recoveryHandlerPath) - recoveredTimes = defaultRecoveryHandlerMaybe['recoveredTimes'] - } else { - recoveryHandlerPath = undefined - recoveryHandlerItemKind = 'script' - recoveryHandlerExtraArgs = {} - recoveryHandlerSelected = 'slack' - recoveredTimes = 1 - } - if (defaultSuccessHandlerMaybe !== undefined && defaultSuccessHandlerMaybe !== null) { - let splitted = (defaultSuccessHandlerMaybe['successHandlerPath'] as string).split('/') - successHandlerItemKind = splitted[0] as 'flow' | 'script' - successHandlerPath = splitted.slice(1)?.join('/') - successHandlerExtraArgs = defaultSuccessHandlerMaybe['successHandlerExtraArgs'] - successHandlerSelected = getHandlerType('success', successHandlerPath) - recoveredTimes = defaultSuccessHandlerMaybe['recoveredTimes'] - } else { - successHandlerPath = undefined - successHandlerItemKind = 'script' - successHandlerExtraArgs = {} - successHandlerSelected = 'slack' - } + const d = wsId ? await loadDefaultScheduleAdvanced(wsId) : emptyScheduleAdvanced() + wsErrorHandlerMuted = d.wsErrorHandlerMuted + errorHandler = d.errorHandler + failedTimes = d.failedTimes + failedExact = d.failedExact + recoveryHandler = d.recoveryHandler + recoveredTimes = d.recoveredTimes + successHandler = d.successHandler } } @@ -328,14 +232,16 @@ defaultValues?: Schedule, schedule_path?: string, fixedScriptPath_?: string, - opts: { getDraft?: boolean } = {} + opts: { getDraft?: boolean; onSaveDraft?: (cfg: Record<string, any>) => boolean } = {} ) { const getDraft = opts.getDraft ?? true + saveDraftHandler = opts.onSaveDraft let loadingTimeout = setTimeout(() => { showLoading = true }, 100) // Do not show loading spinner for the first 100ms drawerLoading = true acting.forgetFailures() + editRights.forgetFailures() try { let s: Schedule | undefined if (schedule_path) { @@ -389,6 +295,7 @@ no_flow_overlap = s?.no_flow_overlap ?? false wsErrorHandlerMuted = s?.ws_error_handler_muted ?? false retry = s?.retry ?? undefined + dynamicSkipPath = s?.dynamic_skip ?? undefined await setScheduleHandler(s) permissionedAs = undefined @@ -432,93 +339,6 @@ } } - async function saveAsDefaultErrorHandler(overrideExisting: boolean) { - if (!$enterpriseLicense) { - sendUserToast(`Setting default error handler is an enterprise edition feature`, true) - return - } - if (wsId) { - await ScheduleService.setDefaultErrorOrRecoveryHandler({ - workspace: wsId!, - requestBody: { - handler_type: 'error', - override_existing: overrideExisting, - path: - errorHandlerPath == undefined - ? undefined - : handlerFullPath(errorHandlerSelected, errorHandleritemKind, errorHandlerPath), - extra_args: errorHandlerExtraArgs, - number_of_occurence: failedTimes, - number_of_occurence_exact: failedExact, - workspace_handler_muted: wsErrorHandlerMuted - } - }) - if (errorHandlerPath !== undefined) { - sendUserToast(`Default error handler saved to ${errorHandlerPath}`, false) - } else { - sendUserToast(`Default error handler reset`, false) - } - } - } - - async function saveAsDefaultRecoveryHandler(overrideExisting: boolean) { - if (!$enterpriseLicense) { - sendUserToast(`Setting default recovery handler is an enterprise edition feature`, true) - return - } - if (wsId) { - await ScheduleService.setDefaultErrorOrRecoveryHandler({ - workspace: wsId!, - requestBody: { - handler_type: 'recovery', - override_existing: overrideExisting, - path: - recoveryHandlerPath === undefined - ? undefined - : handlerFullPath( - recoveryHandlerSelected, - recoveryHandlerItemKind, - recoveryHandlerPath - ), - extra_args: recoveryHandlerExtraArgs, - number_of_occurence: recoveredTimes - } - }) - if (recoveryHandlerPath !== undefined) { - sendUserToast(`Default recovery handler saved to ${recoveryHandlerPath}`, false) - } else { - sendUserToast(`Default recovery handler reset`, false) - } - } - } - - async function saveAsDefaultSuccessHandler(overrideExisting: boolean) { - if (!$enterpriseLicense) { - sendUserToast(`Setting default success handler is an enterprise edition feature`, true) - return - } - if (wsId) { - await ScheduleService.setDefaultErrorOrRecoveryHandler({ - workspace: wsId!, - requestBody: { - handler_type: 'success', - override_existing: overrideExisting, - path: - successHandlerPath === undefined - ? undefined - : handlerFullPath(successHandlerSelected, successHandlerItemKind, successHandlerPath), - extra_args: successHandlerExtraArgs, - number_of_occurence: recoveredTimes - } - }) - if (successHandlerPath !== undefined) { - sendUserToast(`Default success handler saved to ${successHandlerPath}`, false) - } else { - sendUserToast(`Default success handler reset`, false) - } - } - } - /** * Apply the deployed config to the form, then return the saved-draft overlay * so the caller captures `initialConfig` from the deployed-only form BEFORE @@ -574,48 +394,7 @@ no_flow_overlap = cfg.no_flow_overlap ?? false wsErrorHandlerMuted = cfg.ws_error_handler_muted ?? false retry = cfg.retry - if (cfg.on_failure) { - let splitted = cfg.on_failure.split('/') - errorHandleritemKind = splitted[0] as 'flow' | 'script' - errorHandlerPath = splitted.slice(1)?.join('/') - failedTimes = cfg.on_failure_times ?? 1 - failedExact = cfg.on_failure_exact ?? false - errorHandlerExtraArgs = cfg.on_failure_extra_args ?? {} - errorHandlerSelected = getHandlerType('error', errorHandlerPath ?? '') - } else { - errorHandlerPath = undefined - errorHandleritemKind = 'script' - errorHandlerExtraArgs = {} - failedExact = false - failedTimes = 1 - errorHandlerSelected = 'slack' - } - if (cfg.on_recovery) { - let splitted = cfg.on_recovery.split('/') - recoveryHandlerItemKind = splitted[0] as 'flow' | 'script' - recoveryHandlerPath = splitted.slice(1)?.join('/') - recoveredTimes = cfg.on_recovery_times ?? 1 - recoveryHandlerExtraArgs = cfg.on_recovery_extra_args ?? {} - recoveryHandlerSelected = getHandlerType('recovery', recoveryHandlerPath ?? '') - } else { - recoveryHandlerPath = undefined - recoveryHandlerItemKind = 'script' - recoveredTimes = 1 - recoveryHandlerSelected = 'slack' - recoveryHandlerExtraArgs = {} - } - if (cfg.on_success) { - let splitted = cfg.on_success.split('/') - successHandlerItemKind = splitted[0] as 'flow' | 'script' - successHandlerPath = splitted.slice(1)?.join('/') - successHandlerExtraArgs = cfg.on_success_extra_args ?? {} - successHandlerSelected = getHandlerType('success', successHandlerPath ?? '') - } else { - successHandlerPath = undefined - successHandlerItemKind = 'script' - successHandlerSelected = 'slack' - successHandlerExtraArgs = {} - } + setScheduleHandlers(cfg) dynamicSkipPath = cfg.dynamic_skip args = cfg.args ?? {} extraPerms = cfg.extra_perms ?? {} @@ -631,6 +410,11 @@ async function scheduleScript(): Promise<void> { const previousPath = initialPath const scheduleCfg = getScheduleCfg() + if (saveDraftHandler) { + if (!saveDraftHandler($state.snapshot(scheduleCfg))) return + drawer?.closeDrawer() + return + } deploymentLoading = true const isSaved = await saveScheduleFromCfg(scheduleCfg, edit, wsId!) if (isSaved) { @@ -641,36 +425,6 @@ deploymentLoading = false } - function getHandlerType( - isHandler: 'error' | 'recovery' | 'success', - scriptPath: string - ): ErrorHandler { - const handlerMap = { - error: { - teams: '/workspace-or-schedule-error-handler-teams', - slack: '/workspace-or-schedule-error-handler-slack', - email: '/workspace-or-error-handler-email' - }, - recovery: { - teams: '/schedule-recovery-handler-teams', - slack: '/schedule-recovery-handler-slack', - email: '/workspace-or-error-handler-email' - }, - success: { - teams: '/schedule-success-handler-teams', - slack: '/schedule-success-handler-slack', - email: '/workspace-or-error-handler-email' - } - } - - for (const [type, suffix] of Object.entries(handlerMap[isHandler])) { - if (scriptPath.startsWith('hub/') && scriptPath.endsWith(suffix)) { - return type as ErrorHandler - } - } - return 'custom' - } - let drawer: Drawer | undefined = $state() let pathC: Path | undefined = $state() @@ -705,32 +459,25 @@ is_flow: is_flow, args: args, enabled: enabled, - on_failure: errorHandlerPath - ? handlerFullPath(errorHandlerSelected, errorHandleritemKind, errorHandlerPath) - : undefined, - on_failure_times: failedTimes, - on_failure_exact: failedExact, - on_failure_extra_args: errorHandlerPath ? errorHandlerExtraArgs : undefined, - on_recovery: recoveryHandlerPath - ? handlerFullPath(recoveryHandlerSelected, recoveryHandlerItemKind, recoveryHandlerPath) - : undefined, - on_recovery_times: recoveredTimes, - on_recovery_extra_args: recoveryHandlerPath ? recoveryHandlerExtraArgs : {}, - on_success: successHandlerPath - ? handlerFullPath(successHandlerSelected, successHandlerItemKind, successHandlerPath) - : undefined, - on_success_extra_args: successHandlerPath ? successHandlerExtraArgs : {}, - ws_error_handler_muted: wsErrorHandlerMuted, - retry: retry, + ...scheduleAdvancedCfg({ + errorHandler, + wsErrorHandlerMuted, + failedTimes, + failedExact, + recoveryHandler, + recoveredTimes, + successHandler, + retry, + dynamicSkipPath, + tag + }), summary: summary != '' ? summary : undefined, labels: labels, description: description, no_flow_overlap: no_flow_overlap, - tag: tag, paused_until: paused_until, cron_version: cronVersion, extra_perms: extraPerms, - dynamic_skip: dynamicSkipPath, permissioned_as: selectedPermissionedAs, preserve_permissioned_as: preservePermissionedAs || undefined } @@ -799,6 +546,7 @@ onToggleMode={(mode) => handleToggleEnabled(mode === 'enabled')} {isDeployed} disableSuspendedMode + saveLabel={saveDraftHandler ? 'Save draft' : undefined} > {#snippet extra()} {#if !drawerLoading && edit} @@ -808,7 +556,7 @@ variant="default" startIcon={{ icon: List }} disabled={!allowSchedule || pathError != '' || emptyString(script_path)} - href={`${base}/runs/?schedule_path=${path}&job_trigger_kind=schedule&show_future_jobs=true`} + href={`/runs/?schedule_path=${path}&job_trigger_kind=schedule&show_future_jobs=true`} > View runs </Button> @@ -1088,374 +836,35 @@ error_handler_path={errorHandlerPath} {retry} extraBadges={[ - { name: 'Recovery Handler', active: !!recoveryHandlerPath }, - { name: 'Success Handler', active: !!successHandlerPath }, + { name: 'Recovery Handler', active: !!scheduleHandlerStored(recoveryHandler).path }, + { name: 'Success Handler', active: !!scheduleHandlerStored(successHandler).path }, { name: 'Dynamic Skip', active: !!dynamicSkipPath }, { name: 'Custom Tag', active: !!tag } ]} /> {/snippet} - {@render errorHandler()} + <ScheduleAdvancedOptions + {wsId} + {itemKind} + canWrite={can_write} + {loading} + bind:errorHandler + bind:wsErrorHandlerMuted + bind:failedTimes + bind:failedExact + bind:recoveryHandler + bind:recoveredTimes + bind:successHandler + bind:retry + bind:dynamicSkipPath + bind:tag + /> </Section> <div class="pb-8" /> </div> {/if} {/snippet} -{#snippet errorHandler()} - <div class="flex flex-col gap-2 min-h-96"> - {#if !loading} - <Tabs bind:selected={optionTabSelected}> - <Tab value="error_handler" label="Error Handler" /> - <Tab value="recovery_handler" label="Recovery Handler" /> - <Tab value="success_handler" label="Success Handler" /> - <Tab value="retries" label="Retries" /> - <Tab value="dynamic_skip" label="Dynamic skip" /> - {#if itemKind === 'script'} - <Tab value="tag" label="Custom tag" /> - {/if} - </Tabs> - {#if optionTabSelected === 'error_handler'} - <Section label="Error handler"> - {#snippet header()} - <div class="flex flex-row gap-2"> - {#if !$enterpriseLicense}<span class="text-xs text-secondary">(ee only)</span>{/if} - </div> - {/snippet} - {#snippet action()} - <div class="flex flex-row items-center gap-1 text-xs text-secondary"> - <Dropdown - disabled={!can_write} - items={[ - { - displayName: `Override future schedules only`, - action: () => saveAsDefaultErrorHandler(false) - }, - { - displayName: 'Override all existing', - type: 'delete', - action: () => saveAsDefaultErrorHandler(true) - } - ]} - > - {#snippet buttonReplacement()} - <Save size={12} class="mr-1" /> - Set as default - {/snippet} - </Dropdown> - </div> - {/snippet} - <div class="flex flex-row py-2"> - <Toggle - size="xs" - disabled={!can_write || !$enterpriseLicense} - bind:checked={wsErrorHandlerMuted} - options={{ right: 'Mute workspace error handler for this schedule' }} - /> - </div> - - <ErrorOrRecoveryHandler - workspace={wsId} - isEditable={can_write} - errorOrRecovery="error" - showScriptHelpText={true} - bind:handlerSelected={errorHandlerSelected} - bind:handlerPath={errorHandlerPath} - toggleText="Alert channel on error" - customScriptTemplate="/scripts/add?hub=hub%2F19743%2Fwindmill%2Fschedule_error_handler_template" - bind:customHandlerKind={errorHandleritemKind} - bind:handlerExtraArgs={errorHandlerExtraArgs} - > - {#snippet customTabTooltip()} - <Tooltip> - <div class="flex gap-20 items-start mt-3"> - <div class="text-xs" - >The following args will be passed to the error handler: - <ul class="mt-1 ml-2"> - <li - ><b>workspace_id</b>: The ID of the workspace that the schedule belongs to.</li - > - <li><b>job_id</b>: The UUID of the job that errored.</li> - <li><b>path</b>: The path of the script or flow that failed.</li> - <li><b>is_flow</b>: Whether the runnable is a flow.</li> - <li><b>schedule_path</b>: The path of the schedule.</li> - <li><b>error</b>: The error details.</li> - <li - ><b>failed_times</b>: Minimum number of times the schedule failed before - calling the error handler.</li - > - <li><b>started_at</b>: The start datetime of the latest job that failed.</li> - </ul> - </div> - </div> - </Tooltip> - {/snippet} - </ErrorOrRecoveryHandler> - <div class="flex flex-row items-center justify-between"> - <div class="flex flex-row items-center mt-4 font-semibold text-xs gap-2"> - <p class={emptyString(errorHandlerPath) ? 'text-primary' : ''}> - Triggered when schedule failed</p - > - <select - class="!w-14" - bind:value={failedExact} - disabled={!can_write || !$enterpriseLicense || emptyString(errorHandlerPath)} - > - <option value={false}>>=</option> - <option value={true}>==</option> - </select> - <input - type="number" - class="!w-14 text-center {emptyString(errorHandlerPath) ? 'text-primary' : ''}" - bind:value={failedTimes} - disabled={!can_write || !$enterpriseLicense} - min="1" - /> - <p class={emptyString(errorHandlerPath) ? 'text-primary' : ''} - >time{failedTimes > 1 ? 's in a row' : ''}</p - > - </div> - </div> - </Section> - {:else if optionTabSelected === 'recovery_handler'} - {@const disabled = !can_write || emptyString($enterpriseLicense)} - <Section label="Recovery handler"> - {#snippet header()} - <div class="flex flex-row gap-2"> - {#if !$enterpriseLicense}<span class="text-xs text-secondary">(ee only)</span>{/if} - </div> - {/snippet} - {#snippet action()} - <div class="flex flex-row items-center text-secondary text-xs gap-2"> - defaults - <Dropdown - {disabled} - items={[ - { - displayName: `Override future schedules only`, - action: () => saveAsDefaultRecoveryHandler(false) - }, - { - displayName: 'Override all existing', - type: 'delete', - action: () => saveAsDefaultRecoveryHandler(true) - } - ]} - > - {#snippet buttonReplacement()} - <Save size={12} class="mr-1" /> - Set as default - {/snippet} - </Dropdown> - </div> - {/snippet} - <ErrorOrRecoveryHandler - workspace={wsId} - isEditable={!disabled} - errorOrRecovery="recovery" - bind:handlerSelected={recoveryHandlerSelected} - bind:handlerPath={recoveryHandlerPath} - toggleText="Alert channel when error recovered" - customScriptTemplate="/scripts/add?hub=hub%2F9082%2Fwindmill%2Fschedule_recovery_handler_template" - bind:customHandlerKind={recoveryHandlerItemKind} - bind:handlerExtraArgs={recoveryHandlerExtraArgs} - > - {#snippet customTabTooltip()} - <Tooltip> - <div class="flex gap-20 items-start mt-3"> - <div class="text-xs" - >The following args will be passed to the recovery handler: - <ul class="mt-1 ml-2"> - <li><b>path</b>: The path of the script or flow that recovered.</li> - <li><b>is_flow</b>: Whether the runnable is a flow.</li> - <li><b>schedule_path</b>: The path of the schedule.</li> - <li><b>error</b>: The error of the last job that errored</li> - <li - ><b>error_started_at</b>: The start datetime of the last job that errored</li - > - <li - ><b>success_times</b>: The number of times the schedule succeeded before - calling the recovery handler.</li - > - <li><b>success_result</b>: The result of the latest successful job</li> - <li - ><b>success_started_at</b>: The start datetime of the latest successful job</li - > - </ul> - </div> - </div> - </Tooltip> - {/snippet} - </ErrorOrRecoveryHandler> - <div class="flex flex-row items-center justify-between"> - <div - class="flex flex-row items-center mt-5 font-semibold text-xs {emptyString( - recoveryHandlerPath - ) - ? 'text-primary' - : ''}" - > - <p>Triggered when schedule recovered</p> - <input - type="number" - class="!w-14 mx-2 text-center" - bind:value={recoveredTimes} - min="1" - {disabled} - /> - <p>time{recoveredTimes > 1 ? 's in a row' : ''}</p> - </div> - </div> - </Section> - {:else if optionTabSelected === 'success_handler'} - {@const disabled = !can_write || emptyString($enterpriseLicense)} - <Section label="Success handler"> - {#snippet header()} - <div class="flex flex-row gap-2"> - {#if !$enterpriseLicense}<span class="text-xs text-secondary">(ee only)</span>{/if} - </div> - {/snippet} - {#snippet action()} - <div class="flex flex-row items-center text-secondary text-xs gap-2"> - defaults - <Dropdown - {disabled} - items={[ - { - displayName: `Override future schedules only`, - action: () => saveAsDefaultSuccessHandler(false) - }, - { - displayName: 'Override all existing', - type: 'delete', - action: () => saveAsDefaultSuccessHandler(true) - } - ]} - > - {#snippet buttonReplacement()} - <Save size={12} class="mr-1" /> - Set as default - {/snippet} - </Dropdown> - </div> - {/snippet} - <ErrorOrRecoveryHandler - workspace={wsId} - isEditable={!disabled} - errorOrRecovery="success" - bind:handlerSelected={successHandlerSelected} - bind:handlerPath={successHandlerPath} - toggleText="Alert channel when successful" - customScriptTemplate="/scripts/add?hub=hub%2F9071%2Fwindmill%2Fschedule_success_handler_template" - bind:customHandlerKind={successHandlerItemKind} - bind:handlerExtraArgs={successHandlerExtraArgs} - > - {#snippet customTabTooltip()} - <Tooltip> - <div class="flex gap-20 items-start mt-3"> - <div class="text-xs" - >The following args will be passed to the success handler: - <ul class="mt-1 ml-2"> - <li><b>path</b>: The path of the script or flow that succeeded.</li> - <li><b>is_flow</b>: Whether the runnable is a flow.</li> - <li><b>schedule_path</b>: The path of the schedule.</li> - <li><b>success_result</b>: The result of the successful job</li> - <li><b>success_started_at</b>: The start datetime of the successful job</li> - </ul> - </div> - </div> - </Tooltip> - {/snippet} - </ErrorOrRecoveryHandler> - </Section> - {:else if optionTabSelected === 'retries'} - {@const disabled = !can_write || emptyString($enterpriseLicense)} - <Section label="Retries"> - {#snippet header()} - <div class="flex flex-row gap-2"> - {#if !$enterpriseLicense}<span class="text-xs text-secondary">(ee only)</span>{/if} - </div> - <Tooltip> - If defined, upon error this schedule will be retried with a delay and a maximum number - of attempts as defined below. - <br /> - This is only available for individual script. For flows, retries can be set on each flow - step in the flow editor. - </Tooltip> - {/snippet} - {#if itemKind !== 'script'} - <Alert type="info" title="Only available for scripts" class="mb-2"> - Error Handler and Retries are only available for scripts. For flows, use the built-in <a - href="https://www.windmill.dev/docs/flows/flow_error_handler" - target="_blank">error handler</a - > - and <a href="https://www.windmill.dev/docs/flows/retries" target="_blank">retries</a>. - </Alert> - {:else} - <FlowRetries - bind:flowModuleRetry={retry} - disabled={itemKind !== 'script' || disabled} - /> - {/if} - </Section> - {:else if optionTabSelected === 'dynamic_skip'} - <Section label="Dynamic skip"> - {#snippet header()} - <Tooltip> - Optional script to filter scheduled dates. Receives the proposed datetime and returns - boolean. True = run on this date, False = skip to next occurrence. - </Tooltip> - {/snippet} - <div class="flex flex-col gap-6"> - <Label label="Dynamic skip script"> - <div class="flex flex-row"> - <ScriptPicker - workspace={wsId} - disabled={!can_write} - bind:scriptPath={dynamicSkipPath} - kinds={['script']} - allowRefresh={can_write} - clearable - /> - {#if !dynamicSkipPath} - <Button - btnClasses="ml-4 whitespace-nowrap" - variant="default" - size="xs" - href="/scripts/add?hub=hub%2F19822%2Fwindmill%2Fdynamic_skip_template{wsParam}" - disabled={!can_write} - target="_blank" - > - Create from template - </Button> - {/if} - </div> - </Label> - <Alert type="info" size="xs" title="Handler requirements"> - Handler must return a boolean value. Return true to execute the scheduled job, false - to skip. - </Alert> - </div> - </Section> - {:else if optionTabSelected === 'tag'} - <Section - label="Custom script tag" - tooltip="When set, the script tag will be overridden by this tag" - > - <WorkerTagPicker - bind:tag - workspaceId={wsId} - popupPlacement="top-end" - disabled={!can_write} - /> - </Section> - {/if} - {:else} - <Loader2 class="animate-spin" /> - {/if} - </div> -{/snippet} - {#snippet drawerBody()} <DrawerContent hideClose={inline && !onClose} @@ -1465,7 +874,9 @@ ? can_write ? `Edit schedule ${initialPath}` : `View schedule ${initialPath}` - : 'New schedule'} + : saveDraftHandler + ? 'Draft schedule' + : 'New schedule'} on:close={() => (inline ? onClose?.() : drawer?.closeDrawer())} > {#snippet actions()} diff --git a/frontend/src/lib/components/triggers/sqs/SqsTriggerEditor.svelte b/frontend/src/lib/components/triggers/sqs/SqsTriggerEditor.svelte index 4d593f2e92..f2a6a2b630 100644 --- a/frontend/src/lib/components/triggers/sqs/SqsTriggerEditor.svelte +++ b/frontend/src/lib/components/triggers/sqs/SqsTriggerEditor.svelte @@ -21,6 +21,21 @@ drawer?.openNew(is_flow, initial_script_path, defaultValues) } + /** Edit a trigger that exists only as the caller's draft; Save hands the config back. */ + export async function openDraft( + scriptPath: string, + defaults: Record<string, any>, + saved: Record<string, any> | undefined, + onSaveDraft: (cfg: Record<string, any>) => boolean + ) { + open = true + await tickPainted() + drawer?.openNew(false, scriptPath, defaults as any, { + onSaveDraft, + draftConfig: saved + }) + } + let drawer: SqsTriggerEditorInner | undefined = $state() </script> diff --git a/frontend/src/lib/components/triggers/sqs/SqsTriggerEditorInner.svelte b/frontend/src/lib/components/triggers/sqs/SqsTriggerEditorInner.svelte index 4aee2a8581..5593dd121f 100644 --- a/frontend/src/lib/components/triggers/sqs/SqsTriggerEditorInner.svelte +++ b/frontend/src/lib/components/triggers/sqs/SqsTriggerEditorInner.svelte @@ -9,15 +9,14 @@ import DrawerContent from '$lib/components/common/drawer/DrawerContent.svelte' import Path from '$lib/components/Path.svelte' import { usedTriggerKinds } from '$lib/stores' - import { canWrite, capitalize, emptyString, sendUserToast } from '$lib/utils' - import { useTriggerLock } from '$lib/operatorWriteRights' + import { capitalize, emptyString, sendUserToast } from '$lib/utils' + import { useEditRights } from '$lib/operatorWriteRights' import { withForkConflictRetry } from '$lib/utils/forkConflict' import { Loader2 } from 'lucide-svelte' import Label from '$lib/components/Label.svelte' import { SqsTriggerService, type AwsAuthResourceType, - type ErrorHandler, type Retry, type TriggerMode } from '$lib/gen' @@ -28,7 +27,8 @@ import TriggerEditorToolbar from '../TriggerEditorToolbar.svelte' import PermissionedAsLine from '../PermissionedAsLine.svelte' import { saveSqsTriggerFromCfg } from './utils' - import { getHandlerType, handleConfigChange, type Trigger } from '../utils' + import { handleConfigChange, type Trigger } from '../utils' + import { handlerDraftFromStored, handlerDraftToStored } from '../../handlerDraft.svelte' import Tabs from '$lib/components/common/tabs/Tabs.svelte' import Tab from '$lib/components/common/tabs/Tab.svelte' import TriggerRetriesAndErrorHandler from '../TriggerRetriesAndErrorHandler.svelte' @@ -43,7 +43,7 @@ useOperatingWorkspace, useOperatingWorkspaceHref } from '$lib/components/operatingWorkspace.svelte' - const triggerLock = useTriggerLock() + const editRights = useEditRights() interface Props { useDrawer?: boolean @@ -109,8 +109,9 @@ // The acting user in the operating workspace arrives asynchronously, and an unknown user // refuses — so the editor stays read-only until the lookup lands, which is the safe answer. const can_write = $derived( - (permsPath === undefined || canWrite(permsPath, permsForWrite ?? {}, actingUser)) && - !$triggerLock + permsPath === undefined + ? editRights.roleCanAuthor('trigger') + : editRights.canEditItem('trigger', permsPath, permsForWrite) ) let drawerLoading = $state(true) let showLoading = $state(false) @@ -125,9 +126,10 @@ let selectedPermissionedAs = $state<string | undefined>(undefined) let preservePermissionedAs = $state(false) let optionTabSelected: 'error_handler' | 'retries' = $state('error_handler') - let errorHandlerSelected: ErrorHandler = $state('slack') - let error_handler_path: string | undefined = $state() - let error_handler_args: Record<string, any> = $state({}) + let errorHandler = $state(handlerDraftFromStored('error', undefined)) + const storedErrorHandler = $derived(handlerDraftToStored(errorHandler)) + const error_handler_path = $derived(storedErrorHandler.path) + const error_handler_args = $derived(storedErrorHandler.args) let retry: Retry | undefined = $state() let suspendedJobsModal = $state<TriggerSuspendedJobsModal | null>(null) let originalConfig = $state<Record<string, any> | undefined>(undefined) @@ -152,14 +154,20 @@ is_flow = itemKind === 'flow' }) + // Set by `openNew(…, { onSaveDraft })`: the caller keeps the trigger as its own + // draft, so Save hands it the config instead of writing it. + let saveDraftHandler: ((cfg: Record<string, any>) => boolean) | undefined = $state(undefined) + export async function openEdit( ePath: string, isFlow: boolean, defaultConfig?: Record<string, any>, fixedScriptPath_?: string ) { + saveDraftHandler = undefined // A `whoami` that failed earlier would otherwise pin this workspace to "unknown user". operatingUser.forgetFailures() + editRights.forgetFailures() let loadingTimeout = setTimeout(() => { showLoading = true }, 100) // Do not show loading spinner for the first 100ms @@ -199,8 +207,14 @@ export async function openNew( nis_flow: boolean, fixedScriptPath_?: string, - defaultValues?: Record<string, any> + defaultValues?: Record<string, any>, + opts: { + onSaveDraft?: (cfg: Record<string, any>) => boolean + /** A config this editor saved before, re-applied over the defaults. */ + draftConfig?: Record<string, any> + } = {} ) { + saveDraftHandler = opts.onSaveDraft let loadingTimeout = setTimeout(() => { showLoading = true }, 100) @@ -221,14 +235,18 @@ edit = false dirtyPath = false mode = defaultValues?.mode ?? 'enabled' - error_handler_path = defaultValues?.error_handler_path ?? undefined - error_handler_args = defaultValues?.error_handler_args ?? {} + errorHandler = handlerDraftFromStored( + 'error', + defaultValues?.error_handler_path, + 'script', + defaultValues?.error_handler_args + ) retry = defaultValues?.retry ?? undefined - errorHandlerSelected = getHandlerType(error_handler_path ?? '') permissionedAs = undefined selectedPermissionedAs = undefined preservePermissionedAs = false originalConfig = undefined + if (opts.draftConfig) await loadTriggerConfig(opts.draftConfig) } finally { initialConfig = structuredClone($state.snapshot(getSaveCfg())) clearTimeout(loadingTimeout) @@ -252,10 +270,13 @@ aws_auth_resource_type = cfg?.aws_auth_resource_type permsPath = cfg?.path permsForWrite = cfg?.extra_perms - error_handler_path = cfg?.error_handler_path - error_handler_args = cfg?.error_handler_args ?? {} + errorHandler = handlerDraftFromStored( + 'error', + cfg?.error_handler_path, + 'script', + cfg?.error_handler_args + ) retry = cfg?.retry - errorHandlerSelected = getHandlerType(error_handler_path ?? '') permissionedAs = cfg?.permissioned_as selectedPermissionedAs = cfg?.permissioned_as preservePermissionedAs = !!cfg?.permissioned_as @@ -336,6 +357,11 @@ } async function updateTrigger(): Promise<void> { + if (saveDraftHandler) { + if (!saveDraftHandler($state.snapshot(getSaveCfg()))) return + drawer?.closeDrawer() + return + } deploymentLoading = true const previousPath = initialPath const cfg = getSaveCfg() @@ -406,7 +432,9 @@ ? can_write ? `Edit SQS trigger ${initialPath}` : `SQS trigger ${initialPath}` - : 'New SQS trigger'} + : saveDraftHandler + ? 'Draft SQS trigger' + : 'New SQS trigger'} on:close={() => (inline ? onClose?.() : drawer?.closeDrawer())} > {#snippet actions()} @@ -463,6 +491,7 @@ isLoading={deploymentLoading} {isDeployed} onUpdate={updateTrigger} + saveLabel={saveDraftHandler ? 'Save draft' : undefined} {onReset} {onDelete} {mode} @@ -582,9 +611,7 @@ {optionTabSelected} {itemKind} {can_write} - bind:errorHandlerSelected - bind:error_handler_path - bind:error_handler_args + bind:errorHandler bind:retry /> </div> diff --git a/frontend/src/lib/components/triggers/triggers.svelte.ts b/frontend/src/lib/components/triggers/triggers.svelte.ts index cd25328ff6..7fe40d111d 100644 --- a/frontend/src/lib/components/triggers/triggers.svelte.ts +++ b/frontend/src/lib/components/triggers/triggers.svelte.ts @@ -23,14 +23,15 @@ import { type NativeTrigger, type NativeServiceName } from '$lib/gen' -import { enterpriseLicense } from '$lib/stores' +import { enterpriseLicense, userWorkspaces } from '$lib/stores' import { getLightConfig, sortTriggers, updateTriggersCount, type Trigger } from './utils' import { get, type Writable } from 'svelte/store' import type { TriggerType } from './utils' import type { UserExt } from '$lib/stores' import type { ScheduleTrigger } from '../triggers' -import { canWrite, formatCron, generateRandomString } from '$lib/utils' +import { formatCron, generateRandomString } from '$lib/utils' +import { canEditItem } from '$lib/editRights' export class Triggers { #triggers = $state<Trigger[]>([]) @@ -130,9 +131,14 @@ export class Triggers { updateTriggers( remoteTriggers: any[], type: TriggerType, + workspaceId: string, user: UserExt | undefined = undefined ): number { const currentTriggers = this.#triggers + const operatorSettings = get(userWorkspaces).find( + (w) => w.id === workspaceId + )?.operator_settings + const kind = type === 'schedule' ? 'schedule' : 'trigger' // Identify triggers with draftConfig to preserve const configuredTriggers = currentTriggers.filter( (t) => t.type === type && !t.isDraft && t.draftConfig @@ -151,7 +157,7 @@ export class Triggers { path: trigger.path, isPrimary: type === 'schedule' && trigger.path === trigger.script_path, isDraft: false, - canWrite: canWrite(trigger.path, trigger.extra_perms, user), + canWrite: canEditItem(kind, trigger.path, trigger.extra_perms, user, operatorSettings), draftConfig: draftConfig, lightConfig: getLightConfig(type, trigger) } @@ -199,7 +205,7 @@ export class Triggers { isFlow }) - const scheduleCount = this.updateTriggers(allDeployedSchedules, 'schedule', user) + const scheduleCount = this.updateTriggers(allDeployedSchedules, 'schedule', workspaceId, user) const updatedPrimarySchedule = this.#triggers.find((s) => s.isPrimary) triggersCountStore.update((triggersCount) => { return { @@ -234,7 +240,7 @@ export class Triggers { path, isFlow }) - const wsCount = this.updateTriggers(wsTriggers, 'websocket', user) + const wsCount = this.updateTriggers(wsTriggers, 'websocket', workspaceId, user) triggersCountStore.update((triggersCount) => { return { ...(triggersCount ?? {}), @@ -260,7 +266,7 @@ export class Triggers { path, isFlow }) - const pgCount = this.updateTriggers(pgTriggers, 'postgres', user) + const pgCount = this.updateTriggers(pgTriggers, 'postgres', workspaceId, user) triggersCountStore.update((triggersCount) => { return { ...(triggersCount ?? {}), @@ -286,7 +292,7 @@ export class Triggers { path, isFlow }) - const kafkaCount = this.updateTriggers(kafkaTriggers, 'kafka', user) + const kafkaCount = this.updateTriggers(kafkaTriggers, 'kafka', workspaceId, user) triggersCountStore.update((triggersCount) => { return { ...(triggersCount ?? {}), @@ -312,7 +318,7 @@ export class Triggers { path, isFlow }) - const natsCount = this.updateTriggers(natsTriggers, 'nats', user) + const natsCount = this.updateTriggers(natsTriggers, 'nats', workspaceId, user) triggersCountStore.update((triggersCount) => { return { ...(triggersCount ?? {}), @@ -338,7 +344,7 @@ export class Triggers { path, isFlow }) - const mqttCount = this.updateTriggers(mqttTriggers, 'mqtt', user) + const mqttCount = this.updateTriggers(mqttTriggers, 'mqtt', workspaceId, user) triggersCountStore.update((triggersCount) => { return { ...(triggersCount ?? {}), @@ -364,7 +370,7 @@ export class Triggers { path, isFlow }) - const amqpCount = this.updateTriggers(amqpTriggers, 'amqp', user) + const amqpCount = this.updateTriggers(amqpTriggers, 'amqp', workspaceId, user) triggersCountStore.update((triggersCount) => { return { ...(triggersCount ?? {}), @@ -390,7 +396,7 @@ export class Triggers { path, isFlow }) - const sqsCount = this.updateTriggers(sqsTriggers, 'sqs', user) + const sqsCount = this.updateTriggers(sqsTriggers, 'sqs', workspaceId, user) triggersCountStore.update((triggersCount) => { return { ...(triggersCount ?? {}), @@ -416,7 +422,7 @@ export class Triggers { path, isFlow }) - const gcpCount = this.updateTriggers(gcpTriggers, 'gcp', user) + const gcpCount = this.updateTriggers(gcpTriggers, 'gcp', workspaceId, user) triggersCountStore.update((triggersCount) => { return { ...(triggersCount ?? {}), @@ -442,7 +448,7 @@ export class Triggers { path, isFlow }) - const azureCount = this.updateTriggers(azureTriggers, 'azure', user) + const azureCount = this.updateTriggers(azureTriggers, 'azure', workspaceId, user) triggersCountStore.update((triggersCount) => { return { ...(triggersCount ?? {}), @@ -468,7 +474,7 @@ export class Triggers { path, isFlow }) - const httpCount = this.updateTriggers(httpTriggers, 'http', user) + const httpCount = this.updateTriggers(httpTriggers, 'http', workspaceId, user) triggersCountStore.update((triggersCount) => { return { ...(triggersCount ?? {}), @@ -494,7 +500,7 @@ export class Triggers { path, isFlow }) - const emailCount = this.updateTriggers(emailTriggers, 'email', user) + const emailCount = this.updateTriggers(emailTriggers, 'email', workspaceId, user) triggersCountStore.update((triggersCount) => { return { ...(triggersCount ?? {}), @@ -530,7 +536,7 @@ export class Triggers { extra_perms: {}, service_config: t.service_config })) - const count = this.updateTriggers(triggerData, serviceName, user) + const count = this.updateTriggers(triggerData, serviceName, workspaceId, user) const countProperty = `${serviceName}_count` triggersCountStore.update((triggersCount) => { return { diff --git a/frontend/src/lib/components/triggers/utils.ts b/frontend/src/lib/components/triggers/utils.ts index 979791cba1..3eb67cb933 100644 --- a/frontend/src/lib/components/triggers/utils.ts +++ b/frontend/src/lib/components/triggers/utils.ts @@ -30,7 +30,6 @@ import GoogleMonoIcon from '$lib/components/icons/triggers/GoogleIcon.svelte' import GithubMonoIcon from '$lib/components/icons/triggers/GithubIcon.svelte' import type { CaptureTriggerKind, - ErrorHandler, Flow, JobTriggerKind, NewScript, @@ -732,17 +731,3 @@ export function sortTriggers(triggers: Trigger[]): Trigger[] { export type FlowWithDraftAndDraftTriggers = Flow export type NewScriptWithDraftAndDraftTriggers = NewScript & { hash?: string } - -export function getHandlerType(scriptPath: string): ErrorHandler { - const handlerMap = { - teams: '/workspace-or-schedule-error-handler-teams', - slack: '/workspace-or-schedule-error-handler-slack', - email: '/workspace-or-error-handler-email' - } - for (const [type, suffix] of Object.entries(handlerMap)) { - if (scriptPath.startsWith('hub/') && scriptPath.endsWith(suffix)) { - return type as ErrorHandler - } - } - return 'custom' -} diff --git a/frontend/src/lib/components/triggers/webhook/WebhooksConfigSection.svelte b/frontend/src/lib/components/triggers/webhook/WebhooksConfigSection.svelte index 9033aab3cf..218430316a 100644 --- a/frontend/src/lib/components/triggers/webhook/WebhooksConfigSection.svelte +++ b/frontend/src/lib/components/triggers/webhook/WebhooksConfigSection.svelte @@ -16,7 +16,7 @@ import ClipboardPanel from '../../details/ClipboardPanel.svelte' import { copyToClipboard, isObject, readFieldsRecursively } from '$lib/utils' // import { page } from '$app/state' - import { base } from '$lib/base' + import { apiBaseUrl } from '$lib/apiBaseUrl.svelte' import TriggerTokens from '../TriggerTokens.svelte' import { userStore } from '$lib/stores' import UserSettings from '../../UserSettings.svelte' @@ -46,7 +46,7 @@ const operatingWorkspace = useOperatingWorkspace() const wsId = $derived($operatingWorkspace) - const WEBHOOK_BASE_URL = $derived(`${location.origin}${base}/api/w/${wsId}/jobs`) + const WEBHOOK_BASE_URL = $derived(`${apiBaseUrl()}/api/w/${wsId}/jobs`) let baseWebhookUrl = $derived.by(() => { let webhookUrlPath: string @@ -223,9 +223,7 @@ async function triggerJob() { function waitForJobCompletion(UUID) { return new Promise(async (resolve, reject) => { try { - const endpoint = \`${ - location.origin - }/api/w/${wsId}/jobs_u/completed/get_result_maybe/\${UUID}\`; + const endpoint = \`${apiBaseUrl()}/api/w/${wsId}/jobs_u/completed/get_result_maybe/\${UUID}\`; const checkResponse = await fetch(endpoint, { method: 'GET', headers: ${JSON.stringify(headers(), null, 2).replaceAll('\n', '\n\t\t\t\t')} @@ -268,7 +266,7 @@ ${ ? 'echo -E $RESULT | jq' : requestType === 'async' ? ` -URL="${location.origin}/api/w/${wsId}/jobs_u/completed/get_result_maybe/$UUID" +URL="${apiBaseUrl()}/api/w/${wsId}/jobs_u/completed/get_result_maybe/$UUID" while true; do curl -s -H "Authorization: Bearer $TOKEN" $URL -o res.json COMPLETED=$(cat res.json | jq .completed) diff --git a/frontend/src/lib/components/triggers/websocket/WebsocketTriggerEditorInner.svelte b/frontend/src/lib/components/triggers/websocket/WebsocketTriggerEditorInner.svelte index 007bc39e47..b011d6fee1 100644 --- a/frontend/src/lib/components/triggers/websocket/WebsocketTriggerEditorInner.svelte +++ b/frontend/src/lib/components/triggers/websocket/WebsocketTriggerEditorInner.svelte @@ -21,12 +21,11 @@ type WebsocketTriggerInitialMessage, type WebsocketHeartbeat, type Retry, - type ErrorHandler, type TriggerMode } from '$lib/gen' import { usedTriggerKinds } from '$lib/stores' - import { canWrite, emptySchema, emptyString, sendUserToast } from '$lib/utils' - import { useTriggerLock } from '$lib/operatorWriteRights' + import { emptySchema, emptyString, sendUserToast } from '$lib/utils' + import { useEditRights } from '$lib/operatorWriteRights' import { withForkConflictRetry } from '$lib/utils/forkConflict' import Section from '$lib/components/Section.svelte' import { Loader2, X, Plus } from 'lucide-svelte' @@ -43,7 +42,8 @@ import TriggerEditorToolbar from '../TriggerEditorToolbar.svelte' import PermissionedAsLine from '../PermissionedAsLine.svelte' import { saveWebsocketTriggerFromCfg } from './utils' - import { getHandlerType, handleConfigChange, type Trigger } from '../utils' + import { handleConfigChange, type Trigger } from '../utils' + import { handlerDraftFromStored, handlerDraftToStored } from '../../handlerDraft.svelte' import Tabs from '$lib/components/common/tabs/Tabs.svelte' import Tab from '$lib/components/common/tabs/Tab.svelte' import TriggerRetriesAndErrorHandler from '../TriggerRetriesAndErrorHandler.svelte' @@ -59,7 +59,7 @@ useOperatingWorkspace, useOperatingWorkspaceHref } from '$lib/components/operatingWorkspace.svelte' - const triggerLock = useTriggerLock() + const editRights = useEditRights() interface Props { useDrawer?: boolean @@ -137,8 +137,9 @@ // The acting user in the operating workspace arrives asynchronously, and an unknown user // refuses — so the editor stays read-only until the lookup lands, which is the safe answer. const can_write = $derived( - (permsPath === undefined || canWrite(permsPath, permsForWrite ?? {}, actingUser)) && - !$triggerLock + permsPath === undefined + ? editRights.roleCanAuthor('trigger') + : editRights.canEditItem('trigger', permsPath, permsForWrite) ) let drawerLoading = $state(true) let showLoading = $state(false) @@ -149,9 +150,10 @@ let preservePermissionedAs = $state(false) let isValid = $state(false) let optionTabSelected: 'error_handler' | 'retries' = $state('error_handler') - let errorHandlerSelected: ErrorHandler = $state('slack') - let error_handler_path: string | undefined = $state() - let error_handler_args: Record<string, any> = $state({}) + let errorHandler = $state(handlerDraftFromStored('error', undefined)) + const storedErrorHandler = $derived(handlerDraftToStored(errorHandler)) + const error_handler_path = $derived(storedErrorHandler.path) + const error_handler_args = $derived(storedErrorHandler.args) let retry: Retry | undefined = $state() let mode = $state<TriggerMode>('enabled') @@ -206,6 +208,7 @@ ) { // A `whoami` that failed earlier would otherwise pin this workspace to "unknown user". operatingUser.forgetFailures() + editRights.forgetFailures() let loadingTimeout = setTimeout(() => { showLoading = true }, 100) // Do not show loading spinner for the first 100ms @@ -266,10 +269,13 @@ dirtyPath = false can_return_message = false can_return_error_result = false - error_handler_path = defaultValues?.error_handler_path ?? undefined - error_handler_args = defaultValues?.error_handler_args ?? {} + errorHandler = handlerDraftFromStored( + 'error', + defaultValues?.error_handler_path, + 'script', + defaultValues?.error_handler_args + ) retry = defaultValues?.retry ?? undefined - errorHandlerSelected = getHandlerType(error_handler_path ?? '') mode = defaultValues?.mode ?? 'enabled' permissionedAs = undefined selectedPermissionedAs = undefined @@ -303,10 +309,13 @@ heartbeat_state_field = hb?.state_field ?? '' permsPath = path permsForWrite = cfg?.extra_perms - error_handler_path = cfg?.error_handler_path - error_handler_args = cfg?.error_handler_args ?? {} + errorHandler = handlerDraftFromStored( + 'error', + cfg?.error_handler_path, + 'script', + cfg?.error_handler_args + ) retry = cfg?.retry - errorHandlerSelected = getHandlerType(error_handler_path ?? '') mode = cfg?.mode ?? 'enabled' permissionedAs = cfg?.permissioned_as selectedPermissionedAs = cfg?.permissioned_as @@ -914,9 +923,7 @@ {optionTabSelected} {itemKind} {can_write} - bind:errorHandlerSelected - bind:error_handler_path - bind:error_handler_args + bind:errorHandler bind:retry /> </div> diff --git a/frontend/src/lib/components/variables/VariablesList.svelte b/frontend/src/lib/components/variables/VariablesList.svelte index 66f293a11d..3805b51bbb 100644 --- a/frontend/src/lib/components/variables/VariablesList.svelte +++ b/frontend/src/lib/components/variables/VariablesList.svelte @@ -38,7 +38,8 @@ import type { ContextualVariable, ListableVariable, WorkspaceDeployUISettings } from '$lib/gen' import { enterpriseLicense, userWorkspaces } from '$lib/stores' import { sendUserToast } from '$lib/toast' - import { canWrite, isOwner, truncate } from '$lib/utils' + import { isOwner, truncate } from '$lib/utils' + import { useEditRights } from '$lib/operatorWriteRights' import { isDeployable, ALL_DEPLOYABLE } from '$lib/utils_deployable' import { Plus, @@ -64,6 +65,7 @@ const operatingWorkspace = useOperatingWorkspace() const operatingUser = useOperatingUser() + const editRights = useEditRights() const hosted = useHostedPage() function editVariable(path: string) { @@ -205,7 +207,7 @@ const result = (await VariableService.listVariable(apiParams)).map((x) => { return { canWrite: - canWrite(x.path, x.extra_perms!, operatingUser.current) && + editRights.canEditItem('variable', x.path, x.extra_perms) && x.workspace_id == $operatingWorkspace, ...x } diff --git a/frontend/src/lib/components/wizards/AppPicker.svelte b/frontend/src/lib/components/wizards/AppPicker.svelte index 17f384c71d..7e8a1e91a6 100644 --- a/frontend/src/lib/components/wizards/AppPicker.svelte +++ b/frontend/src/lib/components/wizards/AppPicker.svelte @@ -2,18 +2,14 @@ import { getContext, onMount } from 'svelte' import DarkModeObserver from '../DarkModeObserver.svelte' import { AppService, type ListableApp } from '$lib/gen' - import { canWrite } from '$lib/utils' + import { useEditRights } from '$lib/operatorWriteRights' import type { AppViewerContext } from '../apps/types' import Alert from '../common/alert/Alert.svelte' import Select from '../select/Select.svelte' - import { - useOperatingUser, - useOperatingWorkspace - } from '$lib/components/operatingWorkspace.svelte' + import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' const operatingWorkspace = useOperatingWorkspace() - const operatingUser = useOperatingUser() - const actingUser = $derived(operatingUser.current) + const editRights = useEditRights() interface Props { value?: string @@ -32,9 +28,8 @@ ).map((app: ListableApp) => { return { canWrite: - canWrite(app.path!, app.extra_perms!, actingUser) && - app.workspace_id == $operatingWorkspace && - !actingUser?.operator, + editRights.canEditItem('app', app.path!, app.extra_perms) && + app.workspace_id == $operatingWorkspace, ...app } }) diff --git a/frontend/src/lib/components/workspacePicker.ts b/frontend/src/lib/components/workspacePicker.ts index 61b4d3239e..c33ad36843 100644 --- a/frontend/src/lib/components/workspacePicker.ts +++ b/frontend/src/lib/components/workspacePicker.ts @@ -19,6 +19,8 @@ export type WorkspaceItem = { * so read it with `draftOnly` to tell "nothing deployed" from "deployed, with * edits pending". */ hasDraft?: boolean + /** The item's own sharing, which `canEditItem` reads with the folder rules. */ + extraPerms?: Record<string, boolean> } /** Path to display (and group by) in pickers: the friendly draft path when @@ -140,7 +142,8 @@ export async function loadKind( kind: 'flow' as const, draftPath: f.draft_path, draftOnly: f.draft_only ?? false, - hasDraft: f.is_draft ?? false + hasDraft: f.is_draft ?? false, + extraPerms: f.extra_perms })) } else if (kind === 'script') { const scripts = await ScriptService.listScripts({ @@ -154,7 +157,8 @@ export async function loadKind( kind: 'script' as const, draftPath: s.draft_path, draftOnly: s.draft_only ?? false, - hasDraft: s.is_draft ?? false + hasDraft: s.is_draft ?? false, + extraPerms: s.extra_perms })) } else { const apps = await AppService.listApps({ @@ -168,7 +172,8 @@ export async function loadKind( raw_app: a.raw_app ?? false, draftPath: a.draft_path, draftOnly: a.draft_only ?? false, - hasDraft: a.is_draft ?? false + hasDraft: a.is_draft ?? false, + extraPerms: a.extra_perms })) } // Only commit if the cache version hasn't changed since we started — diff --git a/frontend/src/lib/components/workspaceSettings/CreateWorkspaceInner.svelte b/frontend/src/lib/components/workspaceSettings/CreateWorkspaceInner.svelte index 5ae952f03e..2afcbce3c8 100644 --- a/frontend/src/lib/components/workspaceSettings/CreateWorkspaceInner.svelte +++ b/frontend/src/lib/components/workspaceSettings/CreateWorkspaceInner.svelte @@ -11,6 +11,12 @@ type CompletedJob } from '$lib/gen' import { validateUsername } from '$lib/utils' + import { + devWorkspaceTagSuffix, + devWorkspaceSkipNonDevForks, + isForkOfIsolated, + loadDevWorkspaceTagSuffix + } from '$lib/devWorkspaceTags' import { logoutWithRedirect } from '$lib/logoutKit' import { page } from '$app/state' import { @@ -30,10 +36,13 @@ import { useForkableWorkspaces } from '$lib/utils/useForkableWorkspaces.svelte' import { isOperatorInWorkspace } from '$lib/components/sidebar/operatorRoutes' import { + canUserBypassRuleKindInRulesets, fetchProtectionRulesForWorkspace, + isRuleActiveInRulesets, isRuleUnconditionallyActiveInRulesets } from '$lib/workspaceProtectionRules.svelte' import { resource } from 'runed' + import { getUserExt } from '$lib/user' import { Button } from '$lib/components/common' import { DEV_WORKSPACE_LABELS, @@ -64,13 +73,13 @@ import TextInput from '../text_input/TextInput.svelte' import { jobManager } from '$lib/services/JobManager' import Alert from '../common/alert/Alert.svelte' - import { base } from '$lib/base' import Label from '../Label.svelte' import ForkDatatableSection from './ForkDatatableSection.svelte' import Select from '../select/Select.svelte' import WorkspaceScopeTrigger from '../WorkspaceScopeTrigger.svelte' import DarkModeToggle from '../sidebar/DarkModeToggle.svelte' import ForkDucklakeSection from './ForkDucklakeSection.svelte' + import ForkStorageSection from './ForkStorageSection.svelte' import { createWorkspaceForkAndWait } from '$lib/utils/forkCreation' interface Props { @@ -163,6 +172,12 @@ // read as a root (it would offer invalid dev creation while the workspace list is still loading). // `workspaceIsFork` (prefix OR parent) also excludes an orphaned `wm-fork-` workspace, whose parent // FK was set null — it has no parent but is still a fork, so it can't host a dev workspace. + let baseIsRoot = $derived( + !!baseWorkspaceEntry && !workspaceIsFork(baseWorkspaceId, forkableWorkspaces) + ) + $effect(() => { + isFork && loadDevWorkspaceTagSuffix() + }) let baseCanHostDev = $derived( !!baseWorkspaceEntry && (!workspaceIsFork(baseWorkspaceId, forkableWorkspaces) || @@ -266,6 +281,35 @@ let forkDatatableSection: ReturnType<typeof ForkDatatableSection> | undefined = $state(undefined) let forkDucklakeSection: ReturnType<typeof ForkDucklakeSection> | undefined = $state(undefined) + let forkStorageSection: ReturnType<typeof ForkStorageSection> | undefined = $state(undefined) + let datatableCount = $state(0) + let ducklakeCount = $state(0) + let storageCount = $state(0) + let forkDataCount = $derived(datatableCount + ducklakeCount + storageCount) + + // The base's `RequireIsolatedForks` rule leaves no data shared with it: the sections below drop + // their sharing options. The server enforces it; this only keeps the form from offering a + // choice it would refuse. Bypass is judged with the user's identity in the BASE, like + // ParentWorkspaceProtectionAlert. + const baseRuleContext = resource( + () => (isFork ? baseWorkspaceId : undefined), + async (ws) => { + if (!ws) return undefined + const [rules, user] = await Promise.all([ + fetchProtectionRulesForWorkspace(ws), + getUserExt(ws) + ]) + return { rules, user } + } + ) + let requireIsolation = $derived.by(() => { + const ctx = baseRuleContext.current + return ( + !!ctx && + isRuleActiveInRulesets(ctx.rules, 'RequireIsolatedForks') && + !canUserBypassRuleKindInRulesets(ctx.rules, 'RequireIsolatedForks', ctx.user) + ) + }) let workspaceColor: string | undefined = $state(undefined) let colorEnabled = $state(false) @@ -422,9 +466,11 @@ id: prefixed_id, name, color: colorEnabled && workspaceColor ? workspaceColor : undefined, - // Sent in this first phase too, so a clone the fork would refuse is refused before - // any branch is created. + // Sent in this first phase too, so a clone or a sharing choice the fork would refuse + // is refused before any branch is created. forked_datatables: forkedDatatables, + shared_ducklakes: forkDucklakeSection?.getSharedDucklakes() ?? [], + shared_storages: forkStorageSection?.getSharedStorages() ?? [], is_dev_workspace: createAsDevWorkspace, dev_workspace_label: createAsDevWorkspace ? devWorkspaceLabel : undefined, // Send the lock intent in this first phase too so the backend can reject a non-admin's @@ -488,6 +534,7 @@ color: colorEnabled && workspaceColor ? workspaceColor : undefined, forked_datatables: forkedDatatables, shared_ducklakes: forkDucklakeSection?.getSharedDucklakes() ?? [], + shared_storages: forkStorageSection?.getSharedStorages() ?? [], is_dev_workspace: createAsDevWorkspace, dev_workspace_label: createAsDevWorkspace ? devWorkspaceLabel : undefined, lock_prod_deploy: createAsDevWorkspace && effectiveLockProdDeploy, @@ -964,19 +1011,77 @@ there. </Alert> {/if} + {#if baseWorkspaceId && createAsDevWorkspace} + <Alert + type="info" + size="xs" + title="Resources and variables are copied from {baseWorkspaceId}" + > + The dev workspace starts with copies of {baseWorkspaceId}'s resources and variables, + credentials included. Point them at staging before developers use it. + {#if !forkingLocked && !lockProdForking} + Turn on <b>Prevent forking</b> above so developers fork this dev workspace, which will + hold staging credentials, rather than {baseWorkspaceId}. + {/if} + {#if $devWorkspaceTagSuffix} + Its jobs run on dev workers (tags suffixed with <code>{$devWorkspaceTagSuffix}</code + >). + {/if} + </Alert> + {:else if baseWorkspaceId && $devWorkspaceTagSuffix && !isForkOfIsolated(baseWorkspaceId, $userWorkspaces, $devWorkspaceSkipNonDevForks)} + <Alert type="info" size="xs" title="Runs on {baseWorkspaceId}'s workers"> + Forks of non-dev workspaces are not isolated on this instance: jobs of this fork run on + the same workers as {baseWorkspaceId}. + </Alert> + {:else if baseWorkspaceId && $devWorkspaceTagSuffix} + <Alert type="info" size="xs" title="Runs on dev workers"> + Jobs of this fork run on the worker groups serving dev workspaces (tags suffixed with + <code>{$devWorkspaceTagSuffix}</code>). + {#if baseIsRoot} + It copies {baseWorkspaceId}'s resources and variables, so its scripts use + {baseWorkspaceId}'s credentials from those workers and reach what their network + allows. Forking a dev workspace instead gives a fork its staging credentials. + {/if} + </Alert> + {/if} {/if} {#if isFork} - <ForkDatatableSection - bind:this={forkDatatableSection} - sourceWorkspace={baseWorkspaceId} - onAllDone={() => { - completeFork(effectiveForkId) - }} - onCanceled={() => { - forkCreationLoading = false - }} - /> - <ForkDucklakeSection bind:this={forkDucklakeSection} sourceWorkspace={baseWorkspaceId} /> + <!-- Hidden rather than unmounted while empty: the sections load their own lists. --> + <div class={forkDataCount > 0 ? 'flex flex-col gap-3' : 'hidden'}> + <Label label="Fork data"> + <span class="text-xs text-secondary"> + Isolated or cloned: the fork writes only its own data, and this workspace's is never + changed. Shared: the fork reads and writes this workspace's data directly. + {#if requireIsolation} + A protection rule on this workspace requires isolation. + {/if} + </span> + </Label> + <ForkDatatableSection + bind:this={forkDatatableSection} + bind:itemCount={datatableCount} + sourceWorkspace={baseWorkspaceId} + {requireIsolation} + onAllDone={() => { + completeFork(effectiveForkId) + }} + onCanceled={() => { + forkCreationLoading = false + }} + /> + <ForkDucklakeSection + bind:this={forkDucklakeSection} + bind:itemCount={ducklakeCount} + sourceWorkspace={baseWorkspaceId} + {requireIsolation} + /> + <ForkStorageSection + bind:this={forkStorageSection} + bind:itemCount={storageCount} + sourceWorkspace={baseWorkspaceId} + {requireIsolation} + /> + </div> {/if} {#if !automateUsernameCreation} <Label label="Your username in that workspace"> @@ -1102,11 +1207,8 @@ </div> <div class="flex flex-wrap flex-row {inModal ? 'justify-end' : 'justify-between'} gap-4 pt-4"> {#if !inModal} - <Button - disabled={forkCreationLoading} - variant="default" - size="sm" - href="{base}/user/workspaces">← Back to workspaces</Button + <Button disabled={forkCreationLoading} variant="default" size="sm" href="/user/workspaces" + >← Back to workspaces</Button > {/if} {#if !forkCreationLoading} diff --git a/frontend/src/lib/components/workspaceSettings/DataTableMigrationsButton.svelte b/frontend/src/lib/components/workspaceSettings/DataTableMigrationsButton.svelte index f9dd3dda02..eb7e22c858 100644 --- a/frontend/src/lib/components/workspaceSettings/DataTableMigrationsButton.svelte +++ b/frontend/src/lib/components/workspaceSettings/DataTableMigrationsButton.svelte @@ -1,5 +1,5 @@ <script lang="ts"> - import { Button } from '../common' + import { Badge, Button } from '../common' import Modal2 from '../common/modal/Modal2.svelte' import Tabs from '../common/tabs/Tabs.svelte' import Tab from '../common/tabs/Tab.svelte' @@ -29,6 +29,7 @@ import { superadmin } from '$lib/stores' import { useOperatingUser } from '$lib/components/operatingWorkspace.svelte' import { parseMigrationRole, withMigrationRole } from '../datatableMigrationRole' + import { scopesOverlap } from '../datatableMigrationSchemas' const operatingUser = useOperatingUser() const actingUser = $derived(operatingUser.current) @@ -228,17 +229,56 @@ } } - // Run a single migration. Warn first if earlier migrations haven't run, since - // this one might depend on them. + async function runForSchema(schema: string) { + busy = true + try { + const res = await WorkspaceService.runDatatableMigrations({ + workspace, + datatableName: datatable, + schema + }) + sendUserToast( + res.applied.length > 0 + ? `Applied ${res.applied.length} migration(s) on ${schema}` + : `No pending migrations on ${schema}` + ) + await loadMigrations() + if (res.applied.length > 0) onSchemaChanged?.() + } catch (e: any) { + sendUserToast(`Failed to run migrations: ${e?.body ?? e?.message ?? e}`, true) + } finally { + busy = false + } + } + + // The schemas that have pending migrations declaring them, each runnable on its own. + const pendingSchemas = $derived([ + ...new Set(migrations.filter((m) => m.status !== 'ran').flatMap((m) => m.schemas ?? [])) + ]) + + // What makes two migrations depend on each other, for the out-of-order warnings. + function overlap(a: DatatableMigrationWithStatus, b: DatatableMigrationWithStatus): string { + if (!b.schemas) return 'it applies to the whole database' + if (!a.schemas) return `"${a.name}" applies to the whole database` + return `both touch schema ${a.schemas.filter((s) => b.schemas?.includes(s)).join(', ')}` + } + + // Run a single migration. Warn first if an earlier migration touching the same schemas hasn't + // run, since this one might depend on it. async function runMigration(m: DatatableMigrationWithStatus) { - const earlierPending = migrations.filter( - (x) => x.timestamp < m.timestamp && x.status !== 'ran' - ).length - if (earlierPending > 0) { + // `blocked_by` is only known when the applied versions could be read: when they could not, + // an earlier overlapping migration of unknown status may still be pending. + const blocker = + migrations.find((x) => x.timestamp === m.blocked_by) ?? + migrations.find( + (x) => + x.timestamp < m.timestamp && x.status === 'unknown' && scopesOverlap(x.schemas, m.schemas) + ) + if (blocker) { const confirmed = await confirmationModal.ask({ title: 'Run migration out of order', confirmationText: 'Run anyway', - children: `${earlierPending} earlier migration(s) have not been run yet. "${m.name}" might depend on them. Run it anyway?` + children: `"${blocker.name}" ${blocker.status === 'unknown' ? 'may not have been run yet' : 'has not been run yet'} and ${overlap(m, blocker)}, so "${m.name}" might depend on it. Run it anyway?` }) if (!confirmed) return } @@ -267,17 +307,15 @@ } } - // Revert a single migration. Warn first if later migrations have run, since - // they might depend on this one. + // Revert a single migration. Warn first if a later migration touching the same schemas has + // run, since it might depend on this one. async function revertMigration(m: DatatableMigrationWithStatus) { - const laterApplied = migrations.filter( - (x) => x.timestamp > m.timestamp && x.status === 'ran' - ).length - if (laterApplied > 0) { + const blocker = migrations.find((x) => x.timestamp === m.blocked_by) + if (blocker) { const confirmed = await confirmationModal.ask({ title: 'Revert migration out of order', confirmationText: 'Revert anyway', - children: `${laterApplied} later migration(s) have already been run and might depend on "${m.name}". Reverting it may break them. Revert anyway?` + children: `"${blocker.name}" has already been run and ${overlap(m, blocker)}, so it might depend on "${m.name}". Reverting it may break it. Revert anyway?` }) if (!confirmed) return } @@ -535,6 +573,21 @@ <span class="text-sm text-primary truncate">{m.name}</span> <span class="text-xs text-hint">{m.timestamp}</span> </button> + <div class="flex flex-wrap justify-end gap-1 shrink-0 max-w-48"> + {#if m.schemas} + {#each m.schemas as s (s)} + <Badge small>{s}</Badge> + {/each} + {:else} + <Badge + small + color="yellow" + title="Declares no schemas: every later migration waits for it" + > + whole database + </Badge> + {/if} + </div> <Button variant="subtle" size="xs" @@ -579,10 +632,16 @@ > <Button variant="accent" - size="sm" + unifiedSize="sm" startIcon={{ icon: Play }} disabled={busy || !hasPending} on:click={() => runUpTo(undefined)} + dropdownItems={pendingSchemas.length > 0 + ? pendingSchemas.map((s) => ({ + label: `Run pending on ${s} only`, + onClick: () => runForSchema(s) + })) + : undefined} > Run all </Button> diff --git a/frontend/src/lib/components/workspaceSettings/DataTablePermissionsButton.svelte b/frontend/src/lib/components/workspaceSettings/DataTablePermissionsButton.svelte index 680421450d..496c967d7f 100644 --- a/frontend/src/lib/components/workspaceSettings/DataTablePermissionsButton.svelte +++ b/frontend/src/lib/components/workspaceSettings/DataTablePermissionsButton.svelte @@ -23,7 +23,7 @@ import { superadmin } from '$lib/stores' import { sendUserToast } from '$lib/toast' import { deepEqual } from 'fast-equals' - import { ADMIN_DATATABLE_ROLE, isDatatableRoleName } from '../dbTypes' + import { ADMIN_DATATABLE_ROLE, NO_DEFAULT_DATATABLE_ROLE, isDatatableRoleName } from '../dbTypes' import PgAclEditor from '../datatableAcl/PgAclEditor.svelte' import ConfirmationModal from '../common/confirmationModal/ConfirmationModal.svelte' import { createAsyncConfirmationModal } from '../common/confirmationModal/asyncConfirmationModal.svelte' @@ -87,6 +87,8 @@ const pgInstanceName = $derived(pgInstanceNameOf(info?.cluster)) const unusedRoles = $derived(availableRoles.filter((r) => !roles.some((row) => row.id === r.id))) const confirmationModal = createAsyncConfirmationModal() + // Every member of the governing workspace, as the tenant lists spell it. + const EVERYONE_TENANT = '*' let aclEditor = $state<PgAclEditor | undefined>(undefined) const hasUnsavedChanges = $derived( @@ -111,9 +113,13 @@ (a, b) => Number(b.id === ADMIN_DATATABLE_ROLE) - Number(a.id === ADMIN_DATATABLE_ROLE) ) // A data table never put under roles comes back with none; admin is what turning the toggle - // on starts from. + // on starts from, open to everyone so that turning it on changes nothing by itself. if (!loaded.some((r) => r.id === ADMIN_DATATABLE_ROLE)) { - loaded.unshift({ id: ADMIN_DATATABLE_ROLE, name: ADMIN_DATATABLE_ROLE, tenants: [] }) + loaded.unshift({ + id: ADMIN_DATATABLE_ROLE, + name: ADMIN_DATATABLE_ROLE, + tenants: [EVERYONE_TENANT] + }) } info = res catalog = undefined @@ -137,7 +143,7 @@ FolderService.listFolderNames({ workspace: ws }) ]) tenantItems = [ - { value: '*', label: 'Everyone', group: 'Anyone in the workspace' }, + { value: EVERYONE_TENANT, label: 'Everyone', group: 'Anyone in the workspace' }, ...users.map((u) => ({ value: `u/${u}`, label: u, group: 'Users' })), ...groups.map((g) => ({ value: `g/${g}`, label: g, group: 'Groups' })), ...folders.map((f) => ({ value: `f/${f}`, label: f, group: 'Folders' })) @@ -218,11 +224,28 @@ } } - function removeRole(role: EditedRole) { + async function removeRole(role: EditedRole) { + if (defaultRoleId === role.id) { + const confirmed = await confirmationModal.ask({ + title: 'Remove the default role?', + children: `Jobs that name no role connect as ${role.name ?? role.id}. Without it the data table has no default role: they connect with the roles of the person running them, and are refused when that person has none.`, + confirmationText: 'Remove', + type: 'danger' + }) + if (!confirmed) return + defaultRoleId = NO_DEFAULT_DATATABLE_ROLE + } roles = roles.filter((r) => r.id !== role.id) - if (defaultRoleId === role.id) defaultRoleId = ADMIN_DATATABLE_ROLE } + const defaultRoleName = $derived(roles.find((r) => r.id === defaultRoleId)?.name ?? defaultRoleId) + const defaultsToAdmin = $derived(defaultRoleId === ADMIN_DATATABLE_ROLE) + const hasNoDefault = $derived(defaultRoleId === NO_DEFAULT_DATATABLE_ROLE) + const hasOtherRoles = $derived(roles.some((r) => r.id !== ADMIN_DATATABLE_ROLE)) + const adminOpenToEveryone = $derived( + !!roles.find((r) => r.id === ADMIN_DATATABLE_ROLE)?.tenants.includes(EVERYONE_TENANT) + ) + async function save() { saving = true // Turning roles off clears the whole block, so every role it named is removed. @@ -320,7 +343,7 @@ options={{ right: 'Put this data table under roles', rightTooltip: - 'Off, every job connects as admin — the connection that owns every table. On, every job resolves to a role, and a caller no tenant covers is refused.' + 'Off, every job connects as admin — the connection that owns every table. On, every job resolves to a role, and a caller no tenant covers is refused. It starts with admin open to everyone, so turning it on changes nothing until the roles are edited.' }} /> @@ -391,8 +414,10 @@ <Cell head> Default <Tooltip> - The role a job gets when it names none — no `-- role` annotation, no `?role=` in - the reference. Callers still have to be one of its tenants. + The role a job gets when it names none: no `-- role` annotation, no `?role=` in + the reference. There is always one choice: admin until changed, another role, or + none. Unless it is admin, the roles the person running the job is a tenant of + are added to it. </Tooltip> </Cell> <Cell head last /> @@ -440,6 +465,29 @@ </Cell> </Row> {/each} + <Row> + <Cell first class="w-56 align-top"> + <span class="text-xs text-secondary italic">No default role</span> + </Cell> + <Cell class="align-top"> + <span class="text-xs text-secondary"> + Jobs that name no role get only the roles of the person running them. + </span> + </Cell> + <Cell class="w-20 align-top"> + <div class="flex justify-center"> + <Checkbox + checked={hasNoDefault} + disabled={!editable} + title="Use no role when a job names none" + onChange={() => { + defaultRoleId = NO_DEFAULT_DATATABLE_ROLE + }} + /> + </div> + </Cell> + <Cell last class="w-10 align-top" /> + </Row> {#if editable} <Row> <Cell colspan={4} class="pt-2 pb-2"> @@ -466,6 +514,47 @@ {/if} </tbody> </DataTable> + + {#if adminOpenToEveryone} + <Alert type="warning" title="Everyone can connect as admin" size="xs"> + Every member of the workspace may use admin{defaultsToAdmin + ? ', and a job that names no role connects as it, exactly as with roles off' + : ' by naming it'}. admin owns every table: it reads every row and ignores grants + and row-level security. Once the other roles are set up, remove Everyone from admin's + tenants{defaultsToAdmin ? ' and choose another default, or none' : ''}. + </Alert> + {/if} + {#if defaultsToAdmin && hasOtherRoles && !adminOpenToEveryone} + <Alert type="warning" title="The default role is admin" size="xs"> + A job that names no role connects as admin when it runs as a workspace admin or as one + of admin's tenants, which covers every viewer of an app an admin published. admin owns + every table: it reads every row and ignores grants and row-level security. Everyone + else's jobs that name no role are refused. Choose another default, or none, to have + the roles above apply to them. + </Alert> + {:else if !defaultsToAdmin} + <div class="flex flex-col gap-1 text-xs text-secondary"> + {#if hasNoDefault} + <span> + A job that names no role connects with the roles here that the person running it + is a tenant of. It is refused when they have none, and so is a job with nobody + behind it: a schedule, a trigger, an anonymous app viewer. + </span> + {:else} + <span> + A job that names no role connects as + <span class="font-mono">{defaultRoleName}</span> when it may use it, plus every other + role here that the person running it is a tenant of. With neither, it is refused. + </span> + {/if} + <span>A job that names a role connects as that role alone.</span> + <span> + A table created over a connection that holds several roles belongs to that + combination of roles alone. Run <span class="font-mono">SET ROLE</span> to one role before + creating it, or name a role. + </span> + </div> + {/if} {/if} </div> diff --git a/frontend/src/lib/components/workspaceSettings/DucklakeSettings.svelte b/frontend/src/lib/components/workspaceSettings/DucklakeSettings.svelte index f6929e0779..a01318d916 100644 --- a/frontend/src/lib/components/workspaceSettings/DucklakeSettings.svelte +++ b/frontend/src/lib/components/workspaceSettings/DucklakeSettings.svelte @@ -91,7 +91,6 @@ import type { GetSettingsResponse } from '$lib/gen' import { enterpriseLicense, superadmin, userWorkspaces, workspaceStore } from '$lib/stores' - import { base } from '$app/paths' import Toggle from '../Toggle.svelte' import { sendUserToast } from '$lib/toast' import ExploreAssetButton from '../ExploreAssetButton.svelte' @@ -653,7 +652,7 @@ {/if} {#if ducklakeSavedSettings.ducklakes.find((d) => d.name === ducklake.name)?.maintenance?.enabled} <a - href={`${base}/runs/?schedule_path=${encodeURIComponent( + href={`/runs/?schedule_path=${encodeURIComponent( `f/ducklake_maintenance/${ducklake.name}` )}&job_kinds=previews`} target="_blank" diff --git a/frontend/src/lib/components/workspaceSettings/ForkDatatableSection.svelte b/frontend/src/lib/components/workspaceSettings/ForkDatatableSection.svelte index 9627e4a026..b7d67cd80b 100644 --- a/frontend/src/lib/components/workspaceSettings/ForkDatatableSection.svelte +++ b/frontend/src/lib/components/workspaceSettings/ForkDatatableSection.svelte @@ -13,7 +13,7 @@ import { isCloudHosted } from '$lib/cloud' import { resource } from 'runed' import Select from '../select/Select.svelte' - import Label from '../Label.svelte' + import { TriangleAlert } from 'lucide-svelte' import Alert from '../common/alert/Alert.svelte' import ConfirmationModal from '../common/confirmationModal/ConfirmationModal.svelte' @@ -21,11 +21,20 @@ // Workspace whose datatables are cloned into the fork (the fork's base). Falls back to the // current workspace so existing callers keep working. sourceWorkspace?: string + // A protection rule on the base forbids `keep_original` for the base's own datatables. + requireIsolation?: boolean + itemCount?: number onAllDone?: () => void onCanceled?: () => void } - let { sourceWorkspace, onAllDone, onCanceled }: Props = $props() + let { + sourceWorkspace, + requireIsolation = false, + itemCount = $bindable(), + onAllDone, + onCanceled + }: Props = $props() let effectiveSource = $derived(sourceWorkspace ?? $workspaceStore ?? undefined) @@ -34,8 +43,27 @@ async (ws) => (ws ? WorkspaceService.listDataTables({ workspace: ws }) : undefined) ) - let datatableBehaviors: Record<string, 'schema_only' | 'schema_and_data' | 'keep_original'> = - $state({}) + $effect(() => { + itemCount = allDatatables.current?.length ?? 0 + }) + + type Behavior = 'schema_only' | 'schema_and_data' | 'keep_original' + let datatableBehaviors: Record<string, Behavior> = $state({}) + + // An entry whose database another workspace owns is not the base's data: the rule leaves it + // alone, as the server does. + function mustClone(dt: { database_workspace_id?: string }): boolean { + return requireIsolation && !dt.database_workspace_id + } + + function behaviorOf(dt: { name: string; database_workspace_id?: string }): Behavior { + const chosen = datatableBehaviors[dt.name] ?? 'keep_original' + return mustClone(dt) && chosen === 'keep_original' ? 'schema_only' : chosen + } + + let anyShared = $derived( + (allDatatables.current ?? []).some((dt) => behaviorOf(dt) === 'keep_original') + ) let cloneModalOpen = $state(false) let currentCloneJob: DatatableCloneJob | undefined = $state(undefined) @@ -49,14 +77,11 @@ // A fork attempt starts here: what an earlier attempt confirmed is not this one's to send. confirmedJobs = [] return (allDatatables.current ?? []) - .filter((dt) => { - const behavior = datatableBehaviors[dt.name] ?? 'keep_original' - return behavior !== 'keep_original' - }) + .filter((dt) => behaviorOf(dt) !== 'keep_original') .map((dt) => ({ name: dt.name, resourceType: dt.resource_type, - behavior: datatableBehaviors[dt.name] as 'schema_only' | 'schema_and_data', + behavior: behaviorOf(dt) as 'schema_only' | 'schema_and_data', // A dev workspace's id has no `wm-fork-` prefix; its copies are named like a fork's _newDbName: `wm_fork_${targetWorkspaceId.replace(/^wm-fork-/, '').replace(/-/g, '_')}__${dt.name}` })) @@ -94,10 +119,10 @@ </script> {#if allDatatables.current && allDatatables.current.length > 0} - <Label label="Data table behavior"> - <span class="text-xs text-secondary"> Choose how to handle each datatable when forking </span> + <div class="flex flex-col gap-1"> + <span class="text-xs font-medium text-secondary">Data tables</span> <div class="border rounded-md divide-y"> - {#each allDatatables.current as dt} + {#each allDatatables.current as dt (dt.name)} <div class="flex items-center gap-2 justify-between px-4 py-1.5"> <div class="flex flex-col"> <span class="text-xs font-medium">{dt.name}</span> @@ -107,15 +132,18 @@ </div> <Select dropdownClass="max-w-96" - bind:value={ - () => datatableBehaviors[dt.name] ?? 'keep_original', - (v) => (datatableBehaviors[dt.name] = v) - } + bind:value={() => behaviorOf(dt), (v) => (datatableBehaviors[dt.name] = v)} items={[ - { - value: 'keep_original', - label: dt.permissioned ? 'Keep original (under roles)' : 'Keep original' - }, + ...(mustClone(dt) + ? [] + : [ + { + value: 'keep_original' as const, + label: dt.permissioned + ? 'Shared with parent (under roles)' + : 'Shared with parent' + } + ]), // A copy of a data table under roles carries the source's owners and grants, // which only the Enterprise Edition replays: elsewhere the server refuses it. ...(dt.permissioned && !$enterpriseLicense @@ -131,7 +159,13 @@ </div> {/each} </div> - </Label> + {#if anyShared} + <span class="flex items-center gap-1 text-2xs text-amber-700 dark:text-amber-300"> + <TriangleAlert size={12} class="shrink-0" /> + Scripts in the fork will read and write this workspace's rows. + </span> + {/if} + </div> {/if} {#if cloneModalOpen && currentCloneJob} diff --git a/frontend/src/lib/components/workspaceSettings/ForkDucklakeSection.svelte b/frontend/src/lib/components/workspaceSettings/ForkDucklakeSection.svelte index 24d3da404c..41813fa552 100644 --- a/frontend/src/lib/components/workspaceSettings/ForkDucklakeSection.svelte +++ b/frontend/src/lib/components/workspaceSettings/ForkDucklakeSection.svelte @@ -3,13 +3,16 @@ import { workspaceStore } from '$lib/stores' import { resource } from 'runed' import Select from '../select/Select.svelte' - import Label from '../Label.svelte' import { TriangleAlert } from 'lucide-svelte' // The workspace the fork is created from (matches ForkDatatableSection): a // fork-of-fork bases off the selected base, not the navigation workspace, so // the lakes listed here must match the ones the create-fork call submits to. - let { sourceWorkspace }: { sourceWorkspace?: string } = $props() + let { + sourceWorkspace, + requireIsolation = false, + itemCount = $bindable() + }: { sourceWorkspace?: string; requireIsolation?: boolean; itemCount?: number } = $props() let effectiveSource = $derived(sourceWorkspace ?? $workspaceStore ?? undefined) // Keyed on the source so a direct page load (store hydrates after mount) still fetches. @@ -18,34 +21,42 @@ async (ws) => (ws ? WorkspaceService.listDucklakes({ workspace: ws }) : undefined) ) + $effect(() => { + itemCount = allDucklakes.current?.length ?? 0 + }) + let lakeBehaviors: Record<string, 'isolated' | 'shared'> = $state({}) // Lakes the user explicitly opted out of isolation for — sent as // `shared_ducklakes` on the create-fork request. Unlisted lakes default to the // isolated fork namespace with read-defer, so nothing needs sending for them. export function getSharedDucklakes(): string[] { + if (requireIsolation) return [] return (allDucklakes.current ?? []).filter((name) => lakeBehaviors[name] === 'shared') } - let anyShared = $derived((allDucklakes.current ?? []).some((n) => lakeBehaviors[n] === 'shared')) + let anyShared = $derived( + !requireIsolation && (allDucklakes.current ?? []).some((n) => lakeBehaviors[n] === 'shared') + ) </script> <!-- Self-hides when the workspace has no ducklake configured, like the datatable section. --> {#if allDucklakes.current && allDucklakes.current.length > 0} - <Label label="Ducklake data environment"> - <span class="text-xs text-secondary"> - By default each lake is isolated in the fork: materializations write a fork-scoped namespace - and reads of not-yet-materialized tables defer to this workspace's current data. - </span> + <div class="flex flex-col gap-1"> + <span class="text-xs font-medium text-secondary">Ducklakes</span> <div class="border rounded-md divide-y"> {#each allDucklakes.current as name (name)} <div class="flex items-center gap-2 justify-between px-4 py-1.5"> <span class="text-xs font-medium">{name}</span> <Select dropdownClass="max-w-96" - bind:value={() => lakeBehaviors[name] ?? 'isolated', (v) => (lakeBehaviors[name] = v)} + disabled={requireIsolation} + bind:value={ + () => (requireIsolation ? 'isolated' : (lakeBehaviors[name] ?? 'isolated')), + (v) => (lakeBehaviors[name] = v) + } items={[ - { value: 'isolated', label: 'Isolated (defer reads to parent)' }, + { value: 'isolated', label: 'Isolated' }, { value: 'shared', label: 'Shared with parent' } ]} /> @@ -53,15 +64,10 @@ {/each} </div> {#if anyShared} - <div - class="flex items-start gap-2 px-3 py-2 text-xs rounded-md border border-amber-200 dark:border-amber-900/60 bg-amber-50 dark:bg-amber-950/40 text-amber-700 dark:text-amber-300" - > - <TriangleAlert size={14} class="shrink-0 mt-0.5" /> - <span> - A shared lake is NOT isolated: pipeline runs in the fork read and write this workspace's - tables directly. - </span> - </div> + <span class="flex items-center gap-1 text-2xs text-amber-700 dark:text-amber-300"> + <TriangleAlert size={12} class="shrink-0" /> + Pipeline runs in the fork will write this workspace's tables. + </span> {/if} - </Label> + </div> {/if} diff --git a/frontend/src/lib/components/workspaceSettings/ForkStorageSection.svelte b/frontend/src/lib/components/workspaceSettings/ForkStorageSection.svelte new file mode 100644 index 0000000000..01287a72b1 --- /dev/null +++ b/frontend/src/lib/components/workspaceSettings/ForkStorageSection.svelte @@ -0,0 +1,76 @@ +<script lang="ts"> + import { SettingService } from '$lib/gen' + import { workspaceStore } from '$lib/stores' + import { resource } from 'runed' + import Select from '../select/Select.svelte' + import { TriangleAlert } from 'lucide-svelte' + + // The workspace the fork is created from, like ForkDucklakeSection: the storages + // listed here must match the ones the create-fork call submits to. + let { + sourceWorkspace, + requireIsolation = false, + itemCount = $bindable() + }: { sourceWorkspace?: string; requireIsolation?: boolean; itemCount?: number } = $props() + let effectiveSource = $derived(sourceWorkspace ?? $workspaceStore ?? undefined) + + let storages = resource( + () => effectiveSource, + async (ws) => + ws + ? SettingService.getSecondaryStorageNames({ workspace: ws, includeDefault: true }) + : undefined + ) + + $effect(() => { + itemCount = storages.current?.length ?? 0 + }) + + let behaviors: Record<string, 'isolated' | 'shared'> = $state({}) + + // Sent as `shared_storages` on the create-fork request; unlisted storages are isolated. + export function getSharedStorages(): string[] { + if (requireIsolation) return [] + return (storages.current ?? []).filter((name) => behaviors[name] === 'shared') + } + + let anyShared = $derived( + !requireIsolation && (storages.current ?? []).some((n) => behaviors[n] === 'shared') + ) + + function storageLabel(name: string): string { + return name === '_default_' ? 'Primary storage' : name + } +</script> + +<!-- Self-hides when the workspace has no object storage configured. --> +{#if storages.current && storages.current.length > 0} + <div class="flex flex-col gap-1"> + <span class="text-xs font-medium text-secondary">Object storage</span> + <div class="border rounded-md divide-y"> + {#each storages.current as name (name)} + <div class="flex items-center gap-2 justify-between px-4 py-1.5"> + <span class="text-xs font-medium">{storageLabel(name)}</span> + <Select + dropdownClass="max-w-96" + disabled={requireIsolation} + bind:value={ + () => (requireIsolation ? 'isolated' : (behaviors[name] ?? 'isolated')), + (v) => (behaviors[name] = v) + } + items={[ + { value: 'isolated', label: 'Isolated' }, + { value: 'shared', label: 'Shared with parent' } + ]} + /> + </div> + {/each} + </div> + {#if anyShared} + <span class="flex items-center gap-1 text-2xs text-amber-700 dark:text-amber-300"> + <TriangleAlert size={12} class="shrink-0" /> + Scripts in the fork will overwrite and delete this workspace's files. + </span> + {/if} + </div> +{/if} diff --git a/frontend/src/lib/components/workspaceSettings/NewDataTableMigrationModal.svelte b/frontend/src/lib/components/workspaceSettings/NewDataTableMigrationModal.svelte index 04cf841b28..09a7ffaac8 100644 --- a/frontend/src/lib/components/workspaceSettings/NewDataTableMigrationModal.svelte +++ b/frontend/src/lib/components/workspaceSettings/NewDataTableMigrationModal.svelte @@ -17,6 +17,13 @@ import { fetchPendingMigrations, outOfOrderRunMessage } from './datatableMigrationUtils' import Select from '../select/Select.svelte' import { parseMigrationRole, withMigrationRole } from '../datatableMigrationRole' + import { + isAnnotatableSchemaName, + parseMigrationSchemas, + suggestMigrationSchemas, + withMigrationSchemas + } from '../datatableMigrationSchemas' + import MultiSelect from '../select/MultiSelect.svelte' import { ADMIN_DATATABLE_ROLE } from '../dbTypes' import { resource } from 'runed' @@ -95,12 +102,57 @@ const roleOf = (d: typeof declaredUp) => (d.kind === 'role' ? d.role : undefined) // A rollback runs as the role its own SQL names: under another role than the up migration it // typically cannot touch what the up created. + // The scope lives in the SQL too, as its `-- schemas` annotation; the picker is a view onto it. + let declaredSchemas = $derived(parseMigrationSchemas(codeUp)) + let selectedSchemas = $derived(declaredSchemas.kind === 'schemas' ? declaredSchemas.schemas : []) + let suggestedSchemas = $derived(suggestMigrationSchemas(codeUp)) + // Schemas other migrations of this data table already declare, offered next to the suggestion. + const knownSchemas = resource( + () => [workspace, datatable] as const, + async ([ws, dt]) => { + try { + const { migrations } = await WorkspaceService.getDatatableMigrationsStatus({ + workspace: ws, + datatableName: dt + }) + return migrations.flatMap((m) => m.schemas ?? []) + } catch { + return [] + } + } + ) + let schemaItems = $derived( + [ + ...new Set([ + ...selectedSchemas, + ...suggestedSchemas, + ...(knownSchemas.current ?? []), + 'public' + ]) + ].map((s) => ({ value: s, label: s })) + ) + let unsuggested = $derived( + suggestedSchemas.length > 0 && + (selectedSchemas.length !== suggestedSchemas.length || + suggestedSchemas.some((s) => !selectedSchemas.includes(s))) + ) + + function setSchemas(schemas: string[]) { + codeUp = withMigrationSchemas( + codeUp, + schemas.map((s) => s.trim().toLowerCase()).filter(isAnnotatableSchemaName) + ) + upEditor?.setCode(codeUp) + } + let sqlProblem = $derived( malformedLine !== undefined ? malformedMessage(malformedLine) - : declaredDown !== undefined && roleOf(declaredDown) !== roleOf(declaredUp) - ? `The down migration runs as ${roleOf(declaredDown) ?? 'admin (no role)'} but the up migration as ${roleOf(declaredUp) ?? 'admin (no role)'}: make their role annotations match` - : undefined + : declaredSchemas.kind === 'malformed' + ? `Malformed scope annotation \`${declaredSchemas.line}\`: write it as \`-- schemas <name>, <name>\`, or pick the schemas above` + : declaredDown !== undefined && roleOf(declaredDown) !== roleOf(declaredUp) + ? `The down migration runs as ${roleOf(declaredDown) ?? 'admin (no role)'} but the up migration as ${roleOf(declaredUp) ?? 'admin (no role)'}: make their role annotations match` + : undefined ) let selectedRole = $derived(declaredUp.kind === 'role' ? declaredUp.role : NO_ROLE) let permissioned = $derived(!!usableRoles.current?.permissioned) @@ -181,17 +233,29 @@ // Start from the transaction template; when prefilled from detected DDL, // wrap that DDL in the same BEGIN; ... END; frame. A role the prefill declares is taken // out first and put back on top: below `BEGIN;` it would not be read. + knownSchemas.refetch() const prefillRole = prefill?.codeUp ? parseMigrationRole(prefill.codeUp) : undefined if (prefill?.codeUp) { + // The scope is handled like the role. One the prefill does not declare is offered as a + // suggestion for the author to accept, never written for them. + const prefillSchemas = parseMigrationSchemas(prefill.codeUp) const wrapped = wrapInTransaction( - ensureTrailingSemicolon(withMigrationRole(prefill.codeUp, undefined)) + ensureTrailingSemicolon( + withMigrationSchemas(withMigrationRole(prefill.codeUp, undefined), []) + ) ) - codeUp = + const withRole = prefillRole?.kind === 'role' ? withMigrationRole(wrapped, prefillRole.role) : prefillRole?.kind === 'malformed' ? `${prefillRole.line}\n${wrapped}` : wrapped + codeUp = + prefillSchemas.kind === 'schemas' + ? withMigrationSchemas(withRole, prefillSchemas.schemas) + : prefillSchemas.kind === 'malformed' + ? `${prefillSchemas.line}\n${withRole}` + : withRole } else { codeUp = PLACEHOLDER } @@ -224,7 +288,7 @@ // status can't be fetched, fall through and let the run/rollback handle it. let pending: Awaited<ReturnType<typeof fetchPendingMigrations>> = [] try { - pending = await fetchPendingMigrations(workspace, datatable) + pending = await fetchPendingMigrations(workspace, datatable, codeUp) } catch {} if (pending.length > 0) { const confirmed = await confirmationModal.ask({ @@ -315,6 +379,35 @@ /> {/if} </div> + <div class="flex flex-col gap-1"> + <MultiSelect + items={schemaItems} + bind:value={() => selectedSchemas, (v) => setSchemas(v)} + placeholder="Schemas: whole database" + searchPlaceholder="Schema name" + createText="Declare schema" + onCreateItem={(s) => setSchemas([...selectedSchemas, s])} + reorderable={false} + size="sm" + /> + <div class="flex items-center gap-2 text-xs text-secondary"> + {#if selectedSchemas.length === 0} + <span> + Declares no schemas, so it applies to the whole database and every later migration waits + for it. Declare the schemas it changes. + </span> + {:else} + <span> + Waits only on earlier migrations that touch {selectedSchemas.join(', ')} or the whole database. + </span> + {/if} + {#if unsuggested} + <Button variant="subtle" unifiedSize="xs" on:click={() => setSchemas(suggestedSchemas)}> + Use {suggestedSchemas.join(', ')} + </Button> + {/if} + </div> + </div> {#if sqlProblem !== undefined} <p class="text-xs text-red-500">{sqlProblem}</p> {:else if permissioned && usableRoles.current?.roles.length === 0} diff --git a/frontend/src/lib/components/workspaceSettings/RulesetEditor.svelte b/frontend/src/lib/components/workspaceSettings/RulesetEditor.svelte index eefc1d5647..43f5434c4d 100644 --- a/frontend/src/lib/components/workspaceSettings/RulesetEditor.svelte +++ b/frontend/src/lib/components/workspaceSettings/RulesetEditor.svelte @@ -1,8 +1,8 @@ <script lang="ts"> - import { Section, Button, Badge } from '$lib/components/common' + import { Section, Button, DrawerContent } from '$lib/components/common' import Toggle from '$lib/components/Toggle.svelte' import Label from '$lib/components/Label.svelte' - import Select from '$lib/components/select/Select.svelte' + import MultiSelect from '$lib/components/select/MultiSelect.svelte' import TextInput from '$lib/components/text_input/TextInput.svelte' import { workspaceStore } from '$lib/stores' import { @@ -16,16 +16,17 @@ import { clone } from '$lib/utils' import { DEV_WORKSPACE_LOCK_RULE_NAME } from '$lib/workspaceProtectionRules.svelte' import { untrack } from 'svelte' - import { Save, X, Plus } from 'lucide-svelte' + import { Save } from 'lucide-svelte' import { safeSelectItems } from '$lib/components/select/utils.svelte' interface Props { rule?: ProtectionRuleset existingNames?: string[] onUpdate?: () => void + onClose: () => void } - let { rule, existingNames = [], onUpdate }: Props = $props() + let { rule, existingNames = [], onUpdate, onClose }: Props = $props() // Create mode vs Edit mode const isCreateMode = $derived(!rule) @@ -44,6 +45,7 @@ let restrictAnonymousAppDeployment = $state(hasRule('RestrictAnonymousAppDeployment')) let restrictPublicRunSharing = $state(hasRule('RestrictPublicRunSharing')) let restrictGuestAppDeployment = $state(hasRule('RestrictGuestAppDeployment')) + let requireIsolatedForks = $state(hasRule('RequireIsolatedForks')) let selectedGroups = $state<string[]>( untrack(() => rule)?.bypass_groups?.map((g) => g.replace('g/', '')) ?? [] ) @@ -59,6 +61,7 @@ let initialRestrictAnonymousAppDeployment = $state(hasRule('RestrictAnonymousAppDeployment')) let initialRestrictPublicRunSharing = $state(hasRule('RestrictPublicRunSharing')) let initialRestrictGuestAppDeployment = $state(hasRule('RestrictGuestAppDeployment')) + let initialRequireIsolatedForks = $state(hasRule('RequireIsolatedForks')) let initialSelectedGroups = $state<string[]>( untrack(() => rule)?.bypass_groups ? untrack(() => rule)!.bypass_groups.map((g) => g.replace('g/', '')) @@ -74,9 +77,7 @@ let availableGroups = $state<string[]>([]) let availableUsers = $state<string[]>([]) - // Temporary values for Select dropdowns - let selectedGroupToAdd = $state<string | undefined>(undefined) - let selectedUserToAdd = $state<string | undefined>(undefined) + let saving = $state(false) // Load available groups and users async function loadAvailableGroups() { @@ -98,26 +99,6 @@ } }) - // Effect to add selected group - $effect(() => { - if (selectedGroupToAdd && !selectedGroups.includes(selectedGroupToAdd)) { - selectedGroups = [...selectedGroups, selectedGroupToAdd] - untrack(() => { - selectedGroupToAdd = undefined // Reset for next selection - }) - } - }) - - // Effect to add selected user - $effect(() => { - if (selectedUserToAdd && !selectedUsers.includes(selectedUserToAdd)) { - selectedUsers = [...selectedUsers, selectedUserToAdd] - untrack(() => { - selectedUserToAdd = undefined // Reset for next selection - }) - } - }) - // Computed properties const hasUnsavedChanges = $derived( isCreateMode @@ -128,6 +109,7 @@ restrictAnonymousAppDeployment || restrictPublicRunSharing || restrictGuestAppDeployment || + requireIsolatedForks || selectedGroups.length > 0 || selectedUsers.length > 0 : name !== initialName || @@ -137,6 +119,7 @@ restrictAnonymousAppDeployment !== initialRestrictAnonymousAppDeployment || restrictPublicRunSharing !== initialRestrictPublicRunSharing || restrictGuestAppDeployment !== initialRestrictGuestAppDeployment || + requireIsolatedForks !== initialRequireIsolatedForks || JSON.stringify([...selectedGroups].sort()) !== JSON.stringify([...initialSelectedGroups].sort()) || JSON.stringify([...selectedUsers].sort()) !== @@ -155,17 +138,10 @@ const canSave = $derived(!nameError && hasUnsavedChanges) - function removeGroup(group: string) { - selectedGroups = selectedGroups.filter((g) => g !== group) - } - - function removeUser(user: string) { - selectedUsers = selectedUsers.filter((u) => u !== user) - } - async function create() { if (!canSave || !$workspaceStore) return + saving = true try { await WorkspaceService.createProtectionRule({ workspace: $workspaceStore, @@ -183,7 +159,8 @@ ...(restrictPublicRunSharing ? ['RestrictPublicRunSharing' as ProtectionRuleKind] : []), ...(restrictGuestAppDeployment ? ['RestrictGuestAppDeployment' as ProtectionRuleKind] - : []) + : []), + ...(requireIsolatedForks ? ['RequireIsolatedForks' as ProtectionRuleKind] : []) ], bypass_groups: selectedGroups, bypass_users: selectedUsers @@ -195,12 +172,15 @@ } catch (error) { console.error('Failed to create protection rule:', error) sendUserToast('Failed to create protection rule', true) + } finally { + saving = false } } async function save() { if (!canSave || !$workspaceStore) return + saving = true try { await WorkspaceService.updateProtectionRule({ workspace: $workspaceStore, @@ -219,7 +199,8 @@ ...(restrictPublicRunSharing ? ['RestrictPublicRunSharing' as ProtectionRuleKind] : []), ...(restrictGuestAppDeployment ? ['RestrictGuestAppDeployment' as ProtectionRuleKind] - : []) + : []), + ...(requireIsolatedForks ? ['RequireIsolatedForks' as ProtectionRuleKind] : []) ], bypass_groups: selectedGroups, bypass_users: selectedUsers @@ -236,6 +217,7 @@ initialRestrictAnonymousAppDeployment = restrictAnonymousAppDeployment initialRestrictPublicRunSharing = restrictPublicRunSharing initialRestrictGuestAppDeployment = restrictGuestAppDeployment + initialRequireIsolatedForks = requireIsolatedForks initialSelectedGroups = clone(selectedGroups) initialSelectedUsers = clone(selectedUsers) @@ -243,198 +225,138 @@ } catch (error) { console.error('Failed to save protection rule:', error) sendUserToast('Failed to save protection rule', true) + } finally { + saving = false } } + + // The required marker already says an empty name is missing; only a clash needs words. + const shownNameError = $derived(name.trim() ? nameError : undefined) </script> -<div class="flex flex-col gap-6 p-4"> - <!-- Name Section --> - <span class="text-secondary text-sm"> - Keep in mind that rulesets can take up to one minute to take effect - </span> - <Section label="Rule Name" class="space-y-2"> - <TextInput - size="md" - bind:value={name} - error={nameError} - inputProps={{ - placeholder: 'Enter rule name', - disabled: isNameLocked - }} - /> - {#if isNameLocked} - <div class="text-xs text-secondary"> - Managed by the dev workspace pairing, which locates this rule by name. Its restrictions and - bypassers below can still be changed. - </div> - {:else if nameError} - <div class="text-xs text-red-600">{nameError}</div> - {/if} - </Section> +<!-- `pl-11` lines the text up with the toggle's label: the `sm` track is 36px plus its 8px gap. --> +{#snippet description(text: string)} + <p class="text-xs text-secondary pl-11">{text}</p> +{/snippet} - <!-- Bypass Permissions Section --> - <Section - label="Bypass Permissions" - description="Select the groups and/or users who can bypass the restrictions defined in this rule. These users will be exempt from the rules configured below." - class="space-y-4" - > - <!-- Groups --> - <div class="flex flex-col gap-2"> - <Label class="text-xs">Groups</Label> - <Select - bind:value={selectedGroupToAdd} - items={safeSelectItems(availableGroups.filter((g) => !selectedGroups.includes(g)))} - placeholder="Select groups..." +<DrawerContent + title={rule ? `Protection rule ${rule.name}` : 'New protection rule'} + on:close={onClose} +> + <div class="flex flex-col gap-6"> + <p class="text-xs text-secondary">A rule can take up to one minute to take effect.</p> + + <Label label="Name" required> + <TextInput + bind:value={name} + error={shownNameError} + inputProps={{ + placeholder: 'Enter rule name', + disabled: isNameLocked + }} /> - {#if selectedGroups.length > 0} - <div class="flex flex-wrap gap-2 mt-2"> - {#each selectedGroups as group (group)} - <Badge color="blue" class="flex items-center gap-1"> - {group} - <button - type="button" - onclick={() => removeGroup(group)} - class="ml-1 hover:text-red-600" - > - <X size={14} /> - </button> - </Badge> - {/each} - </div> + {#if isNameLocked} + <p class="text-2xs text-hint"> + Managed by the dev workspace pairing, which locates this rule by name. Its restrictions + and bypassers can still be changed. + </p> + {:else if shownNameError} + <p class="text-2xs text-red-500">{shownNameError}</p> {/if} - </div> + </Label> - <!-- Users --> - <div class="flex flex-col gap-2"> - <Label class="text-xs">Users</Label> - <Select - bind:value={selectedUserToAdd} - items={safeSelectItems(availableUsers.filter((u) => !selectedUsers.includes(u)))} - placeholder="Select users..." - /> - {#if selectedUsers.length > 0} - <div class="flex flex-wrap gap-2 mt-2"> - {#each selectedUsers as user (user)} - <Badge color="indigo" class="flex items-center gap-1"> - {user} - <button - type="button" - onclick={() => removeUser(user)} - class="ml-1 hover:text-red-600" - > - <X size={14} /> - </button> - </Badge> - {/each} - </div> - {/if} - </div> - </Section> + <Section + label="Bypassers" + description="Groups and users who are exempt from the restrictions below." + class="flex flex-col gap-4" + > + <Label label="Groups"> + <MultiSelect + bind:value={selectedGroups} + items={safeSelectItems(availableGroups)} + placeholder="Select groups" + reorderable={false} + /> + </Label> + <Label label="Users"> + <MultiSelect + bind:value={selectedUsers} + items={safeSelectItems(availableUsers)} + placeholder="Select users" + reorderable={false} + /> + </Label> + </Section> - <!-- Protection Rules Section --> - <Section - label="Protection Rules" - description="Configure the rules that will be enforced" - class="space-y-4" - > - <div class="flex flex-col gap-4"> - <!-- Disable Direct Deployment --> - <div class="flex flex-col gap-2"> + <Section label="Restrictions" class="flex flex-col gap-4"> + <div class="flex flex-col gap-1"> <Toggle bind:checked={disableDirectDeployment} - options={{ - right: 'Disable direct deployment' - }} + options={{ right: 'Disable direct deployment' }} /> - <div class="text-xs text-secondary ml-6"> - Users must use a fork or git branch to make changes. Direct edits are not allowed. - </div> + {@render description( + 'Users must use a fork or git branch to make changes. Direct edits are not allowed.' + )} </div> - - <!-- Disable Fork --> - <div class="flex flex-col gap-2"> - <Toggle - bind:checked={disableFork} - options={{ - right: 'Disable workspace forking' - }} - /> - <div class="text-xs text-secondary ml-6">Users cannot create forks of this workspace.</div> + <div class="flex flex-col gap-1"> + <Toggle bind:checked={disableFork} options={{ right: 'Disable workspace forking' }} /> + {@render description('Users cannot create forks of this workspace.')} </div> - - <!-- Restrict deploy to deployers --> - <div class="flex flex-col gap-2"> + <div class="flex flex-col gap-1"> + <Toggle bind:checked={requireIsolatedForks} options={{ right: 'Require isolated forks' }} /> + {@render description( + "Forks of this workspace cannot share its data: every object storage and ducklake stays isolated, and every data table is cloned instead of pointing at this workspace's database." + )} + </div> + <div class="flex flex-col gap-1"> <Toggle bind:checked={restrictDeployToDeployers} - options={{ - right: 'Restrict deployment to wm_deployers' - }} + options={{ right: 'Restrict deployment to wm_deployers' }} /> - <div class="text-xs text-secondary ml-6"> - Only workspace admins and members of <code>wm_deployers</code> can deploy to this workspace. - Non-deployers can still fork, browse, and request a review. - </div> + {@render description( + 'Only workspace admins and members of wm_deployers can deploy to this workspace. Non-deployers can still fork, browse, and request a review.' + )} </div> - - <!-- Restrict anonymous app deployment --> - <div class="flex flex-col gap-2"> + <div class="flex flex-col gap-1"> <Toggle bind:checked={restrictAnonymousAppDeployment} - options={{ - right: 'Restrict public app access' - }} + options={{ right: 'Restrict public app access' }} /> - <div class="text-xs text-secondary ml-6"> - Only workspace admins and bypass users can make an app publicly accessible without login - (anonymous execution mode). Apps that are already public can still be redeployed. - </div> + {@render description( + 'Only workspace admins and bypassers can make an app publicly accessible without login (anonymous execution mode). Apps that are already public can still be redeployed.' + )} </div> - - <!-- Restrict guest app deployment --> - <div class="flex flex-col gap-2"> + <div class="flex flex-col gap-1"> <Toggle bind:checked={restrictGuestAppDeployment} - options={{ - right: 'Restrict guest app access' - }} + options={{ right: 'Restrict guest app access' }} /> - <div class="text-xs text-secondary ml-6"> - Only workspace admins and bypass users can open an app to guests (anyone who signs in, - with no workspace membership and no seat). Apps that already admit guests can still be - redeployed. - </div> + {@render description( + 'Only workspace admins and bypassers can open an app to guests (anyone who signs in, with no workspace membership and no seat). Apps that already admit guests can still be redeployed.' + )} </div> - - <!-- Restrict public run sharing --> - <div class="flex flex-col gap-2"> + <div class="flex flex-col gap-1"> <Toggle bind:checked={restrictPublicRunSharing} - options={{ - right: 'Restrict public run sharing' - }} + options={{ right: 'Restrict public run sharing' }} /> - <div class="text-xs text-secondary ml-6"> - Only workspace admins and bypass users can mint a public link to a run (readable without - login). The read-only link for workspace members stays available to everyone. - </div> + {@render description( + 'Only workspace admins and bypassers can mint a public link to a run (readable without login). The read-only link for workspace members stays available to everyone.' + )} </div> - </div> - </Section> + </Section> + </div> - <!-- Actions --> - <div class="flex items-center gap-4 pt-4 border-t"> + {#snippet actions()} <Button variant="accent" unifiedSize="md" disabled={!canSave} + loading={saving} + startIcon={{ icon: Save }} on:click={isCreateMode ? create : save} - startIcon={{ icon: isCreateMode ? Plus : Save }} > - {isCreateMode ? 'Create Rule' : 'Save Rule'} + {isCreateMode ? 'Create' : 'Save'} </Button> - - {#if hasUnsavedChanges && !isCreateMode} - <span class="text-xs text-secondary">You have unsaved changes</span> - {/if} - </div> -</div> + {/snippet} +</DrawerContent> diff --git a/frontend/src/lib/components/workspaceSettings/WorkspaceRulesets.svelte b/frontend/src/lib/components/workspaceSettings/WorkspaceRulesets.svelte index 142c2ad29f..805dc85764 100644 --- a/frontend/src/lib/components/workspaceSettings/WorkspaceRulesets.svelte +++ b/frontend/src/lib/components/workspaceSettings/WorkspaceRulesets.svelte @@ -1,5 +1,5 @@ <script lang="ts"> - import { Alert, Button, Drawer, DrawerContent, Skeleton } from '$lib/components/common' + import { Alert, Button, Drawer, Skeleton } from '$lib/components/common' import Dropdown from '$lib/components/DropdownV2.svelte' import DataTable from '$lib/components/table/DataTable.svelte' import Head from '$lib/components/table/Head.svelte' @@ -99,19 +99,15 @@ </script> <Drawer bind:this={ruleDrawer}> - <DrawerContent - title={selectedRule ? `Protection Rule: ${selectedRule.name}` : 'New Protection Rule'} - on:close={ruleDrawer?.closeDrawer} - > - <RulesetEditor - rule={selectedRule} - existingNames={existingRuleNames} - onUpdate={() => { - loadRules() - ruleDrawer?.closeDrawer() - }} - /> - </DrawerContent> + <RulesetEditor + rule={selectedRule} + existingNames={existingRuleNames} + onClose={() => ruleDrawer?.closeDrawer()} + onUpdate={() => { + loadRules() + ruleDrawer?.closeDrawer() + }} + /> </Drawer> {#if !$enterpriseLicense} diff --git a/frontend/src/lib/components/workspaceSettings/WorkspaceSettingsYaml.svelte b/frontend/src/lib/components/workspaceSettings/WorkspaceSettingsYaml.svelte new file mode 100644 index 0000000000..891ed55008 --- /dev/null +++ b/frontend/src/lib/components/workspaceSettings/WorkspaceSettingsYaml.svelte @@ -0,0 +1,278 @@ +<script lang="ts"> + import { Alert, Skeleton } from '$lib/components/common' + import ConfirmationModal from '$lib/components/common/confirmationModal/ConfirmationModal.svelte' + import SettingsFooter from './SettingsFooter.svelte' + import { WorkspaceService } from '$lib/gen' + import type { ApplyWorkspaceSettingsDocumentResponse } from '$lib/gen' + import { workspaceStore } from '$lib/stores' + import { sendUserToast } from '$lib/toast' + import { Loader2 } from 'lucide-svelte' + import YAML from 'yaml' + import { untrack } from 'svelte' + import type SimpleEditor from '$lib/components/SimpleEditor.svelte' + + let { + onApplied + }: { + /** Called after the document was applied, so the form panes can reload what they show. */ + onApplied?: () => void | Promise<void> + } = $props() + + type Change = ApplyWorkspaceSettingsDocumentResponse['changes'][number] + + // Keys the server never applies from the document. `color` and `operator_settings` are applied + // when set but a null one is ignored, so deleting them does not clear them either. + const READ_ONLY_KEYS = ['name', 'slack_team_id', 'slack_name'] + const NOT_CLEARABLE_KEYS = ['color', 'operator_settings'] + + let loading = $state(true) + let code = $state('') + let initialCode = $state('') + let loadedKeys: string[] = [] + let editor: SimpleEditor | undefined = $state(undefined) + + let loadError = $state('') + let parseError = $state('') + let applyError = $state('') + let warnings: string[] = $state([]) + + // The workspace the editor's document was loaded from. Requests go there rather than to the + // workspace selected at call time, so a document is never applied to another workspace. + let documentWorkspace: string | undefined = undefined + let pendingWorkspace: string | undefined = undefined + let pendingDocument: Record<string, unknown> | undefined = undefined + let pendingChanges: Change[] = $state([]) + let confirmOpen = $state(false) + let applying = $state(false) + + function clearPending() { + confirmOpen = false + pendingDocument = undefined + pendingWorkspace = undefined + } + + async function load() { + const workspace = $workspaceStore! + if (workspace !== documentWorkspace) { + documentWorkspace = undefined + loadedKeys = [] + code = '' + initialCode = '' + editor?.setCode('') + applyError = '' + warnings = [] + clearPending() + } + loading = true + loadError = '' + let doc: Record<string, unknown> | undefined + try { + doc = await WorkspaceService.getWorkspaceSettingsDocument({ workspace }) + } catch (e) { + if (workspace === $workspaceStore) loadError = errorMessage(e) + } + if (workspace !== $workspaceStore) return + loadedKeys = doc ? Object.keys(doc) : [] + code = doc ? YAML.stringify(doc) : '' + initialCode = code + editor?.setCode(code) + parseError = '' + documentWorkspace = workspace + loading = false + } + + $effect(() => { + if ($workspaceStore) { + untrack(() => load()) + } + }) + + function errorMessage(e: unknown): string { + const body = (e as { body?: unknown })?.body + if (typeof body === 'string' && body) return body + return e instanceof Error ? e.message : String(e) + } + + /** The document to send: a key the editor no longer has becomes `null`, which clears it. */ + function documentFromEditor(): Record<string, unknown> | undefined { + const current = editor?.getCode() ?? code + code = current + let parsed: unknown + try { + parsed = YAML.parse(current) + } catch (e) { + parseError = String(e) + return undefined + } + if (parsed == null) parsed = {} + if (typeof parsed !== 'object' || Array.isArray(parsed)) { + parseError = 'The document must be a mapping (key: value)' + return undefined + } + parseError = '' + const doc = { ...(parsed as Record<string, unknown>) } + for (const key of loadedKeys) { + if (!(key in doc)) doc[key] = null + } + return doc + } + + async function review(): Promise<boolean> { + applyError = '' + warnings = [] + const workspace = documentWorkspace + if (!workspace) return false + const document = documentFromEditor() + if (!document) return false + try { + const res = await WorkspaceService.applyWorkspaceSettingsDocument({ + workspace, + requestBody: { document, replace: false, dry_run: true } + }) + if (workspace !== documentWorkspace) return false + warnings = res.warnings ?? [] + if (res.changes.length === 0) { + sendUserToast('No setting would change') + return false + } + pendingWorkspace = workspace + pendingDocument = document + pendingChanges = res.changes + confirmOpen = true + } catch (e) { + if (workspace === documentWorkspace) applyError = errorMessage(e) + } + return false + } + + async function apply() { + const workspace = pendingWorkspace + const document = pendingDocument + if (!document || !workspace || workspace !== documentWorkspace) { + clearPending() + return + } + applying = true + let ok = false + try { + const res = await WorkspaceService.applyWorkspaceSettingsDocument({ + workspace, + requestBody: { document, replace: false } + }) + warnings = res.warnings ?? [] + ok = true + sendUserToast(`Applied ${res.changes.length} setting change(s)`) + } catch (e) { + applyError = errorMessage(e) + } finally { + applying = false + clearPending() + } + // A failing write stops the apply but keeps the writes before it, so the form panes reload + // either way; the editor keeps the user's text on failure so it can be fixed and retried. + try { + await Promise.all([ok ? load() : undefined, onApplied?.()]) + } catch (e) { + sendUserToast(`Could not reload the settings: ${errorMessage(e)}`, true) + } + } + + export function discard() { + code = initialCode + editor?.setCode(initialCode) + parseError = '' + applyError = '' + warnings = [] + } + + export function unsavedChanges() { + return { + savedValue: { code: initialCode }, + modifiedValue: { code: editor?.getCode() ?? code } + } + } + + function formatValue(v: unknown): string { + if (v === null || v === undefined) return 'unset' + const s = typeof v === 'string' ? v : JSON.stringify(v) + return s.length > 200 ? s.slice(0, 200) + '…' : s + } +</script> + +<div class="flex flex-col gap-2 h-full"> + <p class="text-xs text-secondary"> + The workspace settings in the layout of the <code>settings.yaml</code> file that + <code>wmill sync</code> reads and writes. Deleting a key clears that setting. Secrets show as + <code>__SENSITIVE_AND_UNCHANGED__</code>: leave the placeholder to keep the stored value. + </p> + <Alert type="info" title="Read-only keys" size="xs"> + {#each READ_ONLY_KEYS as key, i (key)}<code>{key}</code>{i < READ_ONLY_KEYS.length - 1 + ? ', ' + : ''}{/each} are shown for reference and never applied: change the name from the General pane + and connect Slack from the Slack pane. + {#each NOT_CLEARABLE_KEYS as key, i (key)}<code>{key}</code>{i < NOT_CLEARABLE_KEYS.length - 1 + ? ' and ' + : ''}{/each} are applied when set, but deleting them does not clear them. + </Alert> + + <div class="border rounded w-full h-[calc(100vh-22rem)] min-h-64"> + {#if loading && !initialCode} + <Skeleton layout={[[20]]} /> + {:else} + {#await import('$lib/components/SimpleEditor.svelte')} + <Loader2 class="animate-spin" /> + {:then Module} + <Module.default + bind:this={editor} + class="h-full" + lang="yaml" + bind:code + leadingChangeSync + fixedOverflowWidgets={false} + /> + {/await} + {/if} + </div> + + {#if loadError} + <Alert type="error" title="The settings could not be loaded" size="xs">{loadError}</Alert> + {/if} + {#if parseError} + <Alert type="error" title="Invalid YAML" size="xs">{parseError}</Alert> + {/if} + {#if applyError} + <Alert type="error" title="The settings could not be applied" size="xs">{applyError}</Alert> + {/if} + {#each warnings as warning, i (i)} + <Alert type="warning" title="Warning" size="xs">{warning}</Alert> + {/each} + + <SettingsFooter + inline + hasUnsavedChanges={code !== initialCode} + saveLabel="Review and save" + onSave={review} + onDiscard={discard} + /> +</div> + +<ConfirmationModal + open={confirmOpen} + title="Apply these changes?" + confirmationText="Apply" + type="info" + loading={applying} + onConfirmed={apply} + onCanceled={clearPending} +> + <div class="flex flex-col gap-2 max-h-96 overflow-auto"> + {#each pendingChanges as change (change.key)} + <div class="flex flex-col gap-0.5"> + <span class="text-xs font-semibold text-emphasis font-mono">{change.key}</span> + <span class="text-2xs text-secondary font-mono break-all"> + {formatValue(change.before)} → {formatValue(change.after)} + </span> + </div> + {/each} + </div> +</ConfirmationModal> diff --git a/frontend/src/lib/components/workspaceSettings/datatableMigrationUtils.ts b/frontend/src/lib/components/workspaceSettings/datatableMigrationUtils.ts index ed046418f2..29e5c73b9a 100644 --- a/frontend/src/lib/components/workspaceSettings/datatableMigrationUtils.ts +++ b/frontend/src/lib/components/workspaceSettings/datatableMigrationUtils.ts @@ -1,30 +1,34 @@ import { WorkspaceService, type DatatableMigrationWithStatus } from '$lib/gen' +import { migrationScope, scopesOverlap } from '../datatableMigrationSchemas' /** - * Migrations that are defined but not yet applied. A newly-created migration - * always gets the highest timestamp, so every pending migration is "earlier": - * running the new one on its own would apply it ahead of them (out of order). + * The pending migrations a new migration declaring `sql`'s scope would run ahead of. A + * newly-created migration always gets the highest timestamp, so every pending migration is + * "earlier"; only those whose scope overlaps its own can be ones it depends on. */ export function pendingMigrations( - migrations: DatatableMigrationWithStatus[] + migrations: DatatableMigrationWithStatus[], + sql: string ): DatatableMigrationWithStatus[] { - return migrations.filter((m) => m.status !== 'ran') + const scope = migrationScope(sql) + return migrations.filter((m) => m.status !== 'ran' && scopesOverlap(m.schemas, scope)) } -/** Fetch the data table's migration status and return the pending ones. */ +/** Fetch the data table's migration status and return the pending ones `sql` would run ahead of. */ export async function fetchPendingMigrations( workspace: string, - datatableName: string + datatableName: string, + sql: string ): Promise<DatatableMigrationWithStatus[]> { const { migrations } = await WorkspaceService.getDatatableMigrationsStatus({ workspace, datatableName }) - return pendingMigrations(migrations) + return pendingMigrations(migrations, sql) } /** Confirmation copy shown before running a just-created migration ahead of * `count` still-pending earlier ones (mirrors the row-level Run warning). */ export function outOfOrderRunMessage(count: number): string { - return `${count} earlier migration(s) have not been run yet. This migration might depend on them. Run it anyway?` + return `${count} earlier migration(s) touching the same schemas have not been run yet. This migration might depend on them. Run it anyway?` } diff --git a/frontend/src/lib/components/workspaceSettings/deployToHubSession.svelte.ts b/frontend/src/lib/components/workspaceSettings/deployToHubSession.svelte.ts index c421553a7c..5a46f0a1b8 100644 --- a/frontend/src/lib/components/workspaceSettings/deployToHubSession.svelte.ts +++ b/frontend/src/lib/components/workspaceSettings/deployToHubSession.svelte.ts @@ -1,5 +1,4 @@ import { untrack } from 'svelte' -import { base } from '$lib/base' import { AppService, FlowService, @@ -486,10 +485,10 @@ export class DeployToHubSession { itemUrl(kind: ItemKind, path: string): string | undefined { if (!path) return undefined - return `${base}/${ITEM_KIND_ROUTE[kind]}/${path}?workspace=${this.workspace}` + return `/${ITEM_KIND_ROUTE[kind]}/${path}?workspace=${this.workspace}` } triggerListUrl(kind: WorkspaceTriggerKind): string { - return `${base}/${TRIGGER_KINDS[kind].route}?workspace=${this.workspace}` + return `/${TRIGGER_KINDS[kind].route}?workspace=${this.workspace}` } #patchItem(key: string, patch: Partial<DeployItem>) { diff --git a/frontend/src/lib/components/workspaceSettings/supabaseOauth.svelte.ts b/frontend/src/lib/components/workspaceSettings/supabaseOauth.svelte.ts index 3e11ec2b9d..94c21cf591 100644 --- a/frontend/src/lib/components/workspaceSettings/supabaseOauth.svelte.ts +++ b/frontend/src/lib/components/workspaceSettings/supabaseOauth.svelte.ts @@ -1,9 +1,8 @@ import { fromStore } from 'svelte/store' -import { base } from '$lib/base' import { oauthStore } from '$lib/stores' const OAUTH_WINDOW = 'windmill_supabase_oauth' -const CONNECT_URL = `${base}/api/oauth/connect/supabase_wizard` +const CONNECT_URL = '/api/oauth/connect/supabase_wizard' /** * The Supabase authorization leg, driven from a popup. diff --git a/frontend/src/lib/components/workspaceSettings/supabaseProvisioning.ts b/frontend/src/lib/components/workspaceSettings/supabaseProvisioning.ts index 5040b5ab38..ee91a0ba3c 100644 --- a/frontend/src/lib/components/workspaceSettings/supabaseProvisioning.ts +++ b/frontend/src/lib/components/workspaceSettings/supabaseProvisioning.ts @@ -7,7 +7,6 @@ */ import { DEFAULT_SSLMODE } from '$lib/utils/postgresConnectionString' -import { base } from '$lib/base' import { oauthStore } from '$lib/stores' import { get } from 'svelte/store' @@ -90,19 +89,19 @@ export function supabaseErrorMessage(body: string): string { } export async function listSupabaseOrgs(token: string): Promise<SupabaseOrg[]> { - const res = await fetch(`${base}/api/oauth/list_supabase_orgs`, { headers: headers(token) }) + const res = await fetch('/api/oauth/list_supabase_orgs', { headers: headers(token) }) return unwrap(res, 'Could not list your Supabase organizations') } export async function listSupabaseProjects(token: string): Promise<SupabaseProject[]> { - const res = await fetch(`${base}/api/oauth/list_supabase`, { headers: headers(token) }) + const res = await fetch('/api/oauth/list_supabase', { headers: headers(token) }) return unwrap(res, 'Could not list your Supabase projects') } /** Plan of one organization, which the list endpoint does not carry. */ export async function getSupabaseOrgPlan(token: string, slug: string): Promise<string | undefined> { try { - const res = await fetch(`${base}/api/oauth/get_supabase_org/${slug}`, { + const res = await fetch(`/api/oauth/get_supabase_org/${slug}`, { headers: headers(token) }) if (!res.ok) return undefined @@ -132,7 +131,7 @@ export async function createSupabaseProject( token: string, args: { name: string; organizationSlug: string; region: string; dbPass: string } ): Promise<SupabaseProject> { - const res = await fetch(`${base}/api/oauth/create_supabase_project`, { + const res = await fetch('/api/oauth/create_supabase_project', { method: 'POST', headers: headers(token), body: JSON.stringify({ @@ -185,7 +184,7 @@ export async function waitUntilSupabaseHealthy( * that landed on another one, and the resulting resource never connects. */ export async function getSupabasePooler(token: string, projectId: string): Promise<SupabasePooler> { - const res = await fetch(`${base}/api/oauth/get_supabase_pooler/${projectId}`, { + const res = await fetch(`/api/oauth/get_supabase_pooler/${projectId}`, { headers: headers(token) }) const configs: SupabasePooler[] = await unwrap(res, 'Could not read the connection details') diff --git a/frontend/src/lib/components/workspaceTree.test.ts b/frontend/src/lib/components/workspaceTree.test.ts index f9c00b4d7b..96d54bb8be 100644 --- a/frontend/src/lib/components/workspaceTree.test.ts +++ b/frontend/src/lib/components/workspaceTree.test.ts @@ -7,7 +7,7 @@ import { type WorkspaceItem, type WorkspaceItemKind } from './workspacePicker' -import type { DrillBranch, DrillLeaf, DrillNode } from './drillPicker' +import { resolveScope, type DrillBranch, type DrillLeaf, type DrillNode } from './drillPicker' const item = ( kind: WorkspaceItemKind, @@ -522,6 +522,17 @@ describe('legacyScopeToPath', () => { ]) }) + it('walks every ancestor folder, so a nested dir resolves in the built tree', () => { + const loaded = { flow: [item('flow', 'f/a/b/c')], script: [] } + for (const layout of ['flat', 'by-kind'] as const) { + const tree = buildWorkspaceTree({ loaded, kinds: ['flow', 'script'], loadingKind: {}, layout }) + const path = legacyScopeToPath({ kind: 'flow', dir: 'f/a/b' }, ['flow', 'script'], layout) + expect(resolveScope(tree, path)?.children.map((c) => c.key)).toEqual([ + leafKeyFor('flow', 'f/a/b/c') + ]) + } + }) + it('flat: returns [] without a dir', () => { expect(legacyScopeToPath({ kind: 'all' }, ['flow', 'script'], 'flat')).toEqual([]) }) diff --git a/frontend/src/lib/components/workspaceTree.ts b/frontend/src/lib/components/workspaceTree.ts index 9475b58af5..6c719dafb1 100644 --- a/frontend/src/lib/components/workspaceTree.ts +++ b/frontend/src/lib/components/workspaceTree.ts @@ -271,19 +271,20 @@ export function legacyScopeToPath( layout: 'by-kind' | 'flat' = 'by-kind' ): string[] { if (!scope) return [] + // A subfolder is a child of its parent's branch, not a root entry, so a scope into + // `f/a/b` must walk `f/a` first or it resolves to nothing. + const dirChain = (kind: WorkspaceItemKind | 'all') => { + if (!scope.dir) return [] + const parts = scope.dir.split('/') + return parts.slice(1).map((_, i) => dirKey(kind, parts.slice(0, i + 2).join('/'))) + } // Flat layout: no kind branches at all — scope dirs live at root and are // always keyed under the cross-kind 'all' namespace. - if (layout === 'flat') { - return scope.dir ? [dirKey('all', scope.dir)] : [] - } + if (layout === 'flat') return dirChain('all') // Single-kind mode: there's no kind branch at root; scope's `kind` is // implicit. Only the dir (if any) makes it to the path. - if (kinds.length === 1) { - return scope.dir ? [dirKey(scope.kind, scope.dir)] : [] - } - const path: string[] = [kindKey(scope.kind)] - if (scope.dir) path.push(dirKey(scope.kind, scope.dir)) - return path + if (kinds.length === 1) return dirChain(scope.kind) + return [kindKey(scope.kind), ...dirChain(scope.kind)] } /** Return `absolutePath` shortened to its segment relative to the deepest diff --git a/frontend/src/lib/consts.ts b/frontend/src/lib/consts.ts index bfa1d845b2..a6bbc25d49 100644 --- a/frontend/src/lib/consts.ts +++ b/frontend/src/lib/consts.ts @@ -48,6 +48,10 @@ export const DEFAULT_TAGS_WORKSPACES_SETTING = 'default_tags_workspaces' export const FORK_WORKSPACE_TAG_APPEND_FORK_SUFFIX_SETTING = 'fork_workspace_tag_append_fork_suffix' export const PREVIEW_TAGS_OVERRIDE_SETTING = 'preview_tags_override' export const DEPENDENCY_JOB_TAG_SETTING = 'dependency_job_tag' +export const DEV_WORKSPACE_ISOLATION_SETTING = 'dev_workspace_isolation' +export const DEV_WORKSPACE_ISOLATION_SKIP_NON_DEV_FORKS_SETTING = + 'dev_workspace_isolation_skip_non_dev_forks' +export const DEV_WORKSPACE_TAG_SUFFIX_SETTING = 'dev_workspace_tag_suffix' export const WORKSPACE_FAIRNESS_ENABLED_SETTING = 'workspace_fairness_enabled' export const WORKSPACE_FAIRNESS_MAX_PERCENT_SETTING = 'workspace_fairness_max_percent' diff --git a/frontend/src/lib/devWorkspaceTags.ts b/frontend/src/lib/devWorkspaceTags.ts new file mode 100644 index 0000000000..60352576eb --- /dev/null +++ b/frontend/src/lib/devWorkspaceTags.ts @@ -0,0 +1,141 @@ +import { derived, get, writable } from 'svelte/store' +import { WorkerService } from '$lib/gen' + +/** Mirrors `DEFAULT_DEV_WORKSPACE_TAG_SUFFIX` in `windmill-common/src/worker.rs`. */ +export const DEFAULT_DEV_WORKSPACE_TAG_SUFFIX = '-dev' +const WM_FORK_PREFIX = 'wm-fork-' + +/** Mirrors `is_valid_dev_workspace_tag_suffix`: the suffix ends up in SQL literals and tag lists. */ +export const DEV_WORKSPACE_TAG_SUFFIX_PATTERN = /^[A-Za-z0-9_.-]{1,32}$/ + +export type DevWorkspaceIsolationState = { + enabled: boolean + suffix: string + /** Forks of a workspace with no dev workspace in its lineage run on their parent's workers. */ + skip_non_dev_forks: boolean +} + +/** `undefined` until loaded. */ +export const devWorkspaceIsolation = writable<DevWorkspaceIsolationState | undefined>(undefined) +/** The suffix new dev workspace and fork jobs get: `null` while isolation is off. */ +export const devWorkspaceTagSuffix = derived(devWorkspaceIsolation, (i) => + i === undefined ? undefined : i.enabled ? i.suffix : null +) +/** Whether forks with no dev workspace in their lineage run on their parent's workers. */ +export const devWorkspaceSkipNonDevForks = derived( + devWorkspaceIsolation, + (i) => i?.skip_non_dev_forks ?? false +) +/** The suffix worker groups serving dev workspaces listen with, isolation on or off. */ +export const devWorkspaceListenSuffix = derived( + devWorkspaceIsolation, + (i) => i?.suffix ?? DEFAULT_DEV_WORKSPACE_TAG_SUFFIX +) + +let inflight: Promise<void> | undefined +export function loadDevWorkspaceTagSuffix(force = false): Promise<void> { + if (!force && get(devWorkspaceIsolation) !== undefined) return Promise.resolve() + if (!force && inflight) return inflight + // Started inside the chain so any failure lands in the catch: callers on a job's error path + // await this and must not fail because the setting could not be read. + inflight = Promise.resolve() + .then(() => WorkerService.getDevWorkspaceIsolation()) + .then((i) => devWorkspaceIsolation.set(i)) + .catch(() => + devWorkspaceIsolation.set({ + enabled: false, + suffix: DEFAULT_DEV_WORKSPACE_TAG_SUFFIX, + skip_non_dev_forks: false + }) + ) + .finally(() => (inflight = undefined)) + return inflight +} + +/** Mirrors `with_dev_workspace_suffix`: idempotent, as an inherited tag already carries it. */ +export function withDevSuffix(tag: string, suffix: string): string { + return tag.endsWith(suffix) ? tag : `${tag}${suffix}` +} + +/** The suffix `tag` carries as a dev workspace job's tag, if isolation is on and it does. */ +export function devSuffixOf(tag: string | undefined): string | undefined { + const suffix = get(devWorkspaceTagSuffix) + return suffix && tag?.endsWith(suffix) ? suffix : undefined +} + +/** What to do about a dev workspace tag no worker serves, empty for any other tag. */ +export function devTagNoWorkerHint(tag: string): string { + const suffix = devSuffixOf(tag) + if (!suffix) return '' + return ( + ` "${tag}" ends with "${suffix}", the suffix of jobs of dev workspaces and forks: only worker ` + + `groups flagged as serving dev workspaces listen to it. Flag a worker group as serving dev ` + + `workspaces (Workers page) whose tags include "${tag.slice(0, -suffix.length)}".` + ) +} + +type LineageWorkspace = { + id: string + parent_workspace_id?: string | null + is_dev_workspace?: boolean + deleted?: boolean +} + +/** Whether a workspace has a parent, or is (or was) a fork. */ +export function isDevOrForkWorkspace(w: LineageWorkspace): boolean { + return !!w.parent_workspace_id || w.id.startsWith(WM_FORK_PREFIX) +} + +/** Mirrors `in_dev_lineage` in `windmill-queue/src/tags.rs`: a dev workspace on the ancestor chain, + * `w` included, an orphaned fork or an archived ancestor with a parent counting as one (archiving a + * dev workspace clears its flag). The server reads the whole chain; here an + * ancestor missing from `workspaces` (one the user is not a member of) also counts as one, so a + * hint errs toward the dev workers rather than claiming a job reaches the parent's. */ +function isInDevLineage(w: LineageWorkspace, workspaces: LineageWorkspace[]): boolean { + let current: LineageWorkspace | undefined = w + for (let depth = 0; current && depth <= 20; depth++) { + const parentId = current.parent_workspace_id + if (current.is_dev_workspace || (current.deleted && parentId)) return true + if (!parentId) return current.id.startsWith(WM_FORK_PREFIX) + current = workspaces.find((x) => x.id === parentId) + } + return true +} + +/** Whether a workspace's jobs run on dev workers while isolation is on. Mirrors + * `is_isolated_workspace` in `windmill-common/src/worker.rs`. */ +export function isIsolatedWorkspace( + w: LineageWorkspace, + workspaces: LineageWorkspace[], + skipNonDevForks: boolean +): boolean { + return isDevOrForkWorkspace(w) && (!skipNonDevForks || isInDevLineage(w, workspaces)) +} + +/** The same check for a workspace id, looked up in `workspaces` (pass the store's value so a + * reactive caller recomputes once the list loads). */ +export function isIsolatedWorkspaceId( + workspaceId: string | undefined, + workspaces: LineageWorkspace[], + skipNonDevForks: boolean +): boolean { + if (!workspaceId) return false + return isIsolatedWorkspace( + workspaces.find((w) => w.id === workspaceId) ?? { id: workspaceId }, + workspaces, + skipNonDevForks + ) +} + +/** Whether a new throwaway fork of `baseId` would run on dev workers while isolation is on. */ +export function isForkOfIsolated( + baseId: string, + workspaces: LineageWorkspace[], + skipNonDevForks: boolean +): boolean { + return isIsolatedWorkspace( + { id: `${WM_FORK_PREFIX}new`, parent_workspace_id: baseId, is_dev_workspace: false }, + workspaces, + skipNonDevForks + ) +} diff --git a/frontend/src/lib/draftAddRedirect.ts b/frontend/src/lib/draftAddRedirect.ts index 242893f782..2c027ac1da 100644 --- a/frontend/src/lib/draftAddRedirect.ts +++ b/frontend/src/lib/draftAddRedirect.ts @@ -1,5 +1,4 @@ import { redirect } from '@sveltejs/kit' -import { base } from '$app/paths' import { mintDraftPath } from '$lib/mintDraftPath' /** @@ -8,7 +7,7 @@ import { mintDraftPath } from '$lib/mintDraftPath' * * Mints a fresh `u/<username>/draft_<uuid>` path (via the shared `mintDraftPath`, * so the SDK builder wrappers stay in lockstep) and 307s to - * `{base}/{editPrefix}/<path>?new_draft=true&<existing-params>`. `new_draft=true` + * `/{editPrefix}/<path>?new_draft=true&<existing-params>`. `new_draft=true` * tells the edit route to seed an empty editor instead of 404-ing. The hash is * carried over too — fork / handler-template buttons encode a payload into it * that the edit route's `new_draft` branch consumes. @@ -23,6 +22,6 @@ export function makeDraftAddLoad(editPrefix: string) { // points at the PREVIOUS page, but every hash-payload producer arrives // as a full page load, so the hash is correct. const hash = typeof window !== 'undefined' ? window.location.hash : '' - redirect(307, `${base}/${editPrefix}/${path}?${params.toString()}${hash}`) + redirect(307, `/${editPrefix}/${path}?${params.toString()}${hash}`) } } diff --git a/frontend/src/lib/editRights.test.ts b/frontend/src/lib/editRights.test.ts new file mode 100644 index 0000000000..a6d36f693c --- /dev/null +++ b/frontend/src/lib/editRights.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it } from 'vitest' +import type { UserExt } from '$lib/stores' +import { canEditItem, roleCanAuthor, roleCanDraft } from './editRights' + +function user(overrides: Partial<UserExt>): UserExt { + return { + email: 'op@windmill.dev', + username: 'op', + name: 'op', + is_admin: false, + is_super_admin: false, + created_at: '', + groups: [], + pgroups: [], + folders: [], + folders_owners: [], + folders_read: [], + operator: true, + ...overrides + } as UserExt +} + +describe('edit rights', () => { + it('lets a builder operator author flows and nothing else', () => { + const builder = { builder_flows: true } + expect(roleCanAuthor('flow', user({}), builder)).toBe(true) + expect(roleCanAuthor('script', user({}), builder)).toBe(false) + expect(roleCanAuthor('flow', user({}), undefined)).toBe(false) + expect(roleCanDraft('raw_app', user({}), builder)).toBe(false) + expect(roleCanDraft('raw_app', user({}), { builder_apps: true })).toBe(true) + }) + + // drafts.rs admits an admin before its operator branch; the item handlers do not. + it('lets an admin who is also an operator save drafts, but not author code', () => { + const adminOperator = user({ is_admin: true }) + expect(roleCanDraft('script', adminOperator, undefined)).toBe(true) + expect(roleCanAuthor('script', adminOperator, undefined)).toBe(false) + }) + + // drafts.rs admits an operator's draft of a kind they could deploy, and no other. + it('lets an operator draft schedules and triggers until the right is withdrawn', () => { + expect(roleCanDraft('schedule', user({}), undefined)).toBe(true) + expect(roleCanDraft('trigger', user({}), undefined)).toBe(true) + expect(roleCanDraft('schedule', user({}), { manage_schedules: false })).toBe(false) + expect(roleCanDraft('trigger', user({}), { manage_triggers: false })).toBe(false) + }) + + it('lets an operator draft resources and variables, but not scripts', () => { + expect(roleCanDraft('resource', user({}), undefined)).toBe(true) + expect(roleCanDraft('variable', user({}), undefined)).toBe(true) + expect(roleCanDraft('script', user({}), undefined)).toBe(false) + }) + + // The role alone is not enough: a builder still cannot edit a flow in a folder they only read. + it('requires write access to the item on top of the role', () => { + const builder = { builder_flows: true } + expect(canEditItem('flow', 'f/demo/sum', {}, user({}), builder)).toBe(false) + expect(canEditItem('flow', 'u/op/sum', {}, user({}), builder)).toBe(true) + }) +}) diff --git a/frontend/src/lib/editRights.ts b/frontend/src/lib/editRights.ts new file mode 100644 index 0000000000..888b61e818 --- /dev/null +++ b/frontend/src/lib/editRights.ts @@ -0,0 +1,127 @@ +import type { OperatorSettings } from '$lib/gen' +import type { UserExt } from '$lib/stores' +import { canWrite } from '$lib/utils' + +/** + * The frontend's one copy of "may this user edit this item". The server decides — drafts.rs + * `require_can_write_path`, the item handlers' operator refusals, `gate_operator_writes`, and + * row-level security — and this mirrors it so a control the server would refuse is never + * offered. Check edits through `canEditItem` (or `useEditRights` in a component), never by + * pairing `canWrite` with an operator test of your own. + */ + +/** Kinds whose role half differs. Any other kind is code an operator never authors. */ +export type EditKind = + | 'script' + | 'flow' + | 'app' + | 'raw_app' + | 'agent' + | 'pipeline' + | 'schedule' + | 'trigger' + | 'resource' + | 'variable' + | 'group' + | (string & {}) + +type OperatorRights = + | Pick< + NonNullable<OperatorSettings>, + 'builder_flows' | 'builder_apps' | 'manage_schedules' | 'manage_triggers' + > + | null + | undefined + +/** + * Whether a user's role lets them author items of `kind` — create, edit, deploy or delete one — + * in a workspace with these `operator_settings`: the role half of every check against the item + * handlers. Saving a draft is `roleCanDraft`'s rule, and which items they may write is + * `canEditItem`'s other half. For an operator: + * - code (scripts, low-code apps, agents, pipelines): never; + * - flows and full-code apps: where the workspace grants `builder_flows` / `builder_apps` + * (`check_operator_can_build`); + * - schedules and triggers: unless the workspace set `manage_*` to false — a withdrawable + * right, so an unset key grants it (docs/operator-write-rights.md); + * - resources, variables and groups: always, their permissions alone decide. + */ +export function roleCanAuthor( + kind: EditKind, + user: Pick<UserExt, 'operator'> | undefined, + operatorSettings: OperatorRights +): boolean { + if (!user?.operator) return true + switch (kind) { + case 'flow': + case 'raw_app': + return builderGrants(kind, operatorSettings) + case 'schedule': + return operatorSettings?.manage_schedules !== false + case 'trigger': + return operatorSettings?.manage_triggers !== false + case 'resource': + case 'variable': + case 'group': + return true + default: + return false + } +} + +/** + * Whether the user may save drafts of `kind` — what every session editor and the chat's draft + * tools write. Mirrors drafts.rs `require_can_write_path`, which differs from the item handlers + * both ways: it admits an admin before its operator branch, and an operator drafts only the kinds + * they could deploy — resources and variables always, flows and full-code apps under their builder + * right, schedules and triggers under the manage rights. + */ +export function roleCanDraft( + kind: EditKind, + user: Pick<UserExt, 'operator' | 'is_admin' | 'is_super_admin'> | undefined, + operatorSettings: OperatorRights +): boolean { + if (user?.is_admin || user?.is_super_admin || !user?.operator) return true + switch (kind) { + case 'flow': + case 'raw_app': + return builderGrants(kind, operatorSettings) + case 'schedule': + case 'trigger': + return roleCanAuthor(kind, user, operatorSettings) + case 'resource': + case 'variable': + return true + default: + return false + } +} + +function builderGrants(kind: EditKind, operatorSettings: OperatorRights): boolean { + return ( + (kind === 'flow' && operatorSettings?.builder_flows === true) || + (kind === 'raw_app' && operatorSettings?.builder_apps === true) + ) +} + +/** `roleCanDraft` for the item at `path`, with its own permissions as in `canEditItem`. */ +export function canDraftItem( + kind: EditKind, + path: string, + extraPerms: Record<string, boolean> | undefined, + user: UserExt | undefined, + operatorSettings: OperatorRights +): boolean { + return roleCanDraft(kind, user, operatorSettings) && canWrite(path, extraPerms ?? {}, user) +} + +/** Whether `user` may edit the item at `path`: their role authors `kind`, and the item's own + * permissions (`canWrite`: ownership, folder write, `extra_perms`) let them write it. */ +export function canEditItem( + kind: EditKind, + path: string, + extraPerms: Record<string, boolean> | undefined, + user: UserExt | undefined, + operatorSettings: OperatorRights +): boolean { + return roleCanAuthor(kind, user, operatorSettings) && canWrite(path, extraPerms ?? {}, user) +} diff --git a/frontend/src/lib/githubApp.ts b/frontend/src/lib/githubApp.ts index 666734546e..0c19cd8de2 100644 --- a/frontend/src/lib/githubApp.ts +++ b/frontend/src/lib/githubApp.ts @@ -4,7 +4,6 @@ import { type GetGhesConfigResponse } from '$lib/gen' import { sendUserToast } from '$lib/toast' -import { base } from '$lib/base' export interface GitHubAppState { loadingGithubInstallations: boolean @@ -137,7 +136,7 @@ export async function loadGithubInstallations( const stateParam = encodeURIComponent( JSON.stringify({ workspace_id: currentWorkspace, - base_url: window.location.origin + base + base_url: window.location.origin }) ) diff --git a/frontend/src/lib/hubPaths.json b/frontend/src/lib/hubPaths.json index 2c46c48b2c..74c2d6f9f4 100644 --- a/frontend/src/lib/hubPaths.json +++ b/frontend/src/lib/hubPaths.json @@ -1,6 +1,6 @@ { "gitSyncTest": "hub/28950/git-repo-test-read-write-windmill", - "gitInitRepo": "hub/28993/git-sync-init-repository-windmill", + "gitInitRepo": "hub/29784/git-sync-init-repository-windmill", "slackErrorHandler": "hub/28794/workspace-or-schedule-error-handler-slack", "emailErrorHandler": "hub/19795/workspace-or-error-handler-email", "slackRecoveryHandler": "hub/28791/slack/schedule-recovery-handler-slack", diff --git a/frontend/src/lib/infer.ts b/frontend/src/lib/infer.ts index 2eb15f3c34..9e9cddeb00 100644 --- a/frontend/src/lib/infer.ts +++ b/frontend/src/lib/infer.ts @@ -301,7 +301,7 @@ export async function inferAnsibleExecutionMode(code: string): Promise<any> { } } -const SQL_LANGUAGES = [ +export const SQL_LANGUAGES = [ 'postgresql', 'mysql', 'bigquery', diff --git a/frontend/src/lib/instanceRoutes.ts b/frontend/src/lib/instanceRoutes.ts new file mode 100644 index 0000000000..7d57dc1b81 --- /dev/null +++ b/frontend/src/lib/instanceRoutes.ts @@ -0,0 +1,10 @@ +/** + * Pages a devops user can open without belonging to any workspace. Devops grants no workspace + * access, so such a page renders with `$workspaceStore` and `$userStore` unset and must hide + * whatever needs them (a workspace-scoped call or a link into a workspace) rather than break. + */ +const INSTANCE_ROUTES = ['/workers', '/service_logs'] + +export function isInstanceRoute(pathname: string): boolean { + return INSTANCE_ROUTES.some((r) => pathname === r || pathname.startsWith(r + '/')) +} diff --git a/frontend/src/lib/instanceUi.ts b/frontend/src/lib/instanceUi.ts index b9b87d139c..3a7bb1b99c 100644 --- a/frontend/src/lib/instanceUi.ts +++ b/frontend/src/lib/instanceUi.ts @@ -2,7 +2,8 @@ import { writable } from 'svelte/store' import type { GetInstanceUiResponse } from '$lib/gen' /** - * The last `/settings/instance_ui` response: the announcement banner and accent color. + * The last `/settings/instance_ui` response: the announcement banner, accent color + * and API base url. * `undefined` until one lands, and left as is when a fetch fails, so a transient error * never retracts an announcement still in force. Written only by `InstanceUiSync`. */ diff --git a/frontend/src/lib/logout.test.ts b/frontend/src/lib/logout.test.ts index 160bce9934..5bdc15bac3 100644 --- a/frontend/src/lib/logout.test.ts +++ b/frontend/src/lib/logout.test.ts @@ -12,9 +12,25 @@ import { clearUser } from './logout' describe('clearUser', () => { beforeEach(() => { sessionStorage.clear() + localStorage.clear() vi.clearAllMocks() }) + it('drops credential-bearing localStorage entries and keeps preferences', async () => { + const credentialKeys = ['oauth-callback', 'mcp-oauth-callback', 'test_dev_token'] + for (const key of credentialKeys) { + localStorage.setItem(key, 'a-token') + } + localStorage.setItem('dark-mode', 'true') + + await clearUser() + + for (const key of credentialKeys) { + expect(localStorage.getItem(key)).toBeNull() + } + expect(localStorage.getItem('dark-mode')).toBe('true') + }) + // Logging out while impersonating must not leave the impersonator's own token behind. it('drops the impersonation token backup', async () => { sessionStorage.setItem('pre_impersonation_token', 'a-token') diff --git a/frontend/src/lib/logout.ts b/frontend/src/lib/logout.ts index 58fce16fe3..b4782badd3 100644 --- a/frontend/src/lib/logout.ts +++ b/frontend/src/lib/logout.ts @@ -6,15 +6,19 @@ import { clearStores } from './storeUtils' // Note: logout and logoutWithRedirect have been moved to logoutKit.ts // as they depend on SvelteKit navigation -// The impersonation backup holds the impersonator's own auth token, so it must go on -// logout too, not only when impersonation is ended from the banner — otherwise a usable -// token stays readable for the lifetime of the tab. -function clearImpersonationFromStorage(): void { +// Every browser-storage entry that can hold a credential must go on logout. The impersonation +// backup is the impersonator's own auth token; `oauth-callback` and `mcp-oauth-callback` carry a +// connected account's token response when the OAuth popup had no opener to post it to; +// `test_dev_token` is the session token of the /test_dev pages. +function clearCredentialsFromStorage(): void { try { sessionStorage.removeItem('pre_impersonation_token') sessionStorage.removeItem('pre_impersonation_email') + localStorage.removeItem('oauth-callback') + localStorage.removeItem('mcp-oauth-callback') + localStorage.removeItem('test_dev_token') } catch (e) { - console.error('error interacting with session storage', e) + console.error('error interacting with browser storage', e) } } @@ -23,7 +27,7 @@ export async function clearUser() { noteSessionEmail(undefined) accountSetup.reset() clearStores() - clearImpersonationFromStorage() + clearCredentialsFromStorage() await UserService.logout() } catch (error) {} } diff --git a/frontend/src/lib/mcpEndpointTools.ts b/frontend/src/lib/mcpEndpointTools.ts index e0c29f4d7b..e53beeb53b 100644 --- a/frontend/src/lib/mcpEndpointTools.ts +++ b/frontend/src/lib/mcpEndpointTools.ts @@ -65,6 +65,46 @@ export const mcpEndpointTools: EndpointTool[] = [ queryFieldRenames: undefined, bodyFieldRenames: undefined }, + { + name: "getWorkspaceSettingsDocument", + description: "get the workspace settings document: The workspace's settings in the layout of the settings.yaml that `wmill sync` writes. Admin only", + instructions: "", + path: "/w/{workspace}/workspaces/settings_document", + method: "GET", + pathParamsSchema: undefined, + queryParamsSchema: undefined, + bodySchema: undefined, + queryFieldRenames: undefined, + bodyFieldRenames: undefined + }, + { + name: "applyWorkspaceSettingsDocument", + description: "apply a workspace settings document: Applies a settings document, each setting through the endpoint that owns it. Admin only", + instructions: "Send only the top-level keys to change, each whole as getWorkspaceSettingsDocument returns it: a key the document omits is left as it is, and a key set to null clears it. Keep `__SENSITIVE_AND_UNCHANGED__` for a secret you were not given. Call with dry_run true first, show the user the changes and apply only once they agree.", + path: "/w/{workspace}/workspaces/settings_document", + method: "POST", + pathParamsSchema: undefined, + queryParamsSchema: undefined, + bodySchema: { + "type": "object", + "properties": { + "document": { + "type": "object", + "description": "The settings to apply, in the layout of the document. A secret given as `__SENSITIVE_AND_UNCHANGED__` keeps its stored value; one prefixed with `$encrypted:` is decrypted with the workspace key." + }, + "dry_run": { + "description": "Only compute the changes, without applying them.", + "type": "boolean" + } + }, + "required": [ + "document" + ], + "minProperties": 1 +}, + queryFieldRenames: undefined, + bodyFieldRenames: undefined + }, { name: "listDataMetrics", description: "list declared measures and dimensions on DuckLake tables: Call this before writing any aggregate query over a DuckLake table. A declared measure is the canonical definition of that number, and reproducing it yourself will silently disagree with it (a `revenue` measure typically excludes refunds or test rows). Filter by `table` for one table's declarations, or by `path_prefix` (e.g. `f/analytics`) for everything declared under a folder; omit both to browse the whole catalog. Results are keyset-paged: a full page may mean more remain, so continue with the `cursor_*` params rather than assuming a measure does not exist. Use each returned `expr` verbatim, and when a measure has a `filter` write it as `expr FILTER (WHERE filter)` so measures with different predicates can share one GROUP BY. If a number you need has no declared measure, write your own aggregate as usual. Results are limited to declarations whose producing script the caller can read", @@ -568,6 +608,10 @@ export const mcpEndpointTools: EndpointTool[] = [ "include_draft_only": { "type": "boolean", "description": "When true, append per-user draft resources whose path has\nno deployed resource. Synthesized rows carry\n`draft_only: true`.\n" + }, + "starred_only": { + "type": "boolean", + "description": "Only the `ai_agent` resources the caller starred" } }, "required": [] @@ -1303,7 +1347,7 @@ export const mcpEndpointTools: EndpointTool[] = [ "items": { "type": "string" }, - "description": "Raw apps: author-declared scopes for the frontend SDK token. Takes effect only when `sandbox` is also true \u2014 an unsandboxed bundle runs with the viewer's own session, so no token is advertised or minted for it and this list stays inert. On a sandboxed app a non-empty list lets viewers mint (after consenting) a short-lived token carrying their own identity restricted to these scopes, handed to the app bundle so `windmill-client` calls run as the viewer. Must be a subset of the server's curated allowlist (jobs:run, jobs:read, users:read, resources:read, variables:read, flow_conversations:read, flow_conversations:write).\n" + "description": "Raw apps: author-declared scopes for the frontend SDK token. Takes effect only when `sandbox` is also true \u2014 an unsandboxed bundle runs with the viewer's own session, so no token is advertised or minted for it and this list stays inert. On a sandboxed app a non-empty list lets viewers mint (after consenting) a short-lived token carrying their own identity restricted to these scopes, handed to the app bundle so `windmill-client` calls run as the viewer. Must be a subset of the server's curated allowlist (jobs:run, jobs:read, users:read, resources:read, variables:read, flow_conversations:read, flow_conversations:write). Every such token can call whoami without consent, whether `users:read` is declared or not.\n" } } } @@ -1420,7 +1464,7 @@ export const mcpEndpointTools: EndpointTool[] = [ "items": { "type": "string" }, - "description": "Raw apps: author-declared scopes for the frontend SDK token. Takes effect only when `sandbox` is also true \u2014 an unsandboxed bundle runs with the viewer's own session, so no token is advertised or minted for it and this list stays inert. On a sandboxed app a non-empty list lets viewers mint (after consenting) a short-lived token carrying their own identity restricted to these scopes, handed to the app bundle so `windmill-client` calls run as the viewer. Must be a subset of the server's curated allowlist (jobs:run, jobs:read, users:read, resources:read, variables:read, flow_conversations:read, flow_conversations:write).\n" + "description": "Raw apps: author-declared scopes for the frontend SDK token. Takes effect only when `sandbox` is also true \u2014 an unsandboxed bundle runs with the viewer's own session, so no token is advertised or minted for it and this list stays inert. On a sandboxed app a non-empty list lets viewers mint (after consenting) a short-lived token carrying their own identity restricted to these scopes, handed to the app bundle so `windmill-client` calls run as the viewer. Must be a subset of the server's curated allowlist (jobs:run, jobs:read, users:read, resources:read, variables:read, flow_conversations:read, flow_conversations:write). Every such token can call whoami without consent, whether `users:read` is declared or not.\n" } } }, @@ -1809,7 +1853,7 @@ export const mcpEndpointTools: EndpointTool[] = [ }, "resolved": { "type": "boolean", - "description": "filter on whether a failure has been marked as handled. true keeps only resolved failures, false hides them" + "description": "filter on whether a failed or canceled run has been marked as handled. true keeps only resolved runs, false hides them" }, "is_flow_step": { "type": "boolean", diff --git a/frontend/src/lib/navigation.test.ts b/frontend/src/lib/navigation.test.ts index f499ddf1f7..d7f503b4eb 100644 --- a/frontend/src/lib/navigation.test.ts +++ b/frontend/src/lib/navigation.test.ts @@ -2,11 +2,10 @@ import { describe, it, expect, vi } from 'vitest' const goto = vi.hoisted(() => vi.fn(async (_path: string) => {})) vi.mock('$app/navigation', () => ({ goto: (path: string) => goto(path) })) -vi.mock('$app/paths', () => ({ base: '' })) import { buildFilterUrl, setQuery } from './navigation' -// Parse the (un-based) app path the builder returns against a dummy origin so we can +// Parse the app path the builder returns against a dummy origin so we can // assert on pathname / searchParams / hash without caring about ordering. function parse(appPath: string): URL { return new URL(appPath, 'http://x') diff --git a/frontend/src/lib/navigation.ts b/frontend/src/lib/navigation.ts index db8b9f3a80..164b9402c1 100644 --- a/frontend/src/lib/navigation.ts +++ b/frontend/src/lib/navigation.ts @@ -1,23 +1,14 @@ -import { goto as svelteGoto } from '$app/navigation' -import { base as svelteBase } from '$app/paths' +import { goto } from '$app/navigation' import { serializeParam } from '$lib/utils/serializeParam' -export function goto(path: string, options = {}) { - if (svelteBase == '' || path.startsWith('?')) { - return svelteGoto(path, options) - } else { - const fullPath = path.startsWith(svelteBase) ? path : `${svelteBase}${path}` - return svelteGoto(fullPath, options) - } -} +export { goto } /** * Build an in-app deep-link to `pathname` with query-param filters, encoded exactly * as the pages write them (via `serializeParam`) so `useUrlSyncedFilterInstance` * round-trips them back into filter state. Nullish/empty values are dropped; when * `validKeys` is provided, unknown keys are dropped too (structured output guarantees - * shape, not truth). Returns an un-prefixed app path — pass it to `goto`, which adds - * the SvelteKit base. + * shape, not truth). Returns an app path to pass to `goto`. */ export function buildFilterUrl( pathname: string, diff --git a/frontend/src/lib/operatorWriteRights.ts b/frontend/src/lib/operatorWriteRights.ts index 21a27d87f0..916e39dce6 100644 --- a/frontend/src/lib/operatorWriteRights.ts +++ b/frontend/src/lib/operatorWriteRights.ts @@ -1,48 +1,110 @@ -import { derived, type Readable } from 'svelte/store' -import { userWorkspaces, workspaceStore } from '$lib/stores' +import { derived, fromStore, get, readable, type Readable } from 'svelte/store' +import { userWorkspaces, usersWorkspaceStore, workspaceStore } from '$lib/stores' import { useOperatingWorkspace } from '$lib/components/operatingWorkspace.svelte' +import { useActingUser } from '$lib/actingUser.svelte' +import { canDraftItem, canEditItem, roleCanAuthor, roleCanDraft } from '$lib/editRights' + +/** + * The `editRights` rules (`roleCanAuthor` / `canEditItem` for the item handlers, `roleCanDraft` / + * `canDraftItem` for drafts) answered for the user acting in the operating workspace, + * with that workspace's `operator_settings` — or in `workspace`, for a component that is handed + * one rather than sitting under a host that declares it. Reads context and registers an effect: + * call during component initialisation. + */ +export function useEditRights(workspace?: () => string | undefined) { + const operating = fromStore(useOperatingWorkspace()) + const ws = workspace ?? (() => operating.current) + const user = useActingUser(ws) + const workspaces = fromStore(userWorkspaces) + const settings = () => workspaces.current.find((w) => w.id === ws())?.operator_settings + return { + roleCanAuthor: (kind: string) => roleCanAuthor(kind, user.current, settings()), + canEditItem: (kind: string, path: string, extraPerms: Record<string, boolean> | undefined) => + canEditItem(kind, path, extraPerms, user.current, settings()), + roleCanDraft: (kind: string) => roleCanDraft(kind, user.current, settings()), + canDraftItem: (kind: string, path: string, extraPerms: Record<string, boolean> | undefined) => + canDraftItem(kind, path, extraPerms, user.current, settings()), + /** This hook looks the user up on its own, so an editor that retries a failed lookup on + * its acting user (`forgetFailures`) must retry this one too, or it stays read-only. */ + forgetFailures: () => user.forgetFailures() + } +} /** * Why writes of this kind are locked in the operating workspace, or `undefined` when they are not — * the shape `title` and `disabled` both want. See `docs/operator-write-rights.md`. * - * Only `false` locks. A workspace that never configured the key and a non-operator (whose - * `operator_settings` is null) both hold the right, so `=== true` here would disable the controls - * for everyone. + * The role half of `roleCanAuthor`, phrased for the controls that explain it. `operator_settings` + * is non-null exactly for an operator (`isOperatorInWorkspace`), so it stands in for the user. */ -function writeLock(key: 'manage_schedules' | 'manage_triggers', noun: string) { +function writeLock(kind: 'schedule' | 'trigger', noun: string) { return derived([userWorkspaces, useOperatingWorkspace()], ([$userWorkspaces, $workspace]) => { const settings = $userWorkspaces.find((w) => w.id === $workspace)?.operator_settings // Worded as the server words its refusal of the same write. - return settings?.[key] === false - ? `Operators cannot manage ${noun} in this workspace` - : undefined + return roleCanAuthor(kind, { operator: settings != null }, settings) + ? undefined + : `Operators cannot manage ${noun} in this workspace` }) } /** Reads context: call during component initialisation. */ -export const useScheduleLock = () => writeLock('manage_schedules', 'schedules') +export const useScheduleLock = () => writeLock('schedule', 'schedules') /** Reads context: call during component initialisation. */ -export const useTriggerLock = () => writeLock('manage_triggers', 'triggers') +export const useTriggerLock = () => writeLock('trigger', 'triggers') /** * True when the user is an operator of `workspace` and it granted operators the right to compose - * flows out of runnables that are already deployed. They still author no code, and everywhere else - * `operator` keeps meaning read-only, so a gate on the operator role has to consult this before + * this kind out of runnables that are already deployed. They still author no code, and everywhere + * else `operator` keeps meaning read-only, so a gate on the operator role has to consult this before * refusing. `operator_settings` is null for a non-operator, so this is false for them. + * + * The two rights are granted independently: anything that authors one kind must gate on that + * kind, or a flows-only workspace offers app affordances the backend then refuses. */ -function builderFlows(workspace: Readable<string | undefined>): Readable<boolean> { +function builderRight( + key: 'builder_flows' | 'builder_apps', + workspace: Readable<string | undefined> +): Readable<boolean> { return derived( [userWorkspaces, workspace], ([$userWorkspaces, $workspace]) => - $userWorkspaces.find((w) => w.id === $workspace)?.operator_settings?.builder_flows === true + $userWorkspaces.find((w) => w.id === $workspace)?.operator_settings?.[key] === true + ) +} + +/** Either right, only for surfaces that are not per-kind, such as the create menu's visibility. */ +function anyBuilderRight(workspace: Readable<string | undefined>): Readable<boolean> { + return derived( + [builderRight('builder_flows', workspace), builderRight('builder_apps', workspace)], + ([flows, apps]) => flows || apps ) } /** Builder rights in the operating workspace. Reads context: call during component * initialisation. */ -export const useOperatorBuilderFlows = () => builderFlows(useOperatingWorkspace()) +export const useOperatorBuilderFlows = () => builderRight('builder_flows', useOperatingWorkspace()) +/** Reads context: call during component initialisation. */ +export const useOperatorBuilderApps = () => builderRight('builder_apps', useOperatingWorkspace()) +/** Reads context: call during component initialisation. */ +export const useOperatorBuilderRights = () => anyBuilderRight(useOperatingWorkspace()) /** Builder rights in the navigation workspace, for code outside any component: the legacy AI * chat is one instance for the whole app and acts on the workspace the nav is on. */ -export const navigationOperatorBuilderFlows = builderFlows(workspaceStore) +export const navigationOperatorBuilderFlows = builderRight('builder_flows', workspaceStore) +export const navigationOperatorBuilderApps = builderRight('builder_apps', workspaceStore) +export const navigationOperatorBuilderRights = anyBuilderRight(workspaceStore) + +/** The app builder right in a given workspace, read once: for code acting on an explicit + * workspace rather than the nav's, such as the global AI chat. */ +export const operatorBuilderAppsIn = (workspace: string | undefined) => + get(builderRight('builder_apps', readable(workspace))) + +/** Resolves once the workspace list has loaded. Every builder right reads false until then, so + * code that picks what a builder starts with on a fresh page load has to wait for it. */ +export async function workspaceListLoaded(): Promise<void> { + let unsubscribe = () => {} + await new Promise<void>((resolve) => { + unsubscribe = usersWorkspaceStore.subscribe((list) => list && resolve()) + }) + unsubscribe() +} diff --git a/frontend/src/lib/pipelinePaths.ts b/frontend/src/lib/pipelinePaths.ts index 534e691479..d12b162e06 100644 --- a/frontend/src/lib/pipelinePaths.ts +++ b/frontend/src/lib/pipelinePaths.ts @@ -9,6 +9,11 @@ export function pipelineBundlePath(folder: string): string { return `f/${folder}/${PIPELINE_DRAFT_KIND}` } +/** localStorage key of the editor's crash mirror of a folder's bundle. */ +export function pipelineLocalMirrorKey(folder: string): string { + return `pipeline-${folder}` +} + const BUNDLE_PATH_RE = new RegExp(`^f/([^/]+)/${PIPELINE_DRAFT_KIND}$`) /** The folder a pipeline bundle belongs to, or `undefined` if the path isn't one. */ diff --git a/frontend/src/lib/remoteDeploy.ts b/frontend/src/lib/remoteDeploy.ts index ad887504fb..dbac372f94 100644 --- a/frontend/src/lib/remoteDeploy.ts +++ b/frontend/src/lib/remoteDeploy.ts @@ -1,4 +1,3 @@ -import { base } from '$lib/base' import type { RemoteDeployConnection, RemoteDeployTarget } from '$lib/gen' import { randomSecret } from '$lib/utils/uuid' @@ -67,7 +66,7 @@ export function remoteDeployAuthorizeUrl( localStorage.setItem(PENDING_PREFIX + state, JSON.stringify(pending)) const params = new URLSearchParams({ workspace: target.workspace_id, - callback: `${window.location.origin}${base}${CALLBACK_PATH}`, + callback: `${window.location.origin}${CALLBACK_PATH}`, state }) return `${target.base_url}/user/remote_deploy_authorize?${params}` diff --git a/frontend/src/lib/script_helpers.ts b/frontend/src/lib/script_helpers.ts index 25ac64e607..b909aed43f 100644 --- a/frontend/src/lib/script_helpers.ts +++ b/frontend/src/lib/script_helpers.ts @@ -3,6 +3,7 @@ import { type Script } from './gen' import type { SupportedLanguage } from './common' import CLAUDE_SANDBOX_INIT_CODE from './templates/claude_sandbox.ts.template?raw' +import PI_SANDBOX_INIT_CODE from './templates/pi_sandbox.ts.template?raw' import WAC_PYTHON_INIT_CODE from './templates/wac_python.py.template?raw' import WAC_TYPESCRIPT_INIT_CODE from './templates/wac_typescript.ts.template?raw' import CI_TEST_BUN_INIT_CODE from './templates/ci_test_bun.ts.template?raw' @@ -1500,6 +1501,9 @@ export const INITIAL_CODE = { claudesandbox: { script: CLAUDE_SANDBOX_INIT_CODE }, + pisandbox: { + script: PI_SANDBOX_INIT_CODE + }, wac_python: { script: WAC_PYTHON_INIT_CODE }, @@ -1563,6 +1567,7 @@ export function initialCode( | 'powershell' | 'bunnative' | 'claudesandbox' + | 'pisandbox' | 'wac_python' | 'wac_typescript' | 'ci_test_bun' @@ -1670,6 +1675,8 @@ export function initialCode( } else if (language == 'bun' || language == 'bunnative') { if (subkind === 'claudesandbox') { return INITIAL_CODE.claudesandbox.script + } else if (subkind === 'pisandbox') { + return INITIAL_CODE.pisandbox.script } else if (kind == 'trigger') { return INITIAL_CODE.bun.trigger } else if (language == 'bunnative' || subkind === 'bunnative') { @@ -1711,6 +1718,7 @@ export function getResetCode( | 'powershell' | 'bunnative' | 'claudesandbox' + | 'pisandbox' | 'wac_python' | 'wac_typescript' | 'ci_test_bun' diff --git a/frontend/src/lib/scripts.ts b/frontend/src/lib/scripts.ts index 2d905d690a..eb0b3c48a5 100644 --- a/frontend/src/lib/scripts.ts +++ b/frontend/src/lib/scripts.ts @@ -1,5 +1,4 @@ import { get } from 'svelte/store' -import { base } from '$lib/base' import type { Schema, SupportedLanguage } from './common' import { FlowService, type Script, ScriptService, ScheduleService } from './gen' import { hubBaseUrlStore, workspaceStore } from './stores' @@ -136,7 +135,7 @@ export function scriptPathToHref(path: string, hubBaseUrl: string): string { if (path.startsWith('hub/')) { return hubBaseUrl + '/from_version/' + path.substring(4) } else { - return `${base}/scripts/get/${path}?workspace=${get(workspaceStore)}` + return `/scripts/get/${path}?workspace=${get(workspaceStore)}` } } @@ -146,7 +145,7 @@ export function flowPathToHref(path: string, hubBaseUrl: string = get(hubBaseUrl return hubFlowId ? `${hubBaseUrl}/flows/${hubFlowId}` : hubBaseUrl } - return `${base}/flows/get/${path}?workspace=${get(workspaceStore)}` + return `/flows/get/${path}?workspace=${get(workspaceStore)}` } const scriptLanguagesArray: [SupportedLanguage | 'docker' | 'bunnative', string][] = [ @@ -175,8 +174,8 @@ const scriptLanguagesArray: [SupportedLanguage | 'docker' | 'bunnative', string] ['ruby', 'Ruby'], ['rlang', 'R'], ['dbt', 'dbt'], - // This array's order is the picker order. Deno is de-emphasized ahead of - // deprecation, so it stays last. + // Not offered for new scripts (see `processLangs`); listed for the label of + // existing ones. ['deno', 'Deno'] // for related places search: ADD_NEW_LANG ] @@ -197,6 +196,12 @@ export function processInlineLangs(selected: string | undefined, langs: string[] } export function processLangs(selected: string | undefined, langs: string[]): string[] { + // Only a script already written in deno keeps the option, whether or not the + // workspace's saved order still carries it. + langs = langs.filter((lang) => lang !== 'deno') + if (selected === 'deno') { + langs = [...langs, 'deno'] + } if (selected === 'nativets') { return langs } else { @@ -243,6 +248,8 @@ export async function getScriptByPath( lock?: string created_at?: string hash?: string + on_behalf_of?: string + on_behalf_of_email?: string }> { if (path.startsWith('hub/')) { const { content, language, schema, lockfile } = await ScriptService.getHubScriptByPath({ path }) @@ -272,7 +279,9 @@ export async function getScriptByPath( concurrency_time_window_s: script.concurrency_time_window_s, lock: script.lock, hash: script.hash, - created_at: script.created_at + created_at: script.created_at, + on_behalf_of: script.on_behalf_of, + on_behalf_of_email: script.on_behalf_of_email } } } diff --git a/frontend/src/lib/templates/pi_sandbox.ts.template b/frontend/src/lib/templates/pi_sandbox.ts.template new file mode 100644 index 0000000000..ce99d549f7 --- /dev/null +++ b/frontend/src/lib/templates/pi_sandbox.ts.template @@ -0,0 +1,74 @@ +// sandbox +// volume: pi .pi + +import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context"; +import { createModels } from "@earendil-works/pi-ai/models"; +import { anthropicProvider } from "@earendil-works/pi-ai/providers/anthropic"; +import { AssistantEntry, createRegistry, Harness, watchEvents } from "@earendil-works/pi-durable"; +import { NodeExecutionEnv } from "@earendil-works/pi-durable/env/node"; +import { openNodeJsonlStorage } from "@earendil-works/pi-durable/storage/jsonl/node"; +import { CodingTools } from "@earendil-works/pi-durable/tools"; + +export async function main(anthropic: RT.Anthropic, instructions?: string) { + // Any pi-ai provider works: import it from "@earendil-works/pi-ai/providers/<name>", + // set the API key env var it reads, and name it in `model` below. + process.env.ANTHROPIC_API_KEY = anthropic.apiKey; + const models = createModels(); + models.setProvider(anthropicProvider()); + const model = { provider: "anthropic", modelId: "claude-opus-5-5" }; + + // read, write, edit and bash, running in this job's sandbox + const registry = createRegistry(); + registry.install(CodingTools); + + const context = BACKGROUND_CONTEXT; + + // The conversation is stored in the volume, so each run continues the previous one. + const harness = await Harness.open( + await openNodeJsonlStorage(".pi/session", context), + { models, registry, env: ({ cwd }) => new NodeExecutionEnv({ cwd: cwd ?? process.cwd() }) }, + context, + ); + + try { + const root = await harness.root(context); + await root.configure({ model, instructions: instructions ?? null }, context); + + const isResume = (await root.viewState(context)).value.entries.length > 0; + + // you can hardcode the prompt or pass it as input. + const prompt = !isResume ? + "What is the fastest OSS workflow engine?" : + "What did I ask you before?" + + const events = await watchEvents(harness, root.id, context); + events.start(async (batch) => { + for (const event of batch) { + if (event.type === "tool_execution_start") { + console.log(`${event.toolName} ${JSON.stringify(event.args)}`); + } + } + }); + + const submission = await root.submit({ type: "input", content: prompt }, context); + const settled = await submission.wait(context); + if (settled.status !== "done" || settled.type !== "input") { + throw new Error(`Pi did not answer: ${JSON.stringify(settled)}`); + } + + const answer = await root.commit((tx) => tx.entry(AssistantEntry, settled.answer), context); + const response = (answer?.model?.[0]?.content ?? []) + .filter((b: any) => b.type === "text") + .map((b: any) => b.text) + .join(""); + + return { + is_resume: isResume, + prompt, + response, + usage: (await harness.usage(context)).models, + }; + } finally { + await harness.close(context); + } +} diff --git a/frontend/src/lib/utils.test.ts b/frontend/src/lib/utils.test.ts index a37238f91c..07216d341f 100644 --- a/frontend/src/lib/utils.test.ts +++ b/frontend/src/lib/utils.test.ts @@ -13,17 +13,16 @@ import { apiErrorMessage } from './utils' -// Mirrors the backend invariant that only `status = 'failure'` rows can carry a -// resolution; loosening this to `!success` would offer the action on queued and -// canceled runs the API then silently skips. +// Mirrors the backend invariant that only failed or canceled rows can carry a resolution; +// offering the action anywhere else would send ids the API then silently skips. describe('isJobResolvable', () => { const completed = (o: object) => ({ type: 'CompletedJob', ...o }) as any - it('accepts a plain failure', () => { + it('accepts a plain failure and a cancellation', () => { expect(isJobResolvable(completed({ success: false, canceled: false }))).toBe(true) + expect(isJobResolvable(completed({ success: false, canceled: true }))).toBe(true) }) - it('rejects success, cancellation, flow steps and jobs still queued', () => { + it('rejects success, flow steps and jobs still queued', () => { expect(isJobResolvable(completed({ success: true, canceled: false }))).toBe(false) - expect(isJobResolvable(completed({ success: false, canceled: true }))).toBe(false) // a step resolved alone would show orange inside a flow that is still red expect( isJobResolvable(completed({ success: false, canceled: false, is_flow_step: true })) diff --git a/frontend/src/lib/utils.ts b/frontend/src/lib/utils.ts index 8540b964e8..13ae454c92 100644 --- a/frontend/src/lib/utils.ts +++ b/frontend/src/lib/utils.ts @@ -83,13 +83,13 @@ export function isJobReRunnable(j: Job): boolean { return (j.job_kind === 'script' || j.job_kind === 'flow') && j.parent_job === undefined } -// Only a top-level failure can carry a resolution: cancellations and skipped steps are not -// failures, and a flow step resolved on its own would render orange inside a flow whose status -// is still red. The resolve endpoint enforces the same three conditions. +// Only a top-level failed or canceled run can carry a resolution: successes and skipped steps +// have nothing to handle, and a flow step resolved on its own would render orange inside a flow +// whose status is still red. The resolve endpoint enforces the same conditions. // Runs obscured from another workspace stand in with `id: '-'`; they look like failures but // address nothing, and one reaching the endpoint fails the whole batch on UUID parsing. export function isJobResolvable(j: Job): j is CompletedJob { - return j.type === 'CompletedJob' && !j.success && !j.canceled && !j.is_flow_step && j.id !== '-' + return j.type === 'CompletedJob' && !j.success && !j.is_flow_step && j.id !== '-' } // Mirror the caps enforced by /jobs/completed/resolve, so the UI can chunk and validate diff --git a/frontend/src/lib/utils/describeCron.test.ts b/frontend/src/lib/utils/describeCron.test.ts new file mode 100644 index 0000000000..b24ac883b6 --- /dev/null +++ b/frontend/src/lib/utils/describeCron.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from 'vitest' +import { describeCron, describeSchedule } from './describeCron' + +describe('describeCron', () => { + it.each([ + ['*/30 * * * * *', 'Every 30 seconds'], + ['0 * * * * *', 'Every minute'], + ['0 */15 * * * *', 'Every 15 minutes'], + ['0 0 * * * *', 'Every hour'], + ['0 30 * * * *', 'Every hour at :30'], + ['0 0 */6 * * *', 'Every 6 hours'], + ['0 0 4 * * *', 'Every day at 4:00'], + // five fields are padded at the end, like the schedule editor saves them + ['0 0 12 * *', 'Every day at 12:00'], + ['0 30 9 * * 1-5', 'Every weekday at 9:30'], + ['0 0 9 * * MON', 'Every Monday at 9:00'], + ['0 0 18 * * 1,3,5', 'Every Monday, Wednesday and Friday at 18:00'], + ['0 0 8 1 * *', 'Every month on the 1st at 8:00'], + ['0 0 8 22 * *', 'Every month on the 22nd at 8:00'] + ])('%s → %s', (cron, text) => { + expect(describeCron(cron)).toBe(text) + }) + + it.each(['0 0 8 1 1 *', '15 0 4 * * *', '0 0 4-6 * * *', 'not a cron'])( + 'leaves %s to be shown as is', + (cron) => { + expect(describeCron(cron)).toBeUndefined() + } + ) +}) + +describe('describeSchedule', () => { + it('names the zone of a wall-clock time only', () => { + expect(describeSchedule('0 0 12 * * *', 'UTC')).toBe('Every day at 12:00 UTC') + expect(describeSchedule('0 0 * * * *', 'UTC')).toBe('Every hour') + }) +}) diff --git a/frontend/src/lib/utils/describeCron.ts b/frontend/src/lib/utils/describeCron.ts new file mode 100644 index 0000000000..96debb2589 --- /dev/null +++ b/frontend/src/lib/utils/describeCron.ts @@ -0,0 +1,128 @@ +import { formatCron } from '$lib/utils' + +const DAY_NAMES = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] +const DAY_ALIASES: Record<string, number> = { + SUN: 0, + MON: 1, + TUE: 2, + WED: 3, + THU: 4, + FRI: 5, + SAT: 6 +} + +const isNum = (f: string) => /^\d+$/.test(f) +const everyN = (f: string) => /^\*\/(\d+)$/.exec(f)?.[1] + +function time(hour: string, minute: string): string { + return `${Number(hour)}:${minute.padStart(2, '0')}` +} + +function ordinal(n: number): string { + const rest = n % 100 + if (rest >= 11 && rest <= 13) return `${n}th` + return `${n}${['th', 'st', 'nd', 'rd'][n % 10] ?? 'th'}` +} + +function dayNumber(token: string): number | undefined { + const t = token.toUpperCase() + if (t in DAY_ALIASES) return DAY_ALIASES[t] + if (!isNum(t)) return undefined + const n = Number(t) + return n >= 0 && n <= 7 ? n % 7 : undefined +} + +/** `1-5`, `MON-FRI`, `1,3,5`, `6` → sorted day numbers; undefined for anything else. */ +function days(field: string): number[] | undefined { + const out = new Set<number>() + for (const part of field.split(',')) { + const [from, to] = part.split('-') + const a = dayNumber(from) + if (a === undefined) return undefined + if (to === undefined) { + out.add(a) + continue + } + const b = dayNumber(to) + if (b === undefined || b < a) return undefined + for (let d = a; d <= b; d++) out.add(d) + } + return [...out].sort() +} + +function listDays(ds: number[]): string { + if (ds.join() === '1,2,3,4,5') return 'weekday' + if (ds.join() === '0,6') return 'weekend day' + const names = ds.map((d) => DAY_NAMES[d]) + return names.length === 1 + ? names[0] + : `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}` +} + +/** + * A plain-English reading of a Windmill cron expression — "Every hour", + * "Every day at 4:00", "Every Monday at 9:30" — or undefined when it is not one + * of the common shapes, so the caller can show the expression itself. + * + * Windmill crons have six fields, seconds first; a five-field entry is padded + * at the end the way the schedule editor saves it (`formatCron`). + */ +export function describeCron(cron: string): string | undefined { + const fields = formatCron(cron.trim()).split(/\s+/) + if (fields.length !== 6) return undefined + const [sec, min, hour, dom, month, dow] = fields + if (month !== '*') return undefined + + const anyDay = dom === '*' && (dow === '*' || dow === '?') + if (anyDay && min === '*' && hour === '*') { + if (sec === '*') return 'Every second' + const n = everyN(sec) + if (n) return `Every ${n} seconds` + } + if (sec !== '0') return undefined + + if (anyDay) { + if (hour === '*') { + if (min === '*') return 'Every minute' + const n = everyN(min) + if (n) return `Every ${n} minutes` + if (min === '0') return 'Every hour' + if (isNum(min)) return `Every hour at :${min.padStart(2, '0')}` + return undefined + } + const n = everyN(hour) + if (n && min === '0') return `Every ${n} hours` + if (isNum(hour) && isNum(min)) return `Every day at ${time(hour, min)}` + return undefined + } + + if (!isNum(hour) || !isNum(min)) return undefined + if (dom === '*') { + const ds = days(dow) + return ds ? `Every ${listDays(ds)} at ${time(hour, min)}` : undefined + } + if (isNum(dom) && (dow === '*' || dow === '?')) { + return `Every month on the ${ordinal(Number(dom))} at ${time(hour, min)}` + } + return undefined +} + +function shortZone(timezone: string): string { + try { + return ( + new Intl.DateTimeFormat('en-US', { timeZone: timezone, timeZoneName: 'short' }) + .formatToParts(new Date()) + .find((p) => p.type === 'timeZoneName')?.value ?? timezone + ) + } catch { + return timezone + } +} + +/** `describeCron` of a schedule, naming its zone whenever the text states a + * wall-clock time: "Every day at 12:00 UTC". */ +export function describeSchedule(cron: string, timezone?: string): string | undefined { + const text = describeCron(cron) + if (!text || !timezone || !/ at \d/.test(text)) return text + return `${text} ${shortZone(timezone)}` +} diff --git a/frontend/src/lib/utils/editInFork.ts b/frontend/src/lib/utils/editInFork.ts index 67eebcf7eb..d43c3644c9 100644 --- a/frontend/src/lib/utils/editInFork.ts +++ b/frontend/src/lib/utils/editInFork.ts @@ -1,4 +1,3 @@ -import { base } from '$lib/base' import { get } from 'svelte/store' import { userStore, @@ -75,13 +74,13 @@ export function canCreateFork(user: UserExt | undefined): boolean { function editPathFor(itemType: ItemType, itemPath: string): string { switch (itemType) { case 'script': - return `${base}/scripts/edit/${itemPath}` + return `/scripts/edit/${itemPath}` case 'flow': - return `${base}/flows/edit/${itemPath}` + return `/flows/edit/${itemPath}` case 'app': - return `${base}/apps/edit/${itemPath}` + return `/apps/edit/${itemPath}` case 'raw_app': - return `${base}/apps_raw/edit/${itemPath}` + return `/apps_raw/edit/${itemPath}` } } @@ -101,7 +100,7 @@ export function buildForkEditUrl( * workspace the page loads in, so a caller acting on another one names it. */ export function forkWorkspaceUrl(itemType: ItemType, itemPath: string, workspace?: string): string { const from = workspace ? `&workspace=${encodeURIComponent(workspace)}` : '' - return `${base}/user/fork_workspace?rd=${encodeURIComponent(editPathFor(itemType, itemPath))}${from}` + return `/user/fork_workspace?rd=${encodeURIComponent(editPathFor(itemType, itemPath))}${from}` } /** The item's editor in the dev workspace — the target `buildForkEditUrl` produces when a dev exists. */ diff --git a/frontend/src/lib/utils/previewOnBehalfOf.ts b/frontend/src/lib/utils/previewOnBehalfOf.ts new file mode 100644 index 0000000000..5ca4d9133c --- /dev/null +++ b/frontend/src/lib/utils/previewOnBehalfOf.ts @@ -0,0 +1,33 @@ +type ActingUser = + | { is_admin?: boolean; is_super_admin?: boolean; operator?: boolean; groups?: string[] } + | undefined + +/** + * The identity an editor preview should run as: the runnable's configured run-as identity, so a + * test behaves like the current deployed run. Only admins and `wm_deployers` may preview as + * someone else, and never operators (the server refuses everyone else); anyone else previews as + * themselves, which is also what their own save would record. + */ +export function previewOnBehalfOf( + user: ActingUser, + onBehalfOf: string | null | undefined, + onBehalfOfEmail?: string | null +): string | undefined { + const canPreserve = + !user?.operator && + (!!user?.is_admin || !!user?.is_super_admin || !!user?.groups?.includes('wm_deployers')) + if (!canPreserve) return undefined + return onBehalfOf || onBehalfOfEmail || undefined +} + +/** An app's runnables run as its policy identity unless it is in viewer mode, which runs them as + * whoever views it — the editor's user, in a preview. */ +export function appPreviewOnBehalfOf( + user: ActingUser, + policy: + | { execution_mode?: string; on_behalf_of?: string; on_behalf_of_email?: string } + | undefined +): string | undefined { + if (!policy || policy.execution_mode === 'viewer') return undefined + return previewOnBehalfOf(user, policy.on_behalf_of, policy.on_behalf_of_email) +} diff --git a/frontend/src/lib/utils/workspaceHierarchy.test.ts b/frontend/src/lib/utils/workspaceHierarchy.test.ts index 14e063cba8..6855effedc 100644 --- a/frontend/src/lib/utils/workspaceHierarchy.test.ts +++ b/frontend/src/lib/utils/workspaceHierarchy.test.ts @@ -1,10 +1,12 @@ import { describe, expect, it } from 'vitest' import { + buildWorkspaceHierarchy, devWorkspacesInChainAbove, findDefaultForkBase, findWorkspaceAncestors, - findWorkspaceRoot + findWorkspaceRoot, + workspaceSubtreeRows } from './workspaceHierarchy' import type { UserWorkspace } from '../stores' @@ -75,3 +77,39 @@ describe('devWorkspacesInChainAbove', () => { expect(devWorkspacesInChainAbove('prod', nestedFamily)).toEqual([]) }) }) + +describe('buildWorkspaceHierarchy', () => { + const mine = { created_by: 'me@x.com' } + const theirs = { created_by: 'other@x.com' } + const forks = [ + ws('wm-fork-a', 'prod', theirs), + ws('wm-fork-b', 'prod', theirs), + ws('wm-fork-c', 'prod', theirs), + ws('wm-fork-y', 'prod', mine), + ws('wm-fork-z', 'prod', mine) + ] + const ids = (rows: ReturnType<typeof buildWorkspaceHierarchy>) => + rows.map((h) => (h.separatorBefore ? '| ' : '') + h.workspace.id) + + it("puts the user's own forks after the dev workspace, divided from the rest", () => { + const all = [root, ws('devws', 'prod', { is_dev_workspace: true, ...mine }), ...forks] + expect(ids(workspaceSubtreeRows('prod', buildWorkspaceHierarchy(all, 'me@x.com')))).toEqual([ + 'devws', + 'wm-fork-y', + 'wm-fork-z', + '| wm-fork-a', + 'wm-fork-b', + 'wm-fork-c' + ]) + }) + + it('draws no divider in a short list', () => { + const all = [root, ...forks.slice(2)] + expect(ids(buildWorkspaceHierarchy(all, 'me@x.com'))).toEqual([ + 'prod', + 'wm-fork-y', + 'wm-fork-z', + 'wm-fork-c' + ]) + }) +}) diff --git a/frontend/src/lib/utils/workspaceHierarchy.ts b/frontend/src/lib/utils/workspaceHierarchy.ts index 55d54e1b2c..c19eae3c74 100644 --- a/frontend/src/lib/utils/workspaceHierarchy.ts +++ b/frontend/src/lib/utils/workspaceHierarchy.ts @@ -6,14 +6,26 @@ export interface WorkspaceHierarchyItem { isForked: boolean parentName?: string hasChildren: boolean + /** First fork after the caller's own forks among its siblings; pickers draw a divider above it. */ + separatorBefore?: boolean } +/** Sibling forks below this count stay undivided: a divider in a short list is noise. */ +const OWNED_FORKS_SEPARATOR_MIN_SIBLINGS = 5 + /** * Builds a hierarchical structure from a flat array of workspaces. * Supports unlimited nesting levels (fork of fork of fork...). * Returns a flattened array with hierarchy metadata for easy rendering. + * + * With `currentUserEmail`, the forks that user created lead each sibling group (after the dev + * workspace). When every admin and developer is added to new forks, a family lists everyone's forks, + * and without this the user's own are scattered alphabetically among them. */ -export function buildWorkspaceHierarchy(workspaces: UserWorkspace[]): WorkspaceHierarchyItem[] { +export function buildWorkspaceHierarchy( + workspaces: UserWorkspace[], + currentUserEmail?: string | null +): WorkspaceHierarchyItem[] { if (!workspaces || workspaces.length === 0) { return [] } @@ -45,12 +57,15 @@ export function buildWorkspaceHierarchy(workspaces: UserWorkspace[]): WorkspaceH const result: WorkspaceHierarchyItem[] = [] + const isOwnedFork = (w: UserWorkspace) => !w.is_dev_workspace && isForkOwner(w, currentUserEmail) + // Recursively build the hierarchy function addWorkspaceAndChildren( workspace: UserWorkspace, depth: number, isForked: boolean, - parentName?: string + parentName?: string, + separatorBefore?: boolean ) { // Add the current workspace result.push({ @@ -58,19 +73,31 @@ export function buildWorkspaceHierarchy(workspaces: UserWorkspace[]): WorkspaceH depth, isForked, parentName, - hasChildren: hasChildrenSet.has(workspace.id) + hasChildren: hasChildrenSet.has(workspace.id), + separatorBefore }) - // Add its children: the canonical dev workspace first, then throwaway forks by name. - const children = childrenMap.get(workspace.id) || [] - children - .sort((a, b) => { - if (!!a.is_dev_workspace !== !!b.is_dev_workspace) return a.is_dev_workspace ? -1 : 1 - return a.name.localeCompare(b.name) - }) - .forEach((child) => { - addWorkspaceAndChildren(child, depth + 1, true, workspace.name) - }) + // Add its children: the canonical dev workspace first, then the user's own forks, then the + // other forks, each by name. + const children = (childrenMap.get(workspace.id) || []).sort((a, b) => { + if (!!a.is_dev_workspace !== !!b.is_dev_workspace) return a.is_dev_workspace ? -1 : 1 + if (isOwnedFork(a) !== isOwnedFork(b)) return isOwnedFork(a) ? -1 : 1 + return a.name.localeCompare(b.name) + }) + const forkCount = children.filter((c) => !c.is_dev_workspace).length + const firstOtherFork = + forkCount >= OWNED_FORKS_SEPARATOR_MIN_SIBLINGS && children.some(isOwnedFork) + ? children.find((c) => !c.is_dev_workspace && !isOwnedFork(c)) + : undefined + children.forEach((child) => { + addWorkspaceAndChildren( + child, + depth + 1, + true, + workspace.name, + child === firstOtherFork || undefined + ) + }) } // Process root workspaces (sorted by name for consistency) @@ -89,6 +116,21 @@ export function buildWorkspaceHierarchy(workspaces: UserWorkspace[]): WorkspaceH return result } +/** + * The hierarchy rows below `rootId` (the root itself excluded), in the order and with the depths + * `buildWorkspaceHierarchy` gives them. + */ +export function workspaceSubtreeRows( + rootId: string, + hierarchy: WorkspaceHierarchyItem[] +): WorkspaceHierarchyItem[] { + const at = hierarchy.findIndex((h) => h.workspace.id === rootId) + if (at < 0) return [] + const rootDepth = hierarchy[at].depth + const end = hierarchy.findIndex((h, i) => i > at && h.depth <= rootDepth) + return hierarchy.slice(at + 1, end < 0 ? undefined : end) +} + /** * Helper function to get the indentation padding based on depth. * Each level adds 24px of left padding. diff --git a/frontend/src/lib/utils_deployable.ts b/frontend/src/lib/utils_deployable.ts index 63ea88adcb..e3f7fa83ed 100644 --- a/frontend/src/lib/utils_deployable.ts +++ b/frontend/src/lib/utils_deployable.ts @@ -16,7 +16,7 @@ import { type WorkspaceDeployUISettings } from './gen' import type { TriggerKind } from './components/triggers' -import { base } from './base' +import { apiBaseUrl } from './apiBaseUrl.svelte' type DeployUIType = 'script' | 'flow' | 'app' | 'resource' | 'variable' | 'secret' | 'trigger' @@ -250,9 +250,7 @@ export async function getTriggersDeployData( ...gcpTrigger, delivery_config: gcpTrigger.delivery_config ?? undefined, base_endpoint: - gcpTrigger.delivery_type === 'push' - ? (targetBaseUrl ?? `${window.location.origin}${base}`) - : undefined, + gcpTrigger.delivery_type === 'push' ? (targetBaseUrl ?? apiBaseUrl()) : undefined, permissioned_as: onBehalfOf, preserve_permissioned_as: preservePermissionedAs } @@ -320,7 +318,7 @@ export async function getTriggersDeployData( base_endpoint: azureTrigger.azure_mode === 'namespace_pull' ? undefined - : (targetBaseUrl ?? `${window.location.origin}${base}`), + : (targetBaseUrl ?? apiBaseUrl()), permissioned_as: onBehalfOf, preserve_permissioned_as: preservePermissionedAs }, diff --git a/frontend/src/lib/utils_draft_deploy.test.ts b/frontend/src/lib/utils_draft_deploy.test.ts index 5f503989c8..c141af3a3b 100644 --- a/frontend/src/lib/utils_draft_deploy.test.ts +++ b/frontend/src/lib/utils_draft_deploy.test.ts @@ -122,6 +122,83 @@ describe('deployDraft preserves on_behalf_of', () => { }) ) }) + + it('agent: claims the deployed identity, which its draft never carries', async () => { + vi.mocked(ResourceService.getResource).mockResolvedValueOnce({ + path: 'f/support/triage_agent', + resource_type: 'ai_agent', + value: { system_prompt: 'deployed', on_behalf_of: 'u/alice' }, + draft: { path: 'f/support/triage_agent', args: { system_prompt: 'drafted' } } + } as any) + + expect(await deployDraft('resource', 'f/support/triage_agent', 'ws')).toEqual({ success: true }) + expect(ResourceService.updateResource).toHaveBeenCalledWith( + expect.objectContaining({ + requestBody: expect.objectContaining({ + value: { system_prompt: 'drafted', on_behalf_of: 'u/alice' }, + preserve_on_behalf_of: true + }) + }) + ) + }) +}) + +// The backend skips the dependency job when `lock` is set, so a draft that inherited the +// deployed lock would deploy new content against the old lockfile. +describe('deployDraft: script lock', () => { + beforeEach(() => vi.clearAllMocks()) + + it('never sends the draft lock, so the backend relocks', async () => { + vi.mocked(ScriptService.getScriptByPath).mockResolvedValueOnce({ + hash: 'v1', + draft: { + path: 'f/admin/fetch', + content: 'import requests', + lock: 'certifi==2024.1.1', + lock_error_logs: 'old error' + } + } as any) + + await deployDraft('script', 'f/admin/fetch', 'ws') + const body = vi.mocked(ScriptService.createScript).mock.calls[0][0].requestBody + expect(body).not.toHaveProperty('lock') + expect(body).not.toHaveProperty('lock_error_logs') + }) + + it('flow: drops the lock of a step whose code differs from the deployed one only', async () => { + const step = (id: string, content: string) => ({ + id, + value: { type: 'rawscript', language: 'python3', content, lock: 'requests==2.0' } + }) + vi.mocked(FlowService.getFlowByPath).mockResolvedValueOnce({ + value: { modules: [step('edited', 'import requests'), step('kept', 'import requests')] }, + draft: { + path: 'f/admin/flow', + value: { modules: [step('edited', 'import yaml'), step('kept', 'import requests')] } + } + } as any) + + await deployDraft('flow', 'f/admin/flow', 'ws') + const [edited, kept] = vi.mocked(FlowService.updateFlow).mock.calls[0][0].requestBody.value + .modules as any[] + expect(edited.value).not.toHaveProperty('lock') + expect(kept.value.lock).toBe('requests==2.0') + }) + + // A never-deployed flow is often a copy or an import, whose locks match its code. + it('flow: keeps every lock when nothing is deployed to compare against', async () => { + const step = { id: 'copied', value: { type: 'rawscript', content: 'x', lock: 'requests==2.0' } } + vi.mocked(FlowService.getFlowByPath).mockResolvedValueOnce({ + no_deployed: true, + value: { modules: [step] }, + draft: { path: 'f/admin/copy', value: { modules: [step] } } + } as any) + + await deployDraft('flow', 'f/admin/copy', 'ws', { draftOnly: true }) + const [copied] = vi.mocked(FlowService.createFlow).mock.calls[0][0].requestBody.value + .modules as any[] + expect(copied.value.lock).toBe('requests==2.0') + }) }) // The resource branch reads the item again when the deploy lands, and falls back to the deployed diff --git a/frontend/src/lib/utils_draft_deploy.ts b/frontend/src/lib/utils_draft_deploy.ts index df04bb383a..96b83239b7 100644 --- a/frontend/src/lib/utils_draft_deploy.ts +++ b/frontend/src/lib/utils_draft_deploy.ts @@ -46,6 +46,7 @@ import { setLocalDraftHint } from '$lib/localDraftHints.svelte' import { userStore } from '$lib/stores' import { deployTriggers, type Trigger } from '$lib/components/triggers/utils' import { saveScheduleFromCfg } from '$lib/components/flows/scheduleUtils' +import { dropStaleStepLocks } from '$lib/components/flows/staleStepLocks' import { saveHttpRouteFromCfg } from '$lib/components/triggers/http/utils' import { saveWebsocketTriggerFromCfg } from '$lib/components/triggers/websocket/utils' import { savePostgresTriggerFromCfg } from '$lib/components/triggers/postgres/utils' @@ -233,8 +234,14 @@ function canonicalizeDraftDiffValue(kind: DraftKind, raw: any, isDraft: boolean) if (kind === 'resource') { // draft: { args, description, resource_type, labels, wsSpecific } // deployed row: { value, description, resource_type, labels, ws_specific } + // An agent's identity is in its deployed value and never in a draft, which is not an edit. + let value = (isDraft ? raw.args : raw.value) ?? {} + if (raw.resource_type === 'ai_agent') { + const { on_behalf_of: _, ...rest } = value + value = rest + } return { - value: (isDraft ? raw.args : raw.value) ?? {}, + value, description: raw.description ?? '', resource_type: raw.resource_type ?? undefined, labels: raw.labels ?? undefined, @@ -469,7 +476,15 @@ export async function deployDraft( const r = (await ScriptService.getScriptByPath({ workspace, path, getDraft: true })) as any const d = r.draft ?? r // Drop editor-only / server-managed keys; deploy as a real (non-draft) version. - const { draft_triggers: draftTriggers, draft_only: _o, ...rest } = d + // A draft seeded from the deployed script carries its `lock`, and the backend skips + // the dependency job whenever `lock` is set, so the new content would keep the old lock. + const { + draft_triggers: draftTriggers, + draft_only: _o, + lock: _lock, + lock_error_logs: _lockErrorLogs, + ...rest + } = d const scriptPath = d.path ?? path // Deploy at the draft's path so a rename in the draft is honored (same as // the editor: createScript at the new path with parent_hash links lineage). @@ -490,6 +505,9 @@ export async function deployDraft( } else if (kind === 'flow') { const r = (await FlowService.getFlowByPath({ workspace, path, getDraft: true })) as any const d = r.draft ?? r + const value = d.value ? structuredClone(d.value) : d.value + // With nothing deployed the server fills `r.value` from the draft itself. + if (value) dropStaleStepLocks(value, draftOnly || r.no_deployed ? undefined : r.value) const requestBody = { // Deploy at the draft's intended path: flow/app/raw-app drafts keep the // user-typed path in `draft_path` (a never-deployed item is parked at a @@ -498,7 +516,7 @@ export async function deployDraft( path: d.draft_path ?? d.path ?? path, summary: d.summary ?? '', description: d.description ?? '', - value: d.value, + value, schema: d.schema, tag: d.tag, dedicated_worker: d.dedicated_worker, @@ -538,14 +556,20 @@ export async function deployDraft( // no draft. `draft_path` and `summary` are draft-only fields mirrored onto // the App value (the editor drops them on deploy), so strip them from the // value and apply them as the deploy path / summary column. + // `parent_version` is the draft's stale-check base, never deployed. const draft = r.draft as Record<string, any> | undefined - const { draft_path: draftPath, summary: draftSummary, ...appValue } = draft ?? r.value ?? {} + const { + draft_path: draftPath, + summary: draftSummary, + parent_version: _pv, + ...appValue + } = draft ?? r.value ?? {} // Policy isn't carried in the app draft, so it comes from the deployed app // (or a default). custom_path requires admin on update; non-admins send // undefined so the backend preserves the existing route. The draft has no // custom_path, so admins fall back to the deployed route (`''` when none). const isAdmin = !!(get(userStore)?.is_admin || get(userStore)?.is_super_admin) - const policy = r.policy ?? { execution_mode: 'publisher' } + const policy = r.policy ?? { execution_mode: 'publisher', sandbox: true } const requestBody = { value: appValue, summary: draftSummary ?? r.summary ?? '', @@ -640,12 +664,18 @@ export async function deployDraft( } }) } else { + // As for an app: an agent draft carries no identity, so the deployed one is kept (the + // backend resets it to the deploying user without the flag, gated by + // can_preserve_on_behalf_of). + const agentObo = + deployed.resource_type === 'ai_agent' ? deployed.value?.on_behalf_of : undefined await ResourceService.updateResource({ workspace, path, requestBody: { path: d.path ?? path, - value: d.args ?? {}, + value: agentObo ? { ...(d.args ?? {}), on_behalf_of: agentObo } : (d.args ?? {}), + preserve_on_behalf_of: agentObo ? true : undefined, description: d.description ?? '', labels: d.labels, ws_specific: d.wsSpecific diff --git a/frontend/src/lib/utils_workspace_deploy.ts b/frontend/src/lib/utils_workspace_deploy.ts index ba1f293678..91820b581e 100644 --- a/frontend/src/lib/utils_workspace_deploy.ts +++ b/frontend/src/lib/utils_workspace_deploy.ts @@ -196,6 +196,11 @@ export type DeployConflict = { hit: boolean } * A group kept as the target identity travels as its synthetic `group-*@windmill.dev` * address, which an admin-created account holding it would win on the backend: known and * accepted, see `users::permissioned_as_from_email`. + * + * An agent carries its principal inside its resource value, and is handed the chosen one as a + * principal, as a trigger is. Every read here drops the source's, so a diff never shows it and + * the published `deployItem` copies none; the write then stamps the chosen one, or none, which + * leaves the backend to make it the deployer's. */ function makeProvider( onBehalfOfPrincipal?: string, @@ -224,6 +229,17 @@ function makeProvider( } } : app + const agents = new Set<string>() + const withAgentIdentity = <T extends Record<string, any>>(requestBody: T, path: string): T => + agents.has(path) && requestBody.value && typeof requestBody.value === 'object' + ? { + ...requestBody, + value: onBehalfOf + ? { ...requestBody.value, on_behalf_of: onBehalfOf } + : requestBody.value, + preserve_on_behalf_of: onBehalfOf !== undefined + } + : requestBody const refuseUpdate = (): never => { if (conflict) conflict.hit = true throw new Error('item already exists in the target workspace') @@ -290,11 +306,23 @@ function makeProvider( updateVariable: (p) => VariableService.updateVariable({ ...p, requestBody: withLabels(p.requestBody) }), deleteVariable: (p) => VariableService.deleteVariable(p), - getResource: (p) => ResourceService.getResource(p).then(readLabels), + getResource: async (p) => { + const resource = readLabels(await ResourceService.getResource(p)) + if (resource.resource_type !== 'ai_agent' || !resource.value) return resource + agents.add(p.path) + const { on_behalf_of: _, ...value } = resource.value as Record<string, any> + return { ...resource, value } + }, createResource: (p) => - ResourceService.createResource({ ...p, requestBody: withLabels(p.requestBody) }), + ResourceService.createResource({ + ...p, + requestBody: withAgentIdentity(withLabels(p.requestBody), p.requestBody.path) + }), updateResource: (p) => - ResourceService.updateResource({ ...p, requestBody: withLabels(p.requestBody) }), + ResourceService.updateResource({ + ...p, + requestBody: withAgentIdentity(withLabels(p.requestBody), p.path) + }), deleteResource: (p) => ResourceService.deleteResource(p), getResourceType: (p) => ResourceService.getResourceType(p), createResourceType: (p) => ResourceService.createResourceType(p), @@ -314,7 +342,7 @@ function makeProvider( existsTriggerByKind: (kind, p) => triggerServiceFor(kind).exists(p), getTriggerForDeploy: async (kind, p) => { // Reuses the existing per-kind transform map (e.g. GCP wipes - // subscription_id and computes base_endpoint from window.location). + // subscription_id and computes base_endpoint for this instance). // Operational-state strip is applied by the shared `deployItem` // after this returns. const { data } = await getTriggersDeployData( @@ -591,6 +619,17 @@ export async function getOnBehalfOf( return undefined } } + if (kind === 'resource') { + // Only an agent runs as anyone, and like a trigger it records the principal. + try { + const resource = await ResourceService.getResource({ workspace, path }) + return resource.resource_type === 'ai_agent' + ? (resource.value as { on_behalf_of?: string } | undefined)?.on_behalf_of + : undefined + } catch { + return undefined + } + } return sharedGetOnBehalfOf(makeProvider(), kind as DeployKind, path, workspace) } @@ -779,7 +818,8 @@ const KIND_GATED_BY_DEPLOY_RULES: Record<Kind, boolean> = { email_trigger: false, datatable_migration: false, trigger: false, - data_pipeline: false + // Deploying a pipeline deploys its scripts. + data_pipeline: true } // Every gated kind is spelled identically in `Kind` and `UserDraftItemKind`, so one lookup serves diff --git a/frontend/src/lib/workspaceCreation.ts b/frontend/src/lib/workspaceCreation.ts index 34c1644462..0a31d66a96 100644 --- a/frontend/src/lib/workspaceCreation.ts +++ b/frontend/src/lib/workspaceCreation.ts @@ -13,7 +13,6 @@ import { SettingService, UserService, WorkspaceService } from '$lib/gen' import { usersWorkspaceStore } from '$lib/stores' import { switchWorkspace } from '$lib/storeUtils' import { isCloudHosted } from '$lib/cloud' -import { base } from '$lib/base' import { WORKSPACE_NAME_MAX_LENGTH } from '$lib/utils/workspaceId' /** @@ -30,7 +29,7 @@ import { WORKSPACE_NAME_MAX_LENGTH } from '$lib/utils/workspaceId' export async function canCreateWorkspace(isSuperadmin: boolean): Promise<boolean> { if (isSuperadmin || isCloudHosted()) return true try { - const r = await fetch(base + '/api/workspaces/create_workspace_require_superadmin') + const r = await fetch('/api/workspaces/create_workspace_require_superadmin') if ((await r.text()) != 'true') return true return !!(await UserService.globalWhoami()).super_admin } catch { diff --git a/frontend/src/routes/(root)/(logged)/+layout.svelte b/frontend/src/routes/(root)/(logged)/+layout.svelte index 2403299e71..3fe47a74fc 100644 --- a/frontend/src/routes/(root)/(logged)/+layout.svelte +++ b/frontend/src/routes/(root)/(logged)/+layout.svelte @@ -7,6 +7,7 @@ AssetService, FlowService, OpenAPI, + ResourceService, ScriptService, SettingService, UserService, @@ -78,14 +79,18 @@ Home, Play, Search, - WandSparkles + WandSparkles, + ArrowLeft } from 'lucide-svelte' + import { Button } from '$lib/components/common' + import { isInstanceRoute } from '$lib/instanceRoutes' import { getUserExt } from '$lib/user' import { confirmPendingLoginMethod } from '$lib/lastLoginMethod' import { deepEqual } from 'fast-equals' import { twMerge } from 'tailwind-merge' import { navDetached } from '$lib/components/sidebar/navDetached.svelte' import { navHandleSlot } from '$lib/components/sidebar/navHandlePlacement.svelte' + import { overlayStack } from '$lib/components/common/overlayHost.svelte' import PageHeaderBar from '$lib/components/PageHeaderBar.svelte' import { BAR_HEIGHT_PX, pageHeader } from '$lib/components/pageHeaderRegistry.svelte' import { sidebarPageAllowed } from '$lib/components/sidebar/operatorRoutes' @@ -102,18 +107,17 @@ import InstanceUiSync from '$lib/components/InstanceUiSync.svelte' import { onDestroy, setContext, untrack } from 'svelte' import { cubicOut } from 'svelte/easing' - import { base } from '$app/paths' import { Menubar, Tooltip } from '$lib/components/meltComponents' import { aiChatManager } from '$lib/components/copilot/chat/AIChatManager.svelte' import AiChatLayout from '$lib/components/copilot/chat/AiChatLayout.svelte' import SessionPicker from '$lib/components/sessions/SessionPicker.svelte' import SessionModeSwitch from '$lib/components/sessions/SessionModeSwitch.svelte' - import { isGlobalAiEnabled } from '$lib/components/copilot/chat/global/gate' + import { isGlobalAiEnabled, sessionsAllowedFor } from '$lib/components/copilot/chat/global/gate' import { copilotInfo } from '$lib/aiStore' import { - isPageItemListPath, + isPreviewListPath, parsePreviewItemRoute, - stripBase + barePath } from '$lib/components/sessions/previewPaths' import { rememberNavRoute } from '$lib/components/sessions/sessionSwitch.svelte' import { sessionState } from '$lib/components/sessions/sessionState.svelte' @@ -300,11 +304,10 @@ // Session mode is route-derived: the rail shows the sessions sidebar on the // /sessions page and the workspace navigation everywhere else. The switch // (SessionModeSwitch) just navigates in and out of that route. - // The route decides, except for an operator: /sessions refuses them, so handing their - // sidebar over to a session list would offer what the page behind it is declining. - let sessionMode = $derived( - page.url.pathname.startsWith(base + '/sessions') && !$userStore?.operator - ) + // An operator without the opt-in (`gate.ts`) is refused by /sessions, so their sidebar is not + // handed over to a session list the page behind it declines, and they keep the docked chat. + const sessionsAllowed = $derived(sessionsAllowedFor($userStore?.operator)) + let sessionMode = $derived(page.url.pathname.startsWith('/sessions') && sessionsAllowed) // Session mode points the bottom settings entry at the open session's own // workspace. An unsent draft hasn't committed one yet, so it falls back to // the family root. @@ -326,12 +329,10 @@ // A workspace that hid the assistant (`ai_config.copilot_disabled`) loses both entry // points: the Workspace ⇄ Sessions switch and the legacy Ask-AI button. const sessionsSwitchShown = $derived( - globalAiEnabled && !$copilotInfo.workspaceDisabled && !$userStore?.operator + globalAiEnabled && sessionsAllowed && !$copilotInfo.workspaceDisabled ) - // The legacy pane's entry point. An operator keeps that pane whatever the beta gate says - // (`disableAi` above), so the sidebar must still offer them a way into it. const askAiShown = $derived( - (!globalAiEnabled || $userStore?.operator) && !$copilotInfo.workspaceDisabled + (!globalAiEnabled || !sessionsAllowed) && !$copilotInfo.workspaceDisabled ) if (page.status == 404) { @@ -471,7 +472,7 @@ } // A list page mounts in process too, where its rows open as tabs of their own. const listUrl = navigation.to?.url - if (listUrl && isPageItemListPath(stripBase(listUrl.pathname))) { + if (listUrl && isPreviewListPath(barePath(listUrl.pathname))) { navigation.cancel() const u = new URL(listUrl.href) u.searchParams.delete('nomenubar') @@ -518,8 +519,11 @@ function pointerInMenu(): boolean { return !!document.querySelector('[role="menu"]:hover') } + // A click on the handle pins the card: it then outlives the pointer leaving. Only meaningful + // while open — every open from closed starts unpinned. + let menuPinned = $state(false) const { debounced: schedulePeekClose, clearDebounce: cancelPeekClose } = debounce(() => { - if (!peeksOnHover) return + if (!peeksOnHover || menuPinned) return if (pointerInMenu()) { schedulePeekClose() return @@ -532,10 +536,56 @@ const floatBand = $derived(pageHeader.content?.barRightInset != null) // The handle and the edge band both open the card this layout owns. - navHandleSlot.setOpener(() => (menuOpen = true), { - schedule: schedulePeekClose, - cancel: cancelPeekClose - }) + navHandleSlot.setOpener( + () => { + if (!menuOpen) menuPinned = false + menuOpen = true + }, + { schedule: schedulePeekClose, cancel: cancelPeekClose }, + { + isOpen: () => menuOpen, + isPinned: () => menuPinned, + pin: () => (menuPinned = true), + close: () => (menuOpen = false) + } + ) + + // The open card is dismissed by any press on the page, and that press still reaches its target: + // a layer that caught it would cost every dismissal a second click. Only presses inside the page + // column count — the card itself and the menus it portals to `body` sit outside it — and the + // handle toggles the card itself. Capture phase, so a target that stops propagation still closes it. + let pageColumn: HTMLElement | undefined = $state() + function closeCardOnPagePress(e: PointerEvent) { + if (!menuOpen || !useDrawer) return + const target = e.target + if (!(target instanceof Element) || !pageColumn?.contains(target)) return + if (target.closest('[data-nav-handle]')) return + menuOpen = false + } + // A press inside an iframe (a session's preview) never reaches this window; focus moving into one does. + function closeCardOnFrameFocus() { + if (!menuOpen || !useDrawer) return + setTimeout(() => { + if (document.activeElement instanceof HTMLIFrameElement) menuOpen = false + }) + } + + const viewportOverlays = overlayStack() + function onWindowKeydown(e: KeyboardEvent) { + onSearchShortcutBeforeLoad(e) + if (e.key !== 'Escape' || !menuOpen || !useDrawer) return + // Read now: the overlay this Esc closes is off the stack by the time the timeout runs. + if (viewportOverlays.val.length > 0) return + // This listener is attached before any drawer's or menu's, which mount later: wait for + // them, so an Esc that closes one of those leaves the card open. + setTimeout(() => { + if (e.defaultPrevented || document.querySelector('[role="menu"]:not([hidden])')) return + const focusInCard = !!document.activeElement?.closest('[data-nav-card]') + menuOpen = false + // The closed card is inert and would drop focus to `body`. + if (focusInCard) document.querySelector<HTMLElement>('[data-nav-handle] button')?.focus() + }) + } // Set once the user docks or detaches, so the rail that mounts from then on skips its // app-entry animation (`wm-sidebar-in`) and only plays `railMorph`. @@ -624,6 +674,11 @@ workspace: $workspaceStore ?? '', starredOnly: true }) + const agents = await ResourceService.listResource({ + workspace: $workspaceStore ?? '', + resourceType: 'ai_agent', + starredOnly: true + }) const assets = await AssetService.listFavoriteAssets({ workspace: $workspaceStore ?? '' }) favoriteManager.current = [ ...scripts.map((s) => ({ @@ -644,6 +699,12 @@ href: getFavoriteHref(f.path, 'app'), kind: 'app' as const })), + ...agents.map((a) => ({ + label: a.description || getFavoriteLabel(a.path, 'agent'), + path: a.path, + href: getFavoriteHref(a.path, 'agent'), + kind: 'agent' as const + })), ...assets.map((a) => ({ label: getFavoriteLabel(a.path, 'asset'), path: a.path, @@ -722,7 +783,7 @@ // Remember the last navigation-mode route so exiting session mode returns // the user where they were rather than to the home page. const to = n.to?.url - if (to && !to.pathname.startsWith(base + '/sessions')) { + if (to && !to.pathname.startsWith('/sessions')) { rememberNavRoute(to.pathname + to.search) } }) @@ -737,7 +798,12 @@ } } - let devOnly = $derived(page.url.pathname.startsWith(base + '/scripts/dev')) + let devOnly = $derived(page.url.pathname.startsWith('/scripts/dev')) + // A devops user who belongs to no workspace has no `$userStore`, and would otherwise wait on + // "Loading user..." forever on the instance pages their role exists for. + let instanceOnlyView = $derived( + !$workspaceStore && !!$devopsRole && isInstanceRoute(page.url.pathname) + ) async function loadDefaultScripts(workspace: string, user: UserExt | undefined) { if (!user?.operator) { @@ -891,7 +957,7 @@ $effect(() => { const ws = $workspaceStore const ready = sessionState.hydrated && $usersWorkspaceStore !== undefined - if (globalAiEnabled && ready && ws && !$userStore?.operator) { + if (globalAiEnabled && sessionsAllowed && ready && ws) { untrack(() => restoreSessionBackups(ws)) } }) @@ -1045,7 +1111,20 @@ }) </script> -<svelte:window bind:innerWidth onkeydown={onSearchShortcutBeforeLoad} /> +<svelte:window + bind:innerWidth + onkeydown={onWindowKeydown} + onpointerdowncapture={closeCardOnPagePress} + onblur={closeCardOnFrameFocus} +/> + +<!-- A manifest's start_url replaces the URL a home-screen shortcut was added from, so only the +console links it: shared pages (public apps, public runs, shared sessions, approval links) live +outside this layout, and their shortcut must reopen the URL that is their credential. --> +<svelte:head> + <link rel="manifest" href="/manifest.webmanifest" /> + <meta name="apple-mobile-web-app-title" content="Windmill" /> +</svelte:head> <!-- Home + Runs lifted to the top of the workspace nav, sitting with Favorites and Search as the primary quick-access cluster. Excluded from SidebarContent @@ -1054,7 +1133,7 @@ <MenuLink class="!text-xs" label="Home" - href={`${base}/`} + href="/" icon={Home} isCollapsed={collapsed} aiId="sidebar-menu-link-home" @@ -1063,7 +1142,7 @@ <MenuLink class="!text-xs" label="Runs" - href={`${base}/runs`} + href="/runs" icon={Play} disabled={!sidebarPageAllowed( $userStore?.operator, @@ -1369,20 +1448,18 @@ inert={!menuOpen} role="dialog" > - <!-- svelte-ignore a11y_click_events_have_key_events, a11y_no_static_element_interactions --> <!-- The card floats over the page, inset and rounded. Over an app it is not: the app owns the window, and the sidebar revealed beside it reads as the panel the header sits on — flush to the left and bottom edges, square, with one border down its right side. --> - <!-- This outside-click catcher starts where the card does rather than at the top of - the viewport: it would otherwise cover the header's toggle, whose hover opened the - card, and swallow the click meant to put the sidebar back. --> + <!-- The frame spans the page only to position the card; it lets every press through + (closeCardOnPagePress dismisses the card). --> <div - class={classNames('fixed left-0 right-0 bottom-0 flex z-40', 'pl-1 pb-2')} + class={classNames( + 'fixed left-0 right-0 bottom-0 flex z-40 pointer-events-none', + 'pl-1 pb-2' + )} style:top="{navHandleSlot.cardTop}px" - onclick={(e) => { - if (e.target === e.currentTarget) menuOpen = false - }} > <!-- svelte-ignore a11y_no_static_element_interactions --> <div @@ -1394,7 +1471,7 @@ schedulePeekClose() }} class={classNames( - 'relative flex-1 flex flex-col max-w-min w-full bg-surface transition ease-in-out duration-300 transform shadow-lg overflow-hidden rounded-lg border', + 'pointer-events-auto relative flex-1 flex flex-col max-w-min w-full bg-surface transition ease-in-out duration-300 transform shadow-lg overflow-hidden rounded-lg border', menuOpen ? 'translate-x-0' : '-translate-x-[calc(100%+0.5rem)]' )} > @@ -1420,7 +1497,7 @@ </div> {/if} {/if} - <div class="flex flex-col h-full w-full relative"> + <div bind:this={pageColumn} class="flex flex-col h-full w-full relative"> <!-- Not gated on `$enterpriseLicense`: it paints the cached accent before the license resolves, and checks the license itself. --> <InstanceUiSync /> @@ -1488,15 +1565,36 @@ <AiChatLayout {children} noPadding={devOnly || menuHidden} - disableAi={globalAiEnabled && !$userStore?.operator ? true : sessionMode} + disableAi={globalAiEnabled && sessionsAllowed ? true : sessionMode} loadAiConfig={!sessionMode} - showSessionsBetaBanner={!$userStore?.operator} + showSessionsBetaBanner={sessionsAllowed} sidebarWidth={railWidth} transitionClass={sidebarTransitionClass} isMobile={useDrawer} /> </div> </div> +{:else if instanceOnlyView} + <!-- No workspace means no sidebar: everything in it is workspace-scoped. The header bar + stays, without its workspace part: pages register their toolbars there. --> + <div class="flex flex-col h-screen w-full bg-surface"> + <div class="flex items-center pl-4 border-b shrink-0"> + <Button + variant="subtle" + unifiedSize="sm" + href="/user/workspaces" + startIcon={{ icon: ArrowLeft }} + > + Workspaces + </Button> + <div class="flex-1 min-w-0"> + <PageHeaderBar navHidden /> + </div> + </div> + <div class="flex-1 min-h-0 overflow-auto"> + {@render children?.()} + </div> + </div> {:else} <CenteredModal title="Loading user..." loading={true}></CenteredModal> {/if} diff --git a/frontend/src/routes/(root)/(logged)/+page.svelte b/frontend/src/routes/(root)/(logged)/+page.svelte index a0fd3dbf4d..8a3836d233 100644 --- a/frontend/src/routes/(root)/(logged)/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/+page.svelte @@ -20,7 +20,6 @@ LayoutDashboard } from 'lucide-svelte' import { hubBaseUrlStore } from '$lib/stores' - import { base } from '$lib/base' import ItemsList from '$lib/components/home/ItemsList.svelte' import PickHubApp from '$lib/components/flows/pickers/PickHubApp.svelte' @@ -194,7 +193,7 @@ </div> </Button> <Button - href="{base}/scripts/add?hub={encodeURIComponent(codeViewerObj?.path ?? '')}" + href="/scripts/add?hub={encodeURIComponent(codeViewerObj?.path ?? '')}" startIcon={{ icon: GitFork }} variant="accent" size="xs" @@ -231,7 +230,7 @@ </Button> <Button - href="{base}/flows/add?hub={flowViewerFlow?.flow?.id}" + href="/flows/add?hub={flowViewerFlow?.flow?.id}" startIcon={{ icon: GitFork }} variant="accent" size="xs" @@ -273,7 +272,7 @@ </Button> <Button - href="{base}/apps/add?hub={appViewerApp?.app?.id}" + href="/apps/add?hub={appViewerApp?.app?.id}" startIcon={{ icon: GitFork }} variant="accent" disabled={appViewerApp == undefined} diff --git a/frontend/src/routes/(root)/(logged)/agents/edit/[...path]/+page.svelte b/frontend/src/routes/(root)/(logged)/agents/edit/[...path]/+page.svelte index f78192c34c..a67ba2dcfa 100644 --- a/frontend/src/routes/(root)/(logged)/agents/edit/[...path]/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/agents/edit/[...path]/+page.svelte @@ -1,7 +1,6 @@ <script lang="ts"> import { untrack } from 'svelte' import { page } from '$app/state' - import { base } from '$lib/base' import { goto } from '$lib/navigation' import { copilotInfo } from '$lib/aiStore' import AgentEditorModal from '$lib/components/flows/content/AgentEditorModal.svelte' @@ -22,10 +21,10 @@ layout="page" enableAi={$copilotInfo.enabled} owns={(t) => t.host === undefined} - onClose={(deployed) => goto(deployed ? `${base}/agents/get/${path}` : `${base}/?kind=agent`)} + onClose={(deployed) => goto(deployed ? `/agents/get/${path}` : `/?kind=agent`)} onDeployed={(saved) => // Replaced, not pushed, when this URL stopped naming what it opens: Back would otherwise // reopen `new_draft` on an agent that now exists, or a path a rename just moved away from. - goto(`${base}/agents/get/${saved}`, { replaceState: isNew || saved !== path })} + goto(`/agents/get/${saved}`, { replaceState: isNew || saved !== path })} /> </div> diff --git a/frontend/src/routes/(root)/(logged)/agents/get/[...path]/+page.svelte b/frontend/src/routes/(root)/(logged)/agents/get/[...path]/+page.svelte index 30eb5cb32c..d18f19c26a 100644 --- a/frontend/src/routes/(root)/(logged)/agents/get/[...path]/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/agents/get/[...path]/+page.svelte @@ -2,11 +2,11 @@ import { page } from '$app/state' import { FlaskConical, FormInput, MessageSquare, Pen } from 'lucide-svelte' import { resource } from 'runed' - import { base } from '$lib/base' import { goto } from '$lib/navigation' import { copilotInfo } from '$lib/aiStore' import AgentEvalsModal from '$lib/components/flows/content/AgentEvalsModal.svelte' import DetailPageHeader from '$lib/components/details/DetailPageHeader.svelte' + import OnBehalfOfBadge from '$lib/components/details/OnBehalfOfBadge.svelte' import ToggleButtonGroup from '$lib/components/common/toggleButton-v2/ToggleButtonGroup.svelte' import ToggleButton from '$lib/components/common/toggleButton-v2/ToggleButton.svelte' import ConfirmationModal from '$lib/components/common/confirmationModal/ConfirmationModal.svelte' @@ -15,10 +15,13 @@ import AgentEditorHost from '$lib/components/flows/content/AgentEditorHost.svelte' import AgentConfigModal from '$lib/components/flows/content/AgentConfigModal.svelte' import RunForm from '$lib/components/RunForm.svelte' + import { Alert } from '$lib/components/common' import { keepsManagedMemory } from '$lib/components/flows/agentFormFields' import { agentMenuItems, deleteAgent } from '$lib/components/flows/agentActions' + import AgentHistory from '$lib/components/flows/AgentHistory.svelte' import { getDeployUiSettings } from '$lib/components/home/deploy_ui' import { userStore, workspaceStore } from '$lib/stores' + import { sendUserToast } from '$lib/toast' /** * The deployed agent, as a flow's or a script's page shows theirs: a way to run it, a chat when @@ -39,11 +42,27 @@ let configModal: AgentConfigModal | undefined = $state(undefined) let shareModal: ShareModal | undefined = $state(undefined) let deploymentDrawer: DeployWorkspaceDrawer | undefined = $state(undefined) + let history: AgentHistory | undefined = $state(undefined) let deleteOpen = $state(false) let evalsModal: AgentEvalsModal | undefined = $state(undefined) + let runForm: RunForm | undefined = $state(undefined) + let isValid = $state(true) + + // Cmd/Ctrl+Enter runs the form, as on a script's or a flow's page. The form stays mounted, hidden, + // while the chat shows, and the chat's composer owns the key then. + function onKeyDown(event: KeyboardEvent) { + if (event.defaultPrevented || event.key !== 'Enter' || !(event.ctrlKey || event.metaKey)) return + if (!runForm || testPane?.mode === 'chat') return + if (isValid) { + event.preventDefault() + runForm.run() + } else { + sendUserToast('Please fix errors before running', true) + } + } async function remove() { - if (ws && (await deleteAgent(ws, path))) await goto(`${base}/?kind=agent`) + if (ws && (await deleteAgent(ws, path))) await goto('/?kind=agent') } // The workspace's, so a path change never waits on it and a menu never outlives its path. @@ -61,6 +80,7 @@ deployUiSettings: deployUiSettings.current, onPermissions: () => shareModal?.openDrawer?.(path, 'resource'), onDeploy: () => deploymentDrawer?.openDrawer(path, 'resource'), + onHistory: () => history?.open(), onDelete: () => (deleteOpen = true) }).map((item) => ({ label: item.displayName, @@ -75,6 +95,7 @@ <ShareModal bind:this={shareModal} /> <DeployWorkspaceDrawer bind:this={deploymentDrawer} /> +<AgentHistory bind:this={history} {path} canRestore={canEdit} onRestored={() => reloaded++} /> <ConfirmationModal open={deleteOpen} title="Delete agent" @@ -88,6 +109,8 @@ <span>Every flow that links {path} will fail at its agent step once it is deleted.</span> </ConfirmationModal> +<svelte:window onkeydown={onKeyDown} /> + <main class="h-full w-full flex flex-col"> <!-- `labels`: the pen saves every field it shows in one write, so the labels it shows have to be the ones the resource carries. Handed none, it would offer an empty list, and the first @@ -103,7 +126,7 @@ ? async (newPath) => { // A rename moves the page; a summary saved in place has to be read again, since // what is shown here came from the load this page keys on. - if (newPath !== path) await goto(`${base}/agents/get/${newPath}`) + if (newPath !== path) await goto(`/agents/get/${newPath}`) else reloaded++ } : undefined} @@ -127,13 +150,18 @@ variant: 'accent', unifiedSize: 'md', startIcon: Pen, - href: `${base}/agents/edit/${path}` + href: `/agents/edit/${path}` } } ] : []) ]} > + <OnBehalfOfBadge + onBehalfOf={config?.run_on_behalf_of ? agent?.onBehalfOf : undefined} + onBehalfOfEmail={undefined} + kind="agent" + /> {#snippet leading_actions()} <!-- Only an agent that keeps the conversation can chat: without managed memory every message would be answered alone, so it is run from its inputs with nothing to switch. --> @@ -180,6 +208,14 @@ onOpenConfig={() => configModal?.open()} > {#snippet viewForm({ schema, run, loading, actions })} + {#if config && !chatAvailable} + <Alert type="info" size="xs" title="Managed memory is off" class="mb-4"> + Each run is answered on its own inputs, so this agent has no chat. That suits reusing + it as a step in a flow.{canEdit + ? ' Turn on managed memory in its configuration to chat with it.' + : ''} + </Alert> + {/if} <RunForm runnable={{ schema, path }} runAction={run} @@ -188,6 +224,8 @@ autofocus {loading} {actions} + bind:isValid + bind:this={runForm} /> {/snippet} </AgentEditorHost> diff --git a/frontend/src/routes/(root)/(logged)/apps/edit/[...path]/+page.svelte b/frontend/src/routes/(root)/(logged)/apps/edit/[...path]/+page.svelte index 974d1c7f64..57e387ad20 100644 --- a/frontend/src/routes/(root)/(logged)/apps/edit/[...path]/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/apps/edit/[...path]/+page.svelte @@ -108,7 +108,7 @@ itemKind: 'app', path }) - const emptyPolicy = { execution_mode: 'publisher' } as any + const emptyPolicy = { execution_mode: 'publisher', sandbox: true } as any // One-shot import handoff via $importStore (YAML/JSON or "Build app"). // Wrapped exports carry { summary, value, policy }; bare ones are the App value. const importRaw = $importStore @@ -246,7 +246,7 @@ summary: savedDraftApp?.summary ?? '', value: (savedDraftApp ?? {}) as App, path: page.params.path ?? '', - policy: { execution_mode: 'publisher' } as any, + policy: { execution_mode: 'publisher', sandbox: true } as any, custom_path: undefined, versions: undefined as any, id: 0 as any, diff --git a/frontend/src/routes/(root)/(logged)/apps/get_raw/[version]/[...path]/+page.svelte b/frontend/src/routes/(root)/(logged)/apps/get_raw/[version]/[...path]/+page.svelte index dbba9ce790..edc0c2d918 100644 --- a/frontend/src/routes/(root)/(logged)/apps/get_raw/[version]/[...path]/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/apps/get_raw/[version]/[...path]/+page.svelte @@ -1,6 +1,5 @@ <script lang="ts"> import { goto } from '$app/navigation' - import { base } from '$app/paths' import { page } from '$app/state' import { onMount } from 'svelte' @@ -12,6 +11,6 @@ // component (not a load redirect) because `url.hash` is unavailable in `load`. onMount(() => { const path = page.params.path ?? '' - goto(`${base}/apps_raw/get/${path}${page.url.search}${page.url.hash}`, { replaceState: true }) + goto(`/apps_raw/get/${path}${page.url.search}${page.url.hash}`, { replaceState: true }) }) </script> diff --git a/frontend/src/routes/(root)/(logged)/apps_raw/edit/[...path]/+page.svelte b/frontend/src/routes/(root)/(logged)/apps_raw/edit/[...path]/+page.svelte index 9ed2ca296a..8956f42441 100644 --- a/frontend/src/routes/(root)/(logged)/apps_raw/edit/[...path]/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/apps_raw/edit/[...path]/+page.svelte @@ -4,6 +4,7 @@ import { AppService } from '$lib/gen' import { userStore, workspaceStore } from '$lib/stores' + import { useOperatorBuilderApps, workspaceListLoaded } from '$lib/operatorWriteRights' import { readFieldsRecursively } from '$lib/utils' import { goto } from '$lib/navigation' import { sendUserToast } from '$lib/toast' @@ -32,7 +33,11 @@ type RawAppBuildMode, type RawAppTemplatePickerResult } from '$lib/components/raw_apps/RawAppTemplatePicker.svelte' - import { react19Template, STARTER_RUNNABLES } from '$lib/components/raw_apps/templates' + import { + BUILDER_FRAMEWORK_TEMPLATES, + react19Template, + STARTER_RUNNABLES + } from '$lib/components/raw_apps/templates' import { aiChatManager, AIMode } from '$lib/components/copilot/chat/AIChatManager.svelte' type RawAppDraft = { @@ -97,6 +102,8 @@ // edits to the just-deployed app autosaved to a dead key (autosave appeared // broken). See /scripts/edit, which derives its draft path the same way. // effectivePath omitted: the live-editor-draft entry is owned by RawAppEditor. + const operatorBuilderApps = useOperatorBuilderApps() + const draftSync = usePageDraftSync<RawAppDraft>({ itemKind: 'raw_app', path: () => page.params.path ?? '', @@ -188,6 +195,8 @@ // `?new_draft` loads the saved draft instead of blanking it — see // shouldSeedNewDraft. if (shouldSeedNewDraft(page.url.searchParams, $workspaceStore, 'raw_app', path)) { + await workspaceListLoaded() + if (tok !== loadAppToken) return isNewApp = true // Page reused across same-route nav: clear the previous path's // draft-presence state so it doesn't bleed onto the fresh draft. @@ -226,7 +235,8 @@ ? $userStore?.username : `u/${$userStore?.username}`, on_behalf_of_email: $userStore?.email, - execution_mode: 'publisher' + execution_mode: 'publisher', + sandbox: true } as any // Explicit path seed: the fork-a-draft handoff re-homes the source // path into the forker's namespace and passes it here. @@ -270,8 +280,10 @@ } // Seed the React 19 template so the editor has a usable state even if the // user dismisses the picker without selecting. - const seedFiles = { ...react19Template } - const seedRunnables = structuredClone(STARTER_RUNNABLES) + const seedFiles = { + ...($operatorBuilderApps ? BUILDER_FRAMEWORK_TEMPLATES.react19 : react19Template) + } + const seedRunnables = starterRunnables() savedApp = { summary: '', value: { files: seedFiles as any, runnables: seedRunnables as any }, @@ -374,7 +386,7 @@ data: savedRawAppDraft?.data } backendApp.summary = savedRawAppDraft?.summary ?? '' - backendApp.policy = savedRawAppDraft?.policy ?? { execution_mode: 'publisher' } + backendApp.policy = savedRawAppDraft?.policy ?? { execution_mode: 'publisher', sandbox: true } backendApp.custom_path = savedRawAppDraft?.custom_path backendApp.path = page.params.path ?? '' } else if (savedRawAppDraft) { @@ -520,10 +532,16 @@ let rawAppEditor: RawAppEditor | undefined = $state() + // The starter runnables are inline scripts, which the backend refuses from an operator with + // builder rights: seeding them would make their very first deploy fail. + function starterRunnables() { + return $operatorBuilderApps ? {} : structuredClone(STARTER_RUNNABLES) + } + async function onTemplatePickerStart(result: RawAppTemplatePickerResult, mode: RawAppBuildMode) { const picked = { files: { ...result.files }, - runnables: { ...result.runnables, ...structuredClone(STARTER_RUNNABLES) }, + runnables: { ...result.runnables, ...starterRunnables() }, data: result.data, summary: '', policy: result.policy diff --git a/frontend/src/routes/(root)/(logged)/concurrency_groups/+page.svelte b/frontend/src/routes/(root)/(logged)/concurrency_groups/+page.svelte index 2272449e0f..9e58c633e7 100644 --- a/frontend/src/routes/(root)/(logged)/concurrency_groups/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/concurrency_groups/+page.svelte @@ -1,7 +1,6 @@ <script lang="ts"> import type { ConcurrencyGroup } from '$lib/gen' import { ConcurrencyGroupsService } from '$lib/gen' - import { base } from '$lib/base' import CenteredPage from '$lib/components/CenteredPage.svelte' import { Button } from '$lib/components/common' @@ -91,7 +90,7 @@ <tr> <td> <a - href={`${base}/runs/?job_kinds=all&graph=ConcurrencyChart&concurrency_key=${concurrency_key}`} + href={`/runs/?job_kinds=all&graph=ConcurrencyChart&concurrency_key=${concurrency_key}`} >{concurrency_key} </a> </td> diff --git a/frontend/src/routes/(root)/(logged)/groups/+page.svelte b/frontend/src/routes/(root)/(logged)/groups/+page.svelte index ce8c6a8db0..c17c6c188e 100644 --- a/frontend/src/routes/(root)/(logged)/groups/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/groups/+page.svelte @@ -12,7 +12,7 @@ import PageHeader from '$lib/components/PageHeader.svelte' import SharedBadge from '$lib/components/SharedBadge.svelte' import { userStore, workspaceStore, userWorkspaces } from '$lib/stores' - import { canWrite } from '$lib/utils' + import { useEditRights } from '$lib/operatorWriteRights' import { Pen, Plus, Trash } from 'lucide-svelte' import DataTable from '$lib/components/table/DataTable.svelte' import Head from '$lib/components/table/Head.svelte' @@ -24,6 +24,8 @@ type GroupW = Group & { canWrite: boolean } + const editRights = useEditRights() + let restricted = $derived( isDemoWorkspaceRestricted($workspaceStore, $userStore?.is_admin, $userStore?.is_super_admin) ) @@ -34,7 +36,7 @@ async function loadGroups(): Promise<void> { groups = (await GroupService.listGroups({ workspace: $workspaceStore! })).map((x) => { - return { canWrite: canWrite(x.name, x.extra_perms ?? {}, $userStore), ...x } + return { canWrite: editRights.canEditItem('group', x.name, x.extra_perms), ...x } }) } diff --git a/frontend/src/routes/(root)/(logged)/pipeline/+page.svelte b/frontend/src/routes/(root)/(logged)/pipeline/+page.svelte index ad1951f5f7..d7972d3ef1 100644 --- a/frontend/src/routes/(root)/(logged)/pipeline/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/pipeline/+page.svelte @@ -3,10 +3,10 @@ import PipelineFolderList from '$lib/components/assets/AssetGraph/PipelineFolderList.svelte' import PipelineSetupSignpost from '$lib/components/assets/AssetGraph/PipelineSetupSignpost.svelte' import PipelineAlphaAckModal from '$lib/components/assets/AssetGraph/PipelineAlphaAckModal.svelte' - import PipelineDbtSignpost from '$lib/components/assets/AssetGraph/PipelineDbtSignpost.svelte' import { BookOpen } from 'lucide-svelte' - import { onMount } from 'svelte' import PageHeaderContent from '$lib/components/PageHeaderContent.svelte' + import Badge from '$lib/components/common/badge/Badge.svelte' + import { onMount } from 'svelte' const ACK_STORAGE_KEY = 'pipeline-alpha-ack' @@ -42,32 +42,22 @@ <PageHeaderContent section={{ label: 'Pipelines' }} afterName={alphaBadge} separator="always" /> {#snippet alphaBadge()} - <span - class="text-2xs px-1.5 py-0.5 rounded font-semibold bg-emerald-100 text-emerald-700 dark:bg-emerald-900/40 dark:text-emerald-300" - > - Alpha - </span> + <Badge color="green">Alpha</Badge> {/snippet} <div class="flex flex-col h-full"> <div class="flex-1 min-h-0 overflow-y-auto bg-surface-secondary"> <div class="max-w-2xl mx-auto flex flex-col gap-6 px-4 py-8"> <div class="flex flex-col gap-2"> - <h2 class="text-lg font-semibold">Data pipelines</h2> - <p class="text-sm text-tertiary"> + <h2 class="text-lg font-semibold text-emphasis">Data pipelines</h2> + <p class="text-xs text-secondary"> Chain ingestion, transformation and materialization steps into an asset-aware graph. - {#if !$userStore?.operator} - Each pipeline lives in a folder: open one below, or pick a folder to start a new - pipeline. - {:else} - Open a pipeline below to view its graph and runs. - {/if} </p> <a href="https://www.windmill.dev/docs/pipelines" target="_blank" rel="noreferrer" - class="text-xs text-blue-500 hover:underline inline-flex items-center gap-1" + class="text-xs text-accent hover:underline inline-flex items-center gap-1 w-fit" > <BookOpen size={12} /> Pipelines documentation @@ -78,14 +68,8 @@ <PipelineSetupSignpost workspace={$workspaceStore} /> {/if} - <PipelineFolderList /> - - <!-- Below the pipeline content on purpose: dbt is a separate runtime, not a - way of building a pipeline, and reads as one when it sits in the flow - that defines what a pipeline is. --> - {#if !$userStore?.operator} - <PipelineDbtSignpost /> - {/if} + <!-- Operators cannot pick an arbitrary folder, so the list is their only way in. --> + <PipelineFolderList hideExisting={!$userStore?.operator} /> </div> </div> </div> diff --git a/frontend/src/routes/(root)/(logged)/pipeline/[folder]/+page.svelte b/frontend/src/routes/(root)/(logged)/pipeline/[folder]/+page.svelte index a16b1a1e49..f5833527b0 100644 --- a/frontend/src/routes/(root)/(logged)/pipeline/[folder]/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/pipeline/[folder]/+page.svelte @@ -1,7 +1,7 @@ <script lang="ts"> + import pLimit from 'p-limit' import { workspaceStore, userStore } from '$lib/stores' import { PIPELINE_DRAFT_KIND, pipelineBundlePath } from '$lib/pipelinePaths' - import { base } from '$lib/base' import PageHeaderContent from '$lib/components/PageHeaderContent.svelte' import { page } from '$app/state' import Button from '$lib/components/common/button/Button.svelte' @@ -19,16 +19,13 @@ import { usePipelineHistory } from '$lib/components/assets/AssetGraph/pipelineHistory.svelte' import PipelineActivityPanel from '$lib/components/assets/AssetGraph/PipelineActivityPanel.svelte' import PipelinePickerModal from '$lib/components/assets/AssetGraph/PipelinePickerModal.svelte' - import { - extractWrites, - extractReads, - type AssetWithAltAccessType - } from '$lib/components/assets/lib' import type { AssetGraphResponse, AssetGraphSelection, NativeTriggerKind, - PipelineMode + PipelineMode, + PipelineTriggerDraft, + PipelineTriggerDraftKind } from '$lib/components/assets/AssetGraph/types' import PipelineModeToggle from '$lib/components/assets/AssetGraph/PipelineModeToggle.svelte' import MacroExplorerDrawer from '$lib/components/assets/AssetGraph/MacroExplorerDrawer.svelte' @@ -41,9 +38,13 @@ mergeColumnGraphs } from '$lib/components/assets/AssetGraph/columnLineageGraph' import { useDbtColumnLineage } from '$lib/components/assets/AssetGraph/dbtColumnLineage.svelte' - import { resolveGraph } from '$lib/components/assets/AssetGraph/resolveGraph' + import { + pipelineNodeErrors, + resolveGraph + } from '$lib/components/assets/AssetGraph/resolveGraph' import { normalizePipelineFolder } from '$lib/utils/pipelineFolder' import { hideDbtRunnables } from '$lib/components/assets/AssetGraph/hideDbtRunnables' + import { usePipelineDataUploads } from '$lib/components/assets/AssetGraph/pipelineDataUploads.svelte' import { buildSchemaContractContext } from '$lib/components/assets/AssetGraph/schemaContracts' import { computeDownstreamClosure, @@ -80,18 +81,50 @@ createPipelineAiHelpers, type PipelineDraft } from '$lib/components/assets/AssetGraph/pipelineAiHelpers' - import { PipelineEditorState } from '$lib/components/assets/AssetGraph/pipelineEditorState.svelte' + import { + PipelineEditorState + } from '$lib/components/assets/AssetGraph/pipelineEditorState.svelte' + import { + defaultTriggerPath, + isDraftableTriggerKind, + triggerDraftKey + } from '$lib/components/assets/AssetGraph/pipelineTriggerDrafts' + import { deleteTriggerRow } from '$lib/components/assets/AssetGraph/pipelineTriggerDraftDeploy' + import { + deployPipelineDrafts, + deployPipelineScript + } from '$lib/components/assets/AssetGraph/pipelineDeploy.svelte' + import type { AssetUpstreamDelete } from '$lib/components/assets/AssetGraph/assetsOnlyView' + import type { NodeFixSpec } from '$lib/components/assets/AssetGraph/NodeFixButton.svelte' + import { TRIGGER_NODE_STYLE } from '$lib/components/assets/AssetGraph/TriggerNode.svelte' + import { + addTriggerDirective, + assetRef, + listenToAsset, + removeTriggerDirective, + stopListeningChangeText, + stopListeningToAsset + } from '$lib/components/assets/AssetGraph/pipelineAnnotationEdits' + import ConfirmationModal from '$lib/components/common/confirmationModal/ConfirmationModal.svelte' + import type { PipelineInsertOptions } from '$lib/components/assets/AssetGraph/PipelineInsertMenu.svelte' import { createPipelineRecording, finalizePipelineRecording } from '$lib/components/recording/pipelineRecording.svelte' import type { PipelineRecording } from '$lib/components/recording/types' import AutosaveIndicator from '$lib/components/AutosaveIndicator.svelte' + import { usePipelineAssetPrefetch } from '$lib/components/assets/AssetGraph/pipelineAssetPrefetch.svelte' + import PipelineDeployErrors from '$lib/components/assets/AssetGraph/PipelineDeployErrors.svelte' + import PipelineDeployTriggersModal from '$lib/components/assets/AssetGraph/PipelineDeployTriggersModal.svelte' import { onMount, tick, untrack } from 'svelte' + import { UserDraftDbSyncer } from '$lib/userDraftDbSyncer.svelte' + import OpenInSessionButton, { + type OpenInSessionSource + } from '$lib/components/sessions/OpenInSessionButton.svelte' + import { setOpenInSessionHandoff } from '$lib/components/sessions/openInSessionContext' import { aiChatManager } from '$lib/components/copilot/chat/AIChatManager.svelte' import { AlertTriangle, - ArrowLeft, ChevronDown, Circle, Download, @@ -99,6 +132,7 @@ FolderSearch, History, Loader2, + NetworkIcon, Play, RefreshCw, Save, @@ -111,18 +145,15 @@ OpenAPI, ScheduleService, ScriptService, + AssetService, type AssetKind, type Script, type ScriptLang } from '$lib/gen' import { resource } from 'runed' import { emptySchema, sendUserToast, type Item } from '$lib/utils' - import type { Schema } from '$lib/common' import { beforeNavigate, goto } from '$app/navigation' import { fade } from 'svelte/transition' - import { twMerge } from 'tailwind-merge' - import Popover from '$lib/components/meltComponents/Popover.svelte' - import { inferArgs, inferAssets } from '$lib/infer' import PipelineTriggerEditors from '$lib/components/assets/AssetGraph/PipelineTriggerEditors.svelte' // Variables and resources are declarative config, not pipeline assets — @@ -130,7 +161,15 @@ // layout without adding lineage information. const DATA_KINDS = DATA_ASSET_KINDS - let folder = $derived(normalizePipelineFolder(page.params.folder as string)) + // The route param is gone for a moment while the page tears down on leaving; the + // folder keeps its last value so nothing keyed on it (draft autosave, graph + // fetch) sees a different folder in that window. + let lastFolder = '' + let folder = $derived.by(() => { + const param = page.params.folder + if (param !== undefined) lastFolder = normalizePipelineFolder(param) + return lastFolder + }) // Externalized editor state (drafts, live overlays, selection), shared with // the in-session pipeline preview via PipelineEditorState. Referenced as @@ -148,6 +187,8 @@ if (pe.folder !== f) { if (pe.folder !== undefined) { pe.reset() + // The set-aside edit pane belongs to the folder being left. + editPane = undefined // Re-scope the Global chat's pipeline prompt to the new folder. The // helper methods already read the reactive folder, but the system // message string was built for the old one and is only rebuilt when @@ -166,21 +207,45 @@ let isOperator = $derived($userStore?.operator ?? false) let urlMode = $derived(page.url.searchParams.get('mode')) let mode = $derived<PipelineMode>(isOperator ? 'view' : urlMode === 'edit' ? 'edit' : 'view') + // The edit-mode pane, set aside while View shows the activity feed, so coming + // back to Edit reopens it. + let editPane: + | { selection: typeof pe.selection; activeDraftPath: string | undefined; hidden: boolean } + | undefined = undefined function setMode(m: PipelineMode, opts?: { replace?: boolean }) { // Switching edit→view re-surfaces the activity feed: drop the edit-mode // selection / open draft / hidden-pane state so view opens on Activity // rather than a stale details pane (mirrors toggleActivity's show path). if (m === 'view' && mode === 'edit') { + editPane = { + selection: pe.selection, + activeDraftPath: pe.activeDraftPath, + hidden: panelHidden + } pe.selection = undefined pe.activeDraftPath = undefined panelHidden = false pe.liveAnnotations = EMPTY_LIVE_ANNOTATIONS } + // View→edit keeps what was opened in View; with only the activity feed + // (or nothing) showing, it reopens the pane Edit had. + if (m === 'edit' && mode === 'view') { + const openedInView = pe.selection != undefined || pe.activeDraftPath != undefined + if (!openedInView && editPane) { + const draft = editPane.activeDraftPath + pe.activeDraftPath = draft && pe.drafts.has(draft) ? draft : undefined + pe.selection = pe.activeDraftPath ? undefined : editPane.selection + panelHidden = editPane.hidden + } else if (openedInView) { + panelHidden = false + } + editPane = undefined + } const url = new URL(page.url) if (m === 'view') url.searchParams.delete('mode') else url.searchParams.set('mode', m) // Same-pathname navigation — the drafts leave-guard skips it. - goto(url, { replaceState: opts?.replace ?? false, keepFocus: true, noScroll: true }) + return goto(url, { replaceState: opts?.replace ?? false, keepFocus: true, noScroll: true }) } // View-mode drafts overlay: "what View will show once the drafts are // deployed". A view variant rather than a third mode — ephemeral (not @@ -188,17 +253,6 @@ // shared link couldn't reproduce it anyway). let includeDrafts = $state(false) - // Asset-kind → syntax-prefix for `// on <ref>` reconstruction. Mirrors - // ASSET_KINDS in backend/parsers/windmill-parser/src/asset_parser.rs. - const ASSET_PREFIX: Record<AssetKind, string> = { - s3object: 's3://', - resource: '$res:', - ducklake: 'ducklake://', - datatable: 'datatable://', - volume: 'volume://', - dbt: 'dbt://' - } - // Path-input split for the insert menu: a read-only `f/<folder>/` chip // on the left the user can't delete, plus an editable suffix seeded // with a placeholder name. @@ -254,7 +308,7 @@ panelHidden = false focusPipelineNode(`script:${path}`) } else { - window.open(`${base}/scripts/get/${path}`, '_blank') + window.open(`/scripts/get/${path}`, '_blank') } } @@ -281,75 +335,16 @@ } } - // Only-add cache of (script_path → body content) populated lazily by - // `bodyFetchEffect` for every script in the current folder. We never - // remove entries: stale keys (renamed-away, deleted) are simply ignored - // at read time because the derived maps below only iterate paths that - // appear in the current `g.runnables`. That self-cleaning property is - // the whole reason for the refactor — no rename/delete cleanup needed. - let bodiesByPath = $state<Map<string, string>>(new Map()) - // Sibling cache: the parsed asset usages from `inferAssets` (wasm), one - // pass per body. Same only-add semantics as `bodiesByPath`. - let inferredAssetsByPath = $state<Map<string, AssetWithAltAccessType[]>>(new Map()) - // Bumped on folder change so an in-flight prefetch sweep stops before - // writing into the new folder's state. - let bodyFetchGen = 0 - - // Inferred write/read edges per script-in-graph. Derived from - // (a) the open pane's live overlay (`liveBodyAssets`) — current - // keystrokes for the script the user is editing right now, and - // (b) the prefetched assets cache for everyone else. - // Iteration is gated on `graphRes.current.runnables`, so a path that - // gets renamed / deleted disappears from the derived map as soon as - // the refetch lands — no manual rekey, no phantom edges. - // Single pass over the graph's scripts producing both the write- and - // read-asset maps (they only differ by extractWrites vs extractReads over - // the same `liveBodyAssets`-vs-cache asset source). Split into two derives - // below so consumers can depend on one without invalidating on the other. - let inferredAssetEdges = $derived.by(() => { - const writes = new Map<string, Array<{ kind: AssetKind; path: string }>>() - const reads = new Map<string, Array<{ kind: AssetKind; path: string }>>() - const g = graphRes.current - if (!g) return { writes, reads } - const liveAssetsForPath = (path: string) => - pe.liveBodyAssets.scriptPath === path - ? pe.liveBodyAssets.assets - : inferredAssetsByPath.get(path) - for (const r of g.runnables) { - if (r.usage_kind !== 'script') continue - const assets = liveAssetsForPath(r.path) - if (!assets) continue - const w = extractWrites(assets) - if (w.length > 0) writes.set(r.path, w) - const rd = extractReads(assets) - if (rd.length > 0) reads.set(r.path, rd) - } - return { writes, reads } - }) - let inferredWritesByPath = $derived(inferredAssetEdges.writes) - let inferredReadsByPath = $derived(inferredAssetEdges.reads) - // Same derived shape for `// on kafka` etc. annotations. Live buffer - // wins for the open script; everyone else is parsed from the - // prefetched body content. - let annotatedNativeKindsByPath = $derived.by(() => { - const out = new Map<string, Set<NativeTriggerKind>>() - const g = graphRes.current - if (!g) return out - const livePath = pe.liveAnnotations.scriptPath - for (const r of g.runnables) { - if (r.usage_kind !== 'script') continue - let kinds: Set<NativeTriggerKind> - if (r.path === livePath) { - kinds = new Set(pe.liveAnnotations.annotations.nativeTriggers.map((n) => n.kind)) - } else { - const body = bodiesByPath.get(r.path) - if (!body) continue - kinds = new Set(parsePipelineAnnotations(body).nativeTriggers.map((n) => n.kind)) - } - if (kinds.size > 0) out.set(r.path, kinds) - } - return out + // Bodies, inferred asset edges and `// on` annotations of every deployed + // script in the folder, so the graph shows the edges of scripts never opened. + const assetPrefetch = usePipelineAssetPrefetch({ + getWorkspace: () => $workspaceStore, + getGraph: () => graphRes.current, + editor: pe }) + let inferredWritesByPath = $derived(assetPrefetch.inferredWritesByPath) + let inferredReadsByPath = $derived(assetPrefetch.inferredReadsByPath) + let annotatedNativeKindsByPath = $derived(assetPrefetch.annotatedNativeKindsByPath) // Build a runnable Script from picked language / triggers / output. // Delegates to the shared template generator (pipelineTemplates.ts) so @@ -412,9 +407,10 @@ triggers: DraftTriggerSource[], outputKind: PipelineOutputKind, input?: { kind: AssetKind; path: string }, - aiPrompt?: string + aiPrompt?: string, + options?: PipelineInsertOptions ) { - const out = autoOutputAsset(outputKind, folder, language) + const out = options?.outputAsset ?? autoOutputAsset(outputKind, folder, language) const script = buildDraft(language, scriptPath, triggers, outputKind, out, input) // Write the new draft into the map (structural update so Svelte // re-derives graphWithDraft) and focus it in the details pane. When @@ -429,6 +425,19 @@ pe.drafts = next pe.activeDraftPath = scriptPath pe.selection = undefined + if (options?.schedule) { + const path = options.schedule.path || defaultTriggerPath(scriptPath, 'schedule') + const saved = pe.setTriggerDraft({ + kind: 'schedule', + config: { ...options.schedule, path, script_path: scriptPath } + }) + if (!saved) { + sendUserToast( + `Another draft schedule already uses the path ${path}; the new script has no schedule`, + true + ) + } + } // Follow the new node with a smooth pan. The id matches the runnable // node the canvas builds for a draft script (`script:<path>`). @@ -488,10 +497,16 @@ getFolder: () => folder, getWorkspace: () => $workspaceStore, getResolvedGraph: () => graphWithDraft, + hasTriggerDrafts: () => pe.triggerDrafts.size > 0, + getTriggerDrafts: () => pe.triggerDrafts, + setTriggerDraft: pe.setTriggerDraft, getDrafts: () => pe.drafts, setDrafts: (next) => (pe.drafts = next), newDraftLocalId: pe.newDraftLocalId, - onForgetPath: (path) => forgetPath(path), + onForgetPath: (path) => { + forgetPath(path) + pe.discardTriggerDraftsFor(path) + }, onShowDrafts: () => (includeDrafts = true), onProposeNode: (path) => focusPipelineNode(`script:${path}`), ensureEditable: () => { @@ -513,6 +528,42 @@ onMount(() => aiChatManager.setPipelineHelpers(pipelineAiHelpers)) + // The session's preview hydrates this folder's drafts from its DB bundle, so the + // autosave still inside its debounce has to land first. + async function persistDraftsForSession(): Promise<void> { + const workspace = $workspaceStore + if (!workspace) return + await tick() + const draft = { workspace, itemKind: PIPELINE_DRAFT_KIND, path: pipelineDraftPath } + await UserDraftDbSyncer.flush(draft) + // A flush resolves even when the save failed or conflicted, and the session + // would then open on the older drafts the server holds: stay here instead. + if (UserDraftDbSyncer.getConflict(draft).conflict) { + throw new Error('The pipeline drafts conflict with a newer version — resolve that first.') + } + const sync = UserDraftDbSyncer.getState(draft) + if (sync.state === 'failed') { + throw new Error( + `The pipeline drafts could not be saved: ${sync.failureMessage ?? 'unknown error'}` + ) + } + // The drafts go with the pipeline into the session, so leaving for it is + // not leaving them behind. + bypassNavigationGuard = true + } + + const sessionOpen: OpenInSessionSource | undefined = $derived( + isOperator + ? undefined + : { + target: { kind: 'pipeline', path: folder }, + workspaceId: $workspaceStore ?? undefined, + beforeOpen: persistDraftsForSession + } + ) + // Lets the navigation rail's session switch open this pipeline, with its drafts. + setOpenInSessionHandoff({ source: () => sessionOpen }) + // Navigation guard state. `pendingNavigationUrl` holds the URL the user // tried to leave to so we can complete the navigation after they pick // "Save all" or "Discard all"; `bypassNavigationGuard` is the standard @@ -528,7 +579,7 @@ bypassNavigationGuard = false return } - if (pe.drafts.size === 0) return + if (pendingCount === 0) return // `leave` covers tab close / hard reload / cross-origin nav. SvelteKit // turns a cancelled leave into a browser-native "Leave site?" prompt, // which we explicitly don't want — match the rest of the editors and @@ -563,7 +614,11 @@ // stale active path don't bleed into the next page. localStorage // is overwritten by the persist effect on the next tick. pe.drafts = new Map() + pe.triggerDrafts = new Map() pe.activeDraftPath = undefined + // The open pane's buffer is autosaved as a draft of the deployed script it + // edits, so it has to go with the drafts. + pe.clearLiveOverlays() saveErrors = new Map() const target = pendingNavigationUrl leaveModalOpen = false @@ -574,7 +629,20 @@ } } + // Triggers start running once deployed, so leaving through "Save all" asks + // first, like the toolbar button, and navigates once confirmed. + let leaveAfterTriggerConfirm = $state(false) async function leaveModalSaveAll() { + if (pe.triggerDrafts.size > 0) { + leaveModalOpen = false + leaveAfterTriggerConfirm = true + confirmTriggerDeployOpen = true + return + } + await saveAllAndLeave() + } + + async function saveAllAndLeave() { leaveSaving = true await saveAllDrafts() leaveSaving = false @@ -582,7 +650,7 @@ // page so they can deal with the failures via the bar's error // popover. Otherwise resume the navigation that triggered the // guard. - if (pe.drafts.size === 0) { + if (pendingCount === 0) { const target = pendingNavigationUrl leaveModalOpen = false pendingNavigationUrl = undefined @@ -601,6 +669,8 @@ // are removed from the drafts map as they land. let savingAll = $state(false) let saveErrors = $state<Map<string, string>>(new Map()) + // Opened by a save that fails, so the reason is on screen without a click. + let saveErrorsOpen = $state(false) // Post-deploy verification: capture the cascade-relevant facts (writes + // `// on` subscriptions) the resolved draft graph promises for `paths`. @@ -620,134 +690,38 @@ if (msg) sendUserToast(msg, true) } - async function saveDraft(path: string, draft: Draft, ws: string): Promise<void> { - const script = structuredClone($state.snapshot(draft.script) as Script) - script.schema = script.schema ?? emptySchema() - try { - const result = await inferArgs(script.language, script.content, script.schema as Schema) - ;(script as any).auto_kind = result?.auto_kind || undefined - script.has_preprocessor = result?.has_preprocessor ?? false - } catch { - // Inference failures don't block deploys (the same fallback the - // per-pane save uses). The createScript call is the real - // validation gate — if the body is broken it'll reject there. - } - // Re-infer the asset lineage from the CURRENT body. The draft's - // `script.assets` is a snapshot that isn't refreshed on edit, so without - // this a renamed/removed output (e.g. an old `CREATE TABLE foo`) would - // be re-deployed as a phantom write edge and linger as an orphan asset. - // Mirrors the per-pane save, which sends live-inferred assets. - let assets: AssetWithAltAccessType[] = [] - try { - const inferred = await inferAssets(script.language, script.content) - if (inferred?.status !== 'error') - assets = (inferred?.assets ?? []) as AssetWithAltAccessType[] - } catch { - // Same fallback as above — an unparsable body deploys with no - // lineage rather than the stale snapshot. - } - await ScriptService.createScript({ - workspace: ws, - requestBody: { - ...script, - language: script.language, - description: script.description ?? '', - // Brand-new drafts have no parent (buildDraft seeds hash as '' - // — treat any falsy hash as parentless, the backend rejects - // an empty hex string); a draft promoted from unsaved edits - // to a deployed script carries that script's hash and must - // chain off it (createScript rejects a parentless deploy to - // an occupied path). - parent_hash: script.hash ? String(script.hash) : undefined, - is_template: false, - tag: script.tag, - kind: script.kind as Script['kind'] | undefined, - lock: undefined, - // Freshly inferred above — overrides the stale snapshot carried - // by `...script`, so the deployed lineage matches the body. - assets: assets as any - } - }) + // Scripts plus trigger drafts: what "Save all" deploys. + let pendingCount = $derived( + pe.drafts.size + pe.triggerDrafts.size + (pe.liveEditPath != undefined ? 1 : 0) + ) + let confirmTriggerDeployOpen = $state(false) + + function requestSaveAll() { + if (pe.triggerDrafts.size > 0) confirmTriggerDeployOpen = true + else void saveAllDrafts() } async function saveAllDrafts() { - if (!$workspaceStore || pe.drafts.size === 0 || savingAll) return + if (!$workspaceStore || pendingCount === 0 || savingAll) return savingAll = true - const ws = $workspaceStore - // The open pane's keystrokes live in `pe.liveContent` until the pane is - // torn down — the drafts Map still holds the pre-edit snapshot. Deploy - // what the user sees: fold the live buffer into its draft (same merge - // the autosave bundle applies before persisting). - const liveContentPath = - pe.liveContent.scriptPath != undefined && pe.drafts.has(pe.liveContent.scriptPath) - ? pe.liveContent.scriptPath - : undefined - const entries = [...pe.drafts.entries()].map(([path, d]) => { - if (path !== liveContentPath || d.script.content === pe.liveContent.content) - return [path, d] as [string, Draft] - return [path, { ...d, script: { ...d.script, content: pe.liveContent.content } }] as [ - string, - Draft - ] - }) // Snapshot what the preview promises for every draft before anything // deploys — used to verify the persisted graph below. - const predicted = predictCascadeFacts(entries.map(([p]) => p)) - const errors = new Map<string, string>() - const savedPaths: string[] = [] - // Parallel — every createScript is independent. The backend handles - // its own ordering for any cross-script lock writes; we just want - // failures isolated per script so one bad body doesn't block the - // other deploys. - const results = await Promise.allSettled( - entries.map(async ([path, d]) => { - await saveDraft(path, d, ws) - return path - }) - ) - for (let i = 0; i < results.length; i++) { - const r = results[i] - const [path] = entries[i] - if (r.status === 'fulfilled') { - savedPaths.push(path) - } else { - const e: any = r.reason - errors.set(path, e?.body ?? e?.message ?? String(e)) - } - } - // Drop the saved drafts from the map; failed ones stay so the user - // can fix them and retry. Build the new map from the still-failing - // entries to keep insertion order stable. - if (savedPaths.length > 0) { - const next = new Map<string, Draft>() - for (const [k, v] of pe.drafts) { - if (!savedPaths.includes(k)) next.set(k, v) - } - pe.drafts = next - // If the open draft just got deployed, transfer the focus to - // its now-persisted runnable so the pane stays on the same - // script the user was editing — otherwise the pane closes, - // the canvas re-fits, and the user has to re-find their - // script after every save. - if (pe.activeDraftPath && savedPaths.includes(pe.activeDraftPath)) { - pe.selection = { - kind: 'runnable', - runnable_kind: 'script', - path: pe.activeDraftPath - } - pe.activeDraftPath = undefined - } + const predicted = predictCascadeFacts([...pe.drafts.keys()]) + const { savedPaths, savedTriggers, errors } = await deployPipelineDrafts(pe, $workspaceStore) + if (savedPaths.length > 0 || savedTriggers.length > 0) { await graphRes.refetch() // Verify only what actually deployed — failed drafts would // otherwise false-positive as "missing" rows. reportDeployDrift(new Map([...predicted].filter(([p]) => savedPaths.includes(p)))) } saveErrors = errors + if (errors.size > 0) saveErrorsOpen = true savingAll = false - if (savedPaths.length > 0 && errors.size === 0) { - sendUserToast(`Saved ${savedPaths.length} draft${savedPaths.length === 1 ? '' : 's'}`) - } else if (savedPaths.length > 0 && errors.size > 0) { - sendUserToast(`Saved ${savedPaths.length}, ${errors.size} failed — see details`, true) + const savedCount = savedPaths.length + savedTriggers.length + if (savedCount > 0 && errors.size === 0) { + sendUserToast(`Saved ${savedCount} draft${savedCount === 1 ? '' : 's'}`) + } else if (savedCount > 0 && errors.size > 0) { + sendUserToast(`Saved ${savedCount}, ${errors.size} failed — see details`, true) } else if (errors.size > 0) { sendUserToast(`${errors.size} draft${errors.size === 1 ? '' : 's'} failed to save`, true) } @@ -759,6 +733,7 @@ next.delete(path) pe.drafts = next forgetPath(path) + pe.discardTriggerDraftsFor(path) } function clearSaveError(path: string) { @@ -768,13 +743,13 @@ saveErrors = next } - // "This path is gone" cleanup. The three big inferred-* / annotated-* - // maps used to live here too, but they're now derived from - // `bodiesByPath` × `g.runnables` — entries for missing paths drop out - // implicitly when `g.runnables` no longer mentions them, so the only - // things left to flush are the live overlays for the open pane + the - // selection + per-path save errors. `bodiesByPath` keeps its entry - // (only-add cache, harmless if stale). + function forgetScriptCache(...paths: string[]) { + assetPrefetch.forget(...paths) + } + + // "This path is gone" cleanup: the live overlays for the open pane, the + // selection and per-path save errors. The prefetched edge maps need nothing, + // being derived over the current graph's scripts. function forgetPath(path: string) { if (pe.activeDraftPath === path) pe.activeDraftPath = undefined if (pe.selection?.kind === 'runnable' && pe.selection.path === path) { @@ -801,6 +776,8 @@ const draft = pe.drafts.get(oldPath) if (!draft) return 'Draft not found' if (pe.drafts.has(newPath)) return 'Another draft already uses this path' + const clash = pe.retargetTriggerDrafts(oldPath, newPath) + if (clash) return `Its draft trigger would be renamed to ${clash}, which another draft uses` const next = new Map<string, Draft>() // Preserve insertion order: replace the entry at its original // position so the canvas / lists don't reshuffle on rename. @@ -902,7 +879,7 @@ const draft = pe.drafts.get(path) if (!draft) break try { - await saveDraft(path, draft, $workspaceStore) + await deployPipelineScript(draft, $workspaceStore) // Archive the previously-deployed intermediate path (if // any) — a double-rename otherwise leaves it as an // orphan script visible on the canvas as a "deployed" @@ -952,6 +929,7 @@ const nextErrors = new Map(saveErrors) nextErrors.set(path, msg) saveErrors = nextErrors + saveErrorsOpen = true } // Pick up the next queued rename, if any. const next = state.queuedPath @@ -1019,6 +997,7 @@ // template can gate them per-mode with simple ternaries — the canvas // hides each affordance when its callback is undefined. function handleCanvasSelect(s: AssetGraphSelection | undefined) { + uploadInputsPath = undefined // Clicking a node while the pane is explicitly hidden is a request // to see that node — unhide. Background clicks (s == undefined) // keep the hidden state. @@ -1050,9 +1029,10 @@ language: ScriptLang, scriptPath: string, outputKind: PipelineOutputKind, - aiPrompt?: string + aiPrompt?: string, + options?: PipelineInsertOptions ) { - const ref = `${ASSET_PREFIX[asset.kind]}${asset.path}` + const ref = assetRef(asset) openMaterializerDraft( language, scriptPath, @@ -1062,7 +1042,8 @@ kind: asset.kind, path: asset.path }, - aiPrompt + aiPrompt, + options ) } function handleAddPipelineScript( @@ -1070,10 +1051,307 @@ scriptPath: string, source: { kind: NativeTriggerKind; path: string | undefined }, outputKind: PipelineOutputKind, - aiPrompt?: string + aiPrompt?: string, + options?: PipelineInsertOptions ) { - openMaterializerDraft(language, scriptPath, [source], outputKind, undefined, aiPrompt) + openMaterializerDraft(language, scriptPath, [source], outputKind, undefined, aiPrompt, options) + // A schedule was configured by the wizard itself; other row-backed kinds + // are configured in their own editor, as a draft of the new script. + if (source.kind !== 'schedule' && isDraftableTriggerKind(source.kind)) { + openTriggerDraft(source.kind, scriptPath) + } } + // Assets-only "Delete N items": one confirmation, then the trigger and the + // script, each discarded if it is a draft and deleted if it is deployed. + let assetDeleteTarget = $state<AssetUpstreamDelete | undefined>(undefined) + let assetDeleteLoading = $state(false) + // Permanent script deletion is admin-only, as in the pane's own remove modal; + // everyone else archives it. + let canHardDeleteScripts = $derived(!!($userStore?.is_admin || $userStore?.is_super_admin)) + async function confirmAssetUpstreamDelete() { + const target = assetDeleteTarget + const ws = $workspaceStore + if (!target || !ws) return + assetDeleteLoading = true + const { script, trigger } = target + const n = (script ? 1 : 0) + (trigger ? 1 : 0) + try { + // The script first: when it is refused, nothing else has changed. + if (script) await removeScript(script, ws) + } catch (e: any) { + sendUserToast(`Could not remove ${script?.path}: ${e?.body ?? e?.message ?? String(e)}`, true) + assetDeleteLoading = false + return + } + try { + if (trigger) { + const key = triggerDraftKey(trigger.kind, trigger.path) + if (pe.triggerDrafts.has(key)) pe.discardTriggerDraft(key) + if (!trigger.draft) await deleteTriggerRow(trigger.kind, trigger.path, ws) + } + sendUserToast(`Removed ${n} item${n === 1 ? '' : 's'}`) + } catch (e: any) { + sendUserToast( + `${script ? `Removed ${script.path}, but not its` : 'Could not remove the'} ${trigger?.kind} trigger ${trigger?.path}: ${e?.body ?? e?.message ?? String(e)}`, + true + ) + } finally { + assetDeleteTarget = undefined + assetDeleteLoading = false + await graphRes.refetch() + } + } + async function removeScript(script: { path: string }, ws: string) { + const deployed = graphRes.current?.runnables.some( + (r) => r.path === script.path && !r.unsaved + ) + if (deployed) { + if (canHardDeleteScripts) { + await ScriptService.deleteScriptByPath({ workspace: ws, path: script.path }) + } else { + await ScriptService.archiveScriptByPath({ workspace: ws, path: script.path }) + } + } + if (pe.drafts.has(script.path)) discardDraft(script.path) + if (deployed) { + pe.discardTriggerDraftsFor(script.path) + forgetPath(script.path) + forgetScriptCache(script.path) + } + } + + // ===================== Fixes for misconfigured nodes ===================== + // Rewrites a script's annotation header and keeps the result as a draft, opened + // so the change is in view. The pane closes first and its buffer is saved back + // before the content is read: saved back after the edit, it would overwrite it. + async function editScriptHeader( + path: string, + apply: (content: string) => string, + done: string + ): Promise<boolean> { + const ws = $workspaceStore + if (!ws) return false + // Wait for Edit: the switch reopens Edit's set-aside pane when it lands, which + // would take the place of the draft opened below. + if (mode !== 'edit') await setMode('edit') + pe.selection = undefined + pe.activeDraftPath = undefined + await tick() + await new Promise<void>((r) => queueMicrotask(r)) + const draft = pe.drafts.get(path) + let script: Script + try { + script = draft + ? draft.script + : await ScriptService.getScriptByPath({ workspace: ws, path }) + } catch (e: any) { + sendUserToast(`Could not open ${path}: ${e?.body ?? e?.message ?? String(e)}`, true) + return false + } + panelHidden = false + const content = apply(script.content ?? '') + if (content === script.content) { + pe.activeDraftPath = draft ? path : undefined + if (!draft) pe.selection = { kind: 'runnable', runnable_kind: 'script', path } + sendUserToast(`${path} already does that`) + return true + } + const next = new Map(pe.drafts) + next.set(path, { + ...(draft ?? { localId: pe.promotedDraftLocalId(path) }), + script: { ...script, content } + }) + pe.drafts = next + pe.activeDraftPath = path + sendUserToast(`${done} in ${path}. It is a draft until you save.`) + return true + } + + // Edits several scripts' headers at once, after the user has seen the list: a + // change to one edge or node must not silently rewrite scripts they didn't pick. + let multiEdit = $state<{ scripts: string[]; what: string; run: () => Promise<void> } | undefined>( + undefined + ) + function editScripts( + scripts: string[], + what: string, + apply: (script: string) => (content: string) => string + ) { + const run = async () => { + for (const s of scripts) await editScriptHeader(s, apply(s), what) + } + if (scripts.length > 1) multiEdit = { scripts, what, run } + else void run() + } + + const scriptName = (p: string) => p.split('/').pop() ?? p + + const readsAsset = (script: string, asset: { kind: AssetKind; path: string }) => + shownGraph.edges.some( + (e) => + e.runnable_path === script && + e.asset_kind === asset.kind && + e.asset_path === asset.path && + (e.access_type === 'r' || e.access_type === 'rw') + ) + const selectScript = (path: string) => { + pe.activeDraftPath = pe.drafts.has(path) ? path : undefined + pe.selection = pe.drafts.has(path) + ? undefined + : { kind: 'runnable', runnable_kind: 'script', path } + } + const selectAsset = (asset: { kind: AssetKind; path: string }) => { + pe.activeDraftPath = undefined + pe.selection = { kind: 'asset', asset_kind: asset.kind, path: asset.path } + } + const scriptLink = (path: string) => ({ text: path, onClick: () => selectScript(path) }) + const assetLink = (asset: { kind: AssetKind; path: string }) => ({ + text: asset.path, + onClick: () => selectAsset(asset) + }) + + let nodeFixes = $derived.by(() => { + const fixes = new Map<string, NodeFixSpec>() + if (isOperator) return fixes + for (const [path, asset] of nodeErrors.waitsOn) { + fixes.set(`script:${path}`, { + explainer: [ + 'Runs after each write to ', + // Not drawn when only this subscription names it: nothing to select. + shownGraph.edges.some( + (e) => e.asset_kind === asset.kind && e.asset_path === asset.path + ) + ? assetLink(asset) + : asset.path, + ', but nothing writes it, so it never runs.' + ], + actions: [ + { + label: `Remove \`on ${assetRef(asset)}\``, + detail: `${stopListeningChangeText(asset, readsAsset(path, asset))} in ${path}; only the annotation header changes. Saved as a draft.`, + run: () => + editScriptHeader( + path, + (c) => stopListeningToAsset(c, asset, readsAsset(path, asset)), + `Removed \`on ${assetRef(asset)}\`` + ) + }, + { + label: 'Open script', + run: () => { + pe.activeDraftPath = pe.drafts.has(path) ? path : undefined + pe.selection = pe.drafts.has(path) + ? undefined + : { kind: 'runnable', runnable_kind: 'script', path } + } + } + ] + }) + } + for (const [path, why] of nodeErrors.untriggered) { + const unsaved = displayGraph.runnables.some((r) => r.path === path && r.unsaved) + fixes.set(`script:${path}`, { + explainer: [ + 'Nothing starts ', + scriptLink(path), + why === 'no-trigger' + ? ': it has no trigger, so it only runs by hand.' + : ': it only runs after writes to tables it reads, and nothing writes them, so it only runs by hand.' + ], + actions: [ + { + label: 'Run it on a schedule', + detail: `Opens the schedule setup. On create: adds \`on schedule\` in ${path}, with the schedule as a draft.`, + scheduleFor: { + script: path, + onSchedule: async (schedule) => { + // Checked first: a header saying `on schedule` with no schedule + // behind it would be a new error, not a fix. + if (pe.triggerDrafts.has(triggerDraftKey('schedule', schedule.path))) { + sendUserToast( + `Another draft schedule already uses the path ${schedule.path}`, + true + ) + return + } + const ok = await editScriptHeader( + path, + (c) => addTriggerDirective(c, 'schedule'), + 'Added a schedule' + ) + if (!ok) return + if (!pe.setTriggerDraft({ kind: 'schedule', config: { ...schedule, script_path: path } })) { + sendUserToast( + `Another draft schedule already uses the path ${schedule.path}; ${path} has no schedule yet`, + true + ) + } + } + } + }, + { + label: 'Run it from a webhook', + detail: `Adds \`on webhook\` in ${path}: it runs when its webhook URL is called. Saved as a draft.`, + run: () => + editScriptHeader(path, (c) => addTriggerDirective(c, 'webhook'), 'Added a webhook') + }, + { + label: unsaved ? 'Discard it' : 'Remove it', + detail: unsaved + ? 'Drops the draft.' + : 'Opens its archive or delete confirmation.', + run: async () => { + if (mode !== 'edit') await setMode('edit') + // The pane takes the remove request only once it is open on the + // script: a request made as it mounts is its starting point. + if (!unsaved) { + panelHidden = false + pe.activeDraftPath = undefined + pe.selection = { kind: 'runnable', runnable_kind: 'script', path } + await tick() + } + handleRunnableMenuRemove({ runnable_kind: 'script', path, unsaved }) + } + } + ] + }) + } + for (const t of displayGraph.triggers) { + if (t.trigger_kind === 'asset' || !t.missing) continue + if (t.trigger_kind === 'webhook' || t.trigger_kind === 'data_upload') continue + const kind = t.trigger_kind + const script = t.runnable_path + const label = TRIGGER_NODE_STYLE[kind]?.label ?? kind + fixes.set(`trigger:${kind}:missing:${script}`, { + explainer: [ + scriptLink(script), + ` declares \`on ${kind}\`, but no ${label} trigger points at it, so nothing starts it that way.` + ], + actions: [ + { + label: `Create the ${label} trigger`, + detail: 'Opens its editor. It is created when you save the pipeline.', + run: () => { + if (mode !== 'edit') setMode('edit') + openMissingTriggerDrawer(kind, script) + } + }, + { + label: `Remove \`on ${kind}\` from ${scriptName(script)}`, + detail: `Edits ${script}. Saved as a draft.`, + run: () => + editScriptHeader( + script, + (c) => removeTriggerDirective(c, kind), + `Removed \`on ${kind}\`` + ) + } + ] + }) + } + return fixes + }) + function handleRunnableMenuRemove(info: { runnable_kind: 'script' | 'flow' path: string @@ -1227,7 +1505,8 @@ liveAnnotations: pe.liveAnnotations, inferredWritesByPath, inferredReadsByPath, - annotatedNativeKindsByPath + annotatedNativeKindsByPath, + triggerDrafts: pe.triggerDrafts.values() }) ) @@ -1250,7 +1529,166 @@ // What the canvas renders: drafts merged in edit, deployed-only in view — // unless the "show drafts" chip is on, which overlays the drafts onto the // view (what View will show once they're deployed). - let displayGraph = $derived(mode === 'edit' || includeDrafts ? graphWithDraft : deployedGraph) + let shownGraph = $derived(mode === 'edit' || includeDrafts ? graphWithDraft : deployedGraph) + // Each script's explicit `// on <asset>` subscriptions, from its live buffer, + // draft or deployed body. + let explicitOnByPath = $derived.by(() => { + const showDrafts = mode === 'edit' || includeDrafts + const out = new Map<string, Array<{ kind: AssetKind; path: string }>>() + for (const r of shownGraph.runnables) { + if (r.usage_kind !== 'script') continue + const live = + showDrafts && pe.liveAnnotations.scriptPath === r.path ? pe.liveAnnotations : undefined + const content = showDrafts ? pe.drafts.get(r.path)?.script.content : undefined + const body = content ?? assetPrefetch.bodies.get(r.path) + const refs = live + ? live.annotations.triggerAssets + : body !== undefined + ? parsePipelineAnnotations(body).triggerAssets + : [] + if (refs.length > 0) out.set(r.path, refs) + } + return out + }) + // Assets an asset trigger waits on (explicit `on`, or an auto-triggering read) + // that nothing in the pipeline writes, checked against the whole workspace: an + // asset trigger fires on a write from anywhere. + // Every other asset nothing in the pipeline writes is looked up too, so an + // asset nothing writes anywhere can go without the "add downstream step" +. + let writtenInPipeline = $derived( + new Set( + shownGraph.edges + .filter( + (e) => + e.runnable_kind === 'script' && (e.access_type === 'w' || e.access_type === 'rw') + ) + .map((e) => `${e.asset_kind}:${e.asset_path}`) + ) + ) + // dbt builds its models; its sources come from elsewhere, like any other asset. + const dbtBuilt = (a: { dbt?: { resource_type?: string } | null }) => + !!a.dbt && a.dbt.resource_type !== 'source' + let unwrittenInPipeline = $derived( + [ + ...new Set([ + ...pipelineNodeErrors(shownGraph, explicitOnByPath).unwrittenTriggerAssets, + ...shownGraph.assets + .filter((a) => !dbtBuilt(a) && !writtenInPipeline.has(`${a.kind}:${a.path}`)) + .map((a) => `${a.kind}:${a.path}`) + ]) + ] + .sort() + .join('\n') + ) + // Whether a script outside the pipeline writes each asset (a flow's write fires + // no asset trigger). One lookup per asset, bounded, and remembered per + // `kind:path` so editing the graph only asks about assets it has not seen. + const writerLookups = new Map<string, Promise<boolean | undefined>>() + const writerLimit = pLimit(6) + function writtenInWorkspace(ws: string, key: string): Promise<boolean | undefined> { + const cacheKey = `${ws}\n${key}` + let p = writerLookups.get(cacheKey) + if (!p) { + const i = key.indexOf(':') + const kind = key.slice(0, i) + const path = key.slice(i + 1) + p = writerLimit(async () => { + try { + const res = await AssetService.listAssets({ workspace: ws, path, assetKinds: kind }) + return res.assets.some((a) => + a.usages.some( + (u) => u.kind === 'script' && (u.access_type === 'w' || u.access_type === 'rw') + ) + ) + } catch { + // Unknown: the node stays flagged, and the next graph change asks again. + writerLookups.delete(cacheKey) + return undefined + } + }) + writerLookups.set(cacheKey, p) + } + return p + } + let writtenElsewhere = resource( + [() => $workspaceStore, () => unwrittenInPipeline], + async ([ws, keys]) => { + const out = new Set<string>() + if (!ws || !keys) return out + const list = keys.split('\n') + const found = await Promise.all(list.map((key) => writtenInWorkspace(ws, key))) + list.forEach((key, i) => found[i] && out.add(key)) + return out + } + ) + // Until the lookup answers for the assets it is asking about, they count as + // written: a node turns red only once nothing is known to write them, never + // for the moment the answer is in flight. + let nodeErrors = $derived.by(() => { + const errors = pipelineNodeErrors( + shownGraph, + explicitOnByPath, + writtenElsewhere.loading || !writtenElsewhere.current + ? new Set([...(writtenElsewhere.current ?? []), ...unwrittenInPipeline.split('\n')]) + : writtenElsewhere.current + ) + // A webhook or data upload trigger is read from the script's body, which loads + // after the graph: until it has, "nothing starts it" may only mean "not read yet". + for (const path of [...errors.untriggered.keys()]) { + if (pe.drafts.has(path) || assetPrefetch.bodies.has(path)) continue + errors.untriggered.delete(path) + errors.scripts.delete(path) + } + return errors + }) + let displayGraph = $derived(withSummaries(shownGraph)) + // Adds what the canvas shows but the resolved graph does not carry: script + // summaries and languages, schedule crons, and which nodes are misconfigured. + function withSummaries(g: AssetGraphResponse): AssetGraphResponse { + const showDrafts = mode === 'edit' || includeDrafts + const errors = nodeErrors + const schedules = scheduleInfo.current + // An asset drawn only because a script subscribes to it, which nothing ever + // writes, stands for nothing: it is left out, and the subscriber carries the + // error. One a script reads or writes stays. + const used = new Set(g.edges.map((e) => `${e.asset_kind}:${e.asset_path}`)) + const phantom = new Set([...errors.unwritten.keys()].filter((k) => !used.has(k))) + const triggers = g.triggers.filter( + (t) => t.trigger_kind !== 'asset' || !phantom.has(`${t.asset_kind}:${t.asset_path}`) + ) + return { + ...g, + triggers: schedules?.size + ? triggers.map((t) => + t.trigger_kind === 'schedule' && t.path && !t.draft && schedules.has(t.path) + ? { ...t, ...schedules.get(t.path) } + : t + ) + : triggers, + assets: g.assets + .filter((a) => !phantom.has(`${a.kind}:${a.path}`)) + .map((a) => { + const key = `${a.kind}:${a.path}` + const error = errors.assets.get(key) + // Only once the workspace lookup has answered: before, it is unknown. + const never_written = + !dbtBuilt(a) && + !writtenInPipeline.has(key) && + !!writtenElsewhere.current && + !writtenElsewhere.loading && + !writtenElsewhere.current.has(key) + return error || never_written ? { ...a, error, never_written } : a + }), + runnables: g.runnables.map((r) => { + const draft = showDrafts ? pe.drafts.get(r.path)?.script : undefined + const meta = assetPrefetch.scriptMeta.get(r.path) + const summary = draft?.summary || meta?.summary + const language = draft?.language ?? meta?.language + const error = r.usage_kind === 'script' ? errors.scripts.get(r.path) : undefined + return summary || language || error ? { ...r, summary, language, error } : r + }) + } + } // Leaving edit mode: drop the live editor overlays — they substitute the // last keystroke buffer for one script inside inferredWritesByPath / @@ -1486,7 +1924,7 @@ // data_upload) receives its input from the live event or request at dispatch // time — a message, an HTTP body, an uploaded file — which doesn't exist // during a manual run, so there's nothing to default and those scripts run - // empty (data_upload being fed its staged file instead, see dataUploadArgs). + // empty (data_upload being fed its staged file instead, see dataUploads). // Resolved on demand right before a run (schedule args aren't in the graph // response); fail-safe — a schedule we can't fetch just contributes nothing. let scheduleArgsByPath: Record<string, Record<string, any>> = {} @@ -1532,7 +1970,7 @@ // data-upload entry's staged file override. runWholePipeline already // refused to start unless every data-upload entry is staged, so this is // always the intended input. - const staged = { ...(scheduleArgsByPath[path] ?? {}), ...(dataUploadArgs[path]?.args ?? {}) } + const staged = { ...(scheduleArgsByPath[path] ?? {}), ...(dataUploads.argsFor(path) ?? {}) } const draft = mode === 'edit' || includeDrafts ? pe.drafts.get(path) : undefined if (draft) { if (!draft.script.content || !draft.script.language) { @@ -1848,70 +2286,8 @@ } } - // Staged run-form input for data-upload entry scripts, keyed by path. Lifted - // out of the (transient, per-selection) run form so the uploaded/entered data - // persists across selection changes — it drives each entry node's green - // "ready" state and seeds the whole-pipeline run with that input. `valid` is - // the run form's full-schema validity (all required fields satisfied). - let dataUploadArgs = $state<Record<string, { args: Record<string, any>; valid: boolean }>>({}) - - // An S3Object-shaped value (the file picker writes `{ s3: '<path>' }`). - function isS3Object(v: any): boolean { - return !!v && typeof v === 'object' && !Array.isArray(v) && 's3' in v - } - // Whether a staged value carries actual data. Covers the two shapes a - // data-upload entry takes: an S3Object (file picker → `{ s3: '<path>' }`) and - // a plain required input (e.g. a JSON array pasted into the run form). - function hasMeaningfulValue(v: any): boolean { - if (v == null) return false - if (typeof v === 'string') return v.length > 0 - if (Array.isArray(v)) return v.length > 0 - if (typeof v === 'object') - return isS3Object(v) ? typeof v.s3 === 'string' && v.s3.length > 0 : Object.keys(v).length > 0 - return true // numbers / booleans count as provided - } - // A data-upload entry is ready once the user actually provided its data, not - // just opened the form. Two guards: the form's own full-schema `valid` (every - // required field — including non-file ones — is satisfied), AND that any - // declared S3Object file field actually carries a file (the picker can leave - // an empty `{ s3: '' }` on a non-required file field, which `valid` alone - // wouldn't catch). - function dataUploadReady(path: string): boolean { - const staged = dataUploadArgs[path] - if (!staged || !staged.valid) return false - const values = Object.values(staged.args) - const s3s = values.filter(isS3Object) - if (s3s.length > 0) return s3s.every(hasMeaningfulValue) - return values.some(hasMeaningfulValue) - } - // Persist the run form's args + validity, but only for data-upload entries — - // other run forms (partitioned producers) run their own way and must not be - // mistaken for a staged upload. Idempotent: the run form re-emits on every - // keystroke/validation pass, so bail when the value is unchanged — otherwise - // each emit would reassign `dataUploadArgs`, giving `readyDataUploadPaths` a - // fresh Set identity that re-syncs the canvas and re-fires the form's emit - // effect (effect_update_depth_exceeded). - function stageRunFormArgs(path: string, args: Record<string, any>, valid: boolean) { - if (!dataUploadEntryPaths.has(path)) return - const prev = dataUploadArgs[path] - if (prev && prev.valid === valid && JSON.stringify(prev.args) === JSON.stringify(args)) return - dataUploadArgs = { ...dataUploadArgs, [path]: { args, valid } } - } - // Pipeline scripts that are data-upload entry points (a `data_upload` trigger - // in the displayed graph). They can't auto-run — they need an uploaded file - // before the pipeline can go (see runWholePipeline's gate + the node's green - // state). - let dataUploadEntryPaths = $derived( - new Set( - displayGraph.triggers - .filter((t) => t.trigger_kind === 'data_upload' && t.runnable_kind === 'script') - .map((t) => t.runnable_path) - ) - ) - // Of those, the ones with a staged file — drives the green node treatment. - let readyDataUploadPaths = $derived( - new Set([...dataUploadEntryPaths].filter((p) => dataUploadReady(p))) - ) + // Data-upload entries' staged input; see usePipelineDataUploads. + const dataUploads = usePipelineDataUploads(() => displayGraph) // Every pipeline-member script, for the always-visible header "Run pipeline" // control. Per-node runs are hover/select-gated on the canvas; this @@ -1934,7 +2310,7 @@ // point the user at the first unready node instead of launching a doomed // run. const unready = allPipelineScripts.filter( - (p) => dataUploadEntryPaths.has(p) && !dataUploadReady(p) + (p) => dataUploads.entryPaths.has(p) && !dataUploads.isReady(p) ) if (unready.length > 0) { sendUserToast( @@ -2141,7 +2517,52 @@ // auto-generated run form (the script declares an `S3Object` input, so the // form renders the S3 picker) lets the user upload a file and run the // pipeline. Drafts open in-place too so the user can fill the body first. + // A data-upload click opens the node on its inputs alone; any other selection + // (or "Open script") goes back to the script. + let uploadInputsPath = $state<string | undefined>(undefined) + // Runs the open node with its form inputs: a draft previews its own content, a + // deployed script runs for real (in view mode, cascading like any legit run). + // `live` is the pane's buffer when it differs from what is stored (a draft, or a + // deployed node edited before switching to the inputs view): it is previewed. + async function runUploadInputs( + path: string, + args: Record<string, any>, + live?: { content: string; language: ScriptLang } + ): Promise<string | undefined> { + const draft = mode === 'edit' ? pe.drafts.get(path) : undefined + const body = + mode === 'edit' + ? (live ?? (draft && { content: draft.script.content, language: draft.script.language })) + : undefined + if (!body) return mode === 'edit' ? runDeployedWithArgs(path, args) : runByPathLegit(path, args) + if (!$workspaceStore || !body.content || !body.language) return undefined + activeRunnables.arm(`script:${path}`) + try { + const jobId = await JobService.runScriptPreview({ + workspace: $workspaceStore, + requestBody: { + content: body.content, + language: body.language, + path, + args: { ...args, _wmill_skip_asset_dispatch: true } + } + }) + runsPendingJobId = jobId + runsRefreshKey++ + activeRunnable = { kind: 'script', path } + activeRunnableJobId = jobId + return jobId + } catch (e: any) { + sendUserToast(`Run failed: ${e?.body ?? e?.message ?? e}`, true) + return undefined + } + } + // Same as a canvas run of a deployed node in edit mode: this step only. + function runDeployedWithArgs(path: string, args: Record<string, any>) { + return runByPathLegit(path, { ...args, _wmill_skip_asset_dispatch: true }) + } function openDataUploadRun(scriptPath: string) { + uploadInputsPath = scriptPath // Opening the run form is meaningless while the pane is hidden — // unhide first, same as a plain node click. panelHidden = false @@ -2168,6 +2589,12 @@ // time or silently bind to nothing. Surface that as a toast and // keep the drawer closed; the user needs to save the script first // (which also creates it under the new path if they renamed it). + // Kinds with a trigger row can instead wait as a pipeline draft and + // deploy with the pipeline, after the script. + if (isDraftableTriggerKind(kind) && pe.drafts.has(scriptPath)) { + openTriggerDraft(kind, scriptPath) + return + } if (pe.drafts.has(scriptPath)) { sendUserToast( `Save the script "${scriptPath}" first — triggers can only be attached to deployed scripts.`, @@ -2183,13 +2610,42 @@ // can still be edited everywhere else (TriggersPanel, etc.) where the // picker stays editable. function deleteAttachedTrigger(kind: NativeTriggerKind, triggerPath: string) { + const key = triggerDraftKey(kind, triggerPath) + if (pe.triggerDrafts.has(key)) { + pe.discardTriggerDraft(key) + return + } triggerEditors?.requestDelete(kind, triggerPath) } function openEditTriggerDrawer(kind: NativeTriggerKind, triggerPath: string, scriptPath: string) { + const draft = pe.triggerDrafts.get(triggerDraftKey(kind, triggerPath)) + if (draft) { + openTriggerDraft(draft.kind, scriptPath, draft) + return + } triggerEditors?.openEdit(kind, triggerPath, scriptPath) } + /** The kind's editor over a new draft, or over `draft` when re-editing one. */ + function openTriggerDraft( + kind: PipelineTriggerDraftKind, + scriptPath: string, + draft?: PipelineTriggerDraft + ) { + const defaults = { path: defaultTriggerPath(scriptPath, kind) } + triggerEditors?.openTriggerDraft(kind, scriptPath, defaults, draft?.config, (cfg) => { + const { extra_perms: _, ...config } = cfg + const saved = pe.setTriggerDraft( + { kind, config: { ...config, path: cfg.path, script_path: scriptPath, is_flow: false } }, + // The editor's Path field can rename it; drafts are keyed by path. + draft ? triggerDraftKey(kind, draft.config.path) : undefined + ) + if (!saved) sendUserToast(`Another draft trigger already uses the path ${cfg.path}`, true) + return saved + }) + } + // Reuse the empty AssetGraphResponse so we can still render the canvas // (layout, controls, mini-map) on a fresh pipeline. const EMPTY_GRAPH: AssetGraphResponse = { @@ -2230,7 +2686,7 @@ displayName: `f/${p.folder}`, icon: Folder, disabled: false, - action: () => goto(`${base}/pipeline/${encodeURIComponent(p.folder)}${modeQuery}`) + action: () => goto(`/pipeline/${encodeURIComponent(p.folder)}${modeQuery}`) })) items.push({ displayName: 'Choose another folder…', @@ -2277,6 +2733,35 @@ } ) + // Cron, zone and summary of the deployed schedules on the graph, for their nodes' + // labels. Re-read with every graph load, so an edit in the schedule drawer shows. + let scheduleInfo = resource( + [() => $workspaceStore, () => graphRes.current], + async ([ws, g]) => { + const info = new Map<string, { schedule: string; timezone: string; summary?: string }>() + if (!ws || !g) return info + const paths = new Set<string>() + for (const t of g.triggers) { + if (t.trigger_kind === 'schedule' && t.path && !t.missing) paths.add(t.path) + } + await Promise.all( + [...paths].map(async (path) => { + try { + const s = await ScheduleService.getSchedule({ workspace: ws, path }) + info.set(path, { + schedule: s.schedule, + timezone: s.timezone, + summary: s.summary || undefined + }) + } catch { + // Unreadable schedule: its node keeps the plain "Schedule" label. + } + }) + ) + return info + } + ) + // Folder whose graph is actually rendered. `graphRes.current` is stale- // while-revalidate on an in-place folder switch, so keying the canvas's // one-shot initial fit on the route param would fire the new folder's fit @@ -2287,64 +2772,6 @@ if (graphRes.current) untrack(() => (viewportFitFolder = folder)) }) - // Body / inferred-assets prefetch sweep. Watches `g.runnables`; for any - // non-draft path we haven't fetched yet, fetches `getScriptByPath` and - // `inferAssets`, and stores both in their respective only-add caches. - // All three previously-sticky maps (`inferredWritesByPath`, - // `inferredReadsByPath`, `annotatedNativeKindsByPath`) are now derived - // from these caches × the current graph, so rename / delete cleanup - // happens implicitly when `g.runnables` changes — no per-mutation - // cache surgery needed. A generation counter cancels in-flight work on - // folder change so the previous folder's results never leak into the - // new one. - let prefetchingAssets = $state(false) - $effect(() => { - const ws = $workspaceStore - const g = graphRes.current - if (!ws || !g) return - const gen = ++bodyFetchGen - const targets = untrack(() => - g.runnables - .filter((r) => r.usage_kind === 'script') - .map((r) => r.path) - .filter((p) => !pe.drafts.has(p) && !bodiesByPath.has(p)) - ) - if (targets.length === 0) return - let i = 0 - const POOL = 6 - const worker = async () => { - while (i < targets.length && gen === bodyFetchGen) { - const path = targets[i++] - try { - const s = await ScriptService.getScriptByPath({ workspace: ws, path }) - if (gen !== bodyFetchGen) return - const content = s.content ?? '' - const res = await inferAssets(s.language, content) - if (gen !== bodyFetchGen) return - const inferred = (res?.assets ?? []) as AssetWithAltAccessType[] - untrack(() => { - if (!bodiesByPath.has(path)) { - const nextBodies = new Map(bodiesByPath) - nextBodies.set(path, content) - bodiesByPath = nextBodies - } - if (!inferredAssetsByPath.has(path)) { - const nextAssets = new Map(inferredAssetsByPath) - nextAssets.set(path, inferred) - inferredAssetsByPath = nextAssets - } - }) - } catch { - // Skip — that node just falls back to base-graph edges. - } - } - } - prefetchingAssets = true - const pool = Array.from({ length: Math.min(POOL, targets.length) }, () => worker()) - void Promise.all(pool).then(() => { - if (gen === bodyFetchGen) prefetchingAssets = false - }) - }) function pluralize(n: number, singular: string): string { return `${n} ${singular}${n === 1 ? '' : 's'}` @@ -2386,210 +2813,169 @@ <title>Pipeline · {folder} — Windmill - -{#snippet pipelineFolder()} - - {:else} {#snippet buttonReplacement()} - - - f/{folder} - - + {@render folderSegment()} {/snippet} {/if} {#if summary.length > 0} - · {summary.join(' · ')} + {summary.join(' · ')} + {/if} + {#if mode === 'edit' && $workspaceStore} + + {/if} {/snippet} {#snippet pipelineActions()} + being pushed off the end. `actionsFlexible` on the registration is what lets this box + shrink far enough for that to matter. -->
{#if !isOperator} - -
- setMode(m)} /> - {#if mode === 'view' && pe.drafts.size > 0} + +
+ setMode(m)} /> + {#if mode === 'view' && pendingCount > 0} - + {pendingCount} draft{pendingCount === 1 ? '' : 's'} + {/if}
{/if} - {#if !isOperator && allPipelineScripts.length > 0} - - {#if recordingMode} - - {/if} - - - {/if} - {#if mode === 'edit' && saveErrors.size > 0} - - - {#snippet trigger()} + {#if !isOperator && allPipelineScripts.length > 0} + + {#if recordingMode} - {/snippet} - {#snippet content()} -
- Save errors -
- {#each [...saveErrors.entries()] as [path, message]} -
- {path} - - {message} - -
- {/each} -
-
- {/snippet} -
- {/if} - {#if mode === 'edit' && pe.drafts.size > 0} - - {#if $workspaceStore} - + {/if} + + {/if} + {#if mode === 'edit' && saveErrors.size > 0} + + {/if} + {#if mode === 'edit' && pendingCount > 0} + + {/if} + {#if mode === 'view'} + + {/if} + - {/if} - {#if mode === 'view'} - - {/if} -
{/snippet} @@ -2617,7 +3003,7 @@ defaultPathSuffix={DEFAULT_PATH_SUFFIX} {panelHidden} onTogglePanelHidden={() => (panelHidden = !panelHidden)} - {prefetchingAssets} + prefetchingAssets={assetPrefetch.prefetching} hoveredPaths={activityHoverPaths} selectedRunPaths={activitySelectPaths} {activeRunnable} @@ -2636,13 +3022,59 @@ onDeleteTrigger={mode === 'edit' ? deleteAttachedTrigger : undefined} onOpenWebhook={openWebhookDrawer} onOpenDataUpload={openDataUploadRun} - {readyDataUploadPaths} - runFormInitialArgs={openScriptPath ? dataUploadArgs[openScriptPath]?.args : undefined} - onRunFormArgsChange={stageRunFormArgs} + readyDataUploadPaths={dataUploads.readyPaths} + runFormInitialArgs={openScriptPath ? dataUploads.argsFor(openScriptPath) : undefined} + onRunFormArgsChange={dataUploads.stage} + inputsOnly={uploadInputsPath !== undefined && + (openScriptPath === undefined || uploadInputsPath === openScriptPath)} + onRunInputs={runUploadInputs} + onShowScript={() => (uploadInputsPath = undefined)} onSelect={handleCanvasSelect} onAddScriptForAsset={mode === 'edit' ? handleAddScriptForAsset : undefined} onAddPipelineScript={mode === 'edit' ? handleAddPipelineScript : undefined} onRunnableMenuRemove={mode === 'edit' ? handleRunnableMenuRemove : undefined} + onDeleteAssetUpstream={isOperator ? undefined : (t) => (assetDeleteTarget = t)} + {nodeFixes} + assetDeleteVerb={canHardDeleteScripts ? 'Delete' : 'Archive'} + onEdgeAction={isOperator + ? undefined + : ({ + action, + targets + }: { + action: 'listen' | 'stop' + targets: Array<{ + script: string + asset: { kind: AssetKind; path: string } + reads: boolean + }> + }) => { + const byScript = new Map(targets.map((t) => [t.script, t] as const)) + editScripts( + [...byScript.keys()], + action === 'listen' ? 'Now reruns on each write' : 'Stopped rerunning on writes', + (s) => (c) => { + const t = byScript.get(s)! + return action === 'listen' + ? listenToAsset(c, t.asset, t.reads) + : stopListeningToAsset(c, t.asset, t.reads) + } + ) + }} + onAddAssetTrigger={isOperator || mode !== 'edit' + ? undefined + : ({ + scripts, + asset + }: { + scripts: Array<{ script: string; reads: boolean }> + asset: { kind: AssetKind; path: string } + }) => { + const reads = new Map(scripts.map((s) => [s.script, s.reads] as const)) + editScripts([...reads.keys()], 'Now reruns on each write', (s) => (c) => + listenToAsset(c, asset, reads.get(s) ?? false) + ) + }} onRunProducer={mode === 'edit' ? handleRunProducer : undefined} onRequestEdit={isOperator ? undefined : () => setMode('edit')} canRunByPath={openScriptHasDataUpload} @@ -2704,6 +3136,7 @@ }} onPersistedSaved={async (savedPath) => { const predicted = predictCascadeFacts([savedPath]) + forgetScriptCache(savedPath) await graphRes.refetch() reportDeployDrift(predicted) }} @@ -2711,6 +3144,7 @@ if (pe.selection?.kind === 'runnable' && pe.selection.path === oldPath) { pe.selection = { ...pe.selection, path: newPath } } + forgetScriptCache(oldPath, newPath) await graphRes.refetch() }} onScriptRemoved={async (removedPath) => { @@ -2770,6 +3204,102 @@ + { + const m = multiEdit + multiEdit = undefined + void m?.run() + }} + onCanceled={() => (multiEdit = undefined)} +> + {#if multiEdit} +
+

This will edit the annotation header of the following scripts. Each is saved as a draft.

+
    + {#each multiEdit.scripts as s (s)} +
  • {s}
  • + {/each} +
+
+ {/if} +
+ + { + if (!assetDeleteLoading) assetDeleteTarget = undefined + }} +> + {#if assetDeleteTarget} + {@const t = assetDeleteTarget} +
+

+ {#if t.script} + {canHardDeleteScripts + ? 'The script is deleted, with every version' + : 'The script is archived'}{t.trigger ? ', and its trigger deleted' : ''}. The tables + it wrote stay. + {:else} + The trigger is deleted: its script stays, and no longer runs this way. + {/if} +

+
    + {#if t.script} +
  • + {t.script.path} + Script{t.script.unsaved ? ' · draft' : ''} +
  • + {/if} + {#if t.trigger} +
  • + {t.trigger.path} + {t.trigger.kind} trigger{t.trigger.draft ? ' · draft' : ''} +
  • + {/if} +
+
+ {/if} +
+ + { + confirmTriggerDeployOpen = false + if (leaveAfterTriggerConfirm) { + leaveAfterTriggerConfirm = false + void saveAllAndLeave() + } else { + void saveAllDrafts() + } + }} + onCanceled={() => { + confirmTriggerDeployOpen = false + if (leaveAfterTriggerConfirm) { + leaveAfterTriggerConfirm = false + pendingNavigationUrl = undefined + } + }} +/> +

- {pe.drafts.size === 1 ? 'Unsaved draft' : `${pe.drafts.size} unsaved drafts`} + {pendingCount === 1 ? 'Unsaved draft' : `${pendingCount} unsaved drafts`}

- You have {pe.drafts.size === 1 - ? 'a draft pipeline script' - : `${pe.drafts.size} draft pipeline scripts`} that {pe.drafts.size === 1 + You have {pendingCount === 1 + ? 'a pipeline draft' + : `${pendingCount} pipeline drafts`} that {pendingCount === 1 ? 'has' : 'have'} not been deployed yet. What would you like to do?

    - {#each [...pe.drafts.keys()] as p} + {#each [...pe.drafts.keys(), ...[...pe.triggerDrafts.values()].map((d) => d.config.path)] as p}
  • {p}
  • {/each}
@@ -2828,7 +3358,7 @@ startIcon={{ icon: leaveSaving ? Loader2 : Save }} > {leaveSaving ? 'Saving…' : `Save all (${pe.drafts.size})`}{leaveSaving ? 'Saving…' : `Save all (${pendingCount})`} -
- {/snippet} -

-					
-			
- - -{/if} -{#if !job || (job?.job_kind != 'flow' && job?.job_kind != 'flownode' && job?.job_kind != 'flowpreview')} - -{/if} - -{#snippet flowRestartButton( - state: ReturnType, - step: string, - triggerStyle: 'button' | 'link' -)} - {#if job} - { - goto('/run/' + newJobId + '?workspace=' + $workspaceStore) - }} - flowPath={job.script_path} - flowVersionId={job.script_hash ? parseInt(job.script_hash, 16) : undefined} - disabled={!$enterpriseLicense} - enterpriseOnly={!$enterpriseLicense} - {triggerStyle} - unifiedSize="sm" - /> - {/if} -{/snippet} - - - - - -{#if loadError?.status === 403} -
-
- -
-

- This run exists in {$workspaceStore}, but you don't - have permission to view it. -

-

- Ask a colleague who can see it to open the run and use the - Share button to send you a read-only link. Opening that - link will grant you access to this run (and its steps). -

-
-
-
- -
-
-
-{:else if notfound || (job?.workspace_id != undefined && $workspaceStore != undefined && job?.workspace_id != $workspaceStore)} - {@const currentWorkspace = $userWorkspaces.find((w) => w.id === $workspaceStore)} - {@const otherWorkspaces = $userWorkspaces.filter((w) => w.id !== $workspaceStore)} -
-
-
- -
-

Run not found

-

- No run with ID - {page.params.run} - exists in - {currentWorkspace?.name ?? $workspaceStore}. It may belong to another workspace, or it may have been deleted. -

-
- - {#if otherWorkspaces.length > 0} -
-

Look in another workspace

-
- {#each otherWorkspaces as workspace (workspace.id)} - - {/each} -
-
- {/if} - -
- -
-
-{:else} - - - - - {#snippet runActions()} - {@const isScript = job?.job_kind === 'script'} - {@const isHubFlowPreview = isFlowPreview(job?.job_kind) && isHubFlowPath(job?.script_path)} - {@const runsHref = `/runs/${job?.script_path}${!isScript ? '?jobKind=flow' : ''}`} - {#if job && 'deleted' in job && !job?.deleted && ($superadmin || ($userStore?.is_admin ?? false))} - { - job?.id && deleteCompletedJob(job.id) - }, - type: 'delete' - } - ]} - > - {#snippet buttonReplacement()} - - {/if} - {/if} - {#if job} - job && shareReadLink(job.id) - }, - { - displayName: 'Copy public link', - icon: Globe, - disabled: !canSharePublicly, - tooltip: canSharePublicly - ? "Read-only link that anyone on the internet can open, without logging in. It shows a minimal version of this page: this run's inputs, result and logs, and for a flow its graph plus every step's inputs, result, logs and code. The link cannot be revoked." - : 'Sharing a run publicly is restricted in this workspace. Ask an admin to share it, or to grant you a bypass on the ruleset.', - action: () => job && sharePublicLink(job.id) - } - ]} - > - {#snippet buttonReplacement()} - - {/snippet} - - {/if} - {@const stem = job?.job_kind === 'script_hub' ? '/scripts' : `/${job?.job_kind}s`} - {@const viewHref = `${stem}/get/${isScript ? job?.script_hash : job?.script_path}`} - {#if (job?.job_kind == 'flow' || isFlowPreview(job?.job_kind)) && job?.['running'] && job?.parent_job == undefined} -
- { - debugInfo() - } - } - ]} - class="h-auto" - > - {#snippet buttonReplacement()} - - {/snippet} - -
- {/if} - {#if isFlowPreview(job?.job_kind) || isScriptPreview(job?.job_kind)} - - {/if} - {#if persistentScriptDefinition !== undefined} - - {/if} - {#if canRunNow} - - {/if} - {#if job && job?.type != 'CompletedJob' && (!job?.schedule_path || job?.['running'] == true)} - {#if !forceCancel} - - {:else} - - {/if} - {/if} - {#if job?.schedule_path} - - {/if} - {#if restartStep !== undefined && canRestart(restart)} - {@render flowRestartButton(restart, restartStep, 'button')} - {/if} - {#if job?.job_kind === 'script' || job?.job_kind === 'script_hub' || job?.job_kind === 'flow'} - - {/if} - {#if job?.job_kind === 'script' || job?.job_kind === 'flow'} - {#if !$userStore?.operator} - {#if canWrite(job?.script_path ?? '', {}, $userStore)} - - {#if showEditButton} - - - {/if} - {/if} - {#if !showEditButton && !isCloudHosted() && editInForkAllowed($workspaceStore, $userWorkspaces)} - - {/if} - {/if} - {/if} - {#if job?.job_kind === 'script' || job?.job_kind === 'script_hub' || job?.job_kind === 'flow'} - - {/if} - {/snippet} -
- -
- - {#if job} - { - persistentScriptDrawer?.open?.(persistentScriptDefinition) - }} - {concurrencyKey} - /> - {/if} -
- {#if job?.['deleted']} -
- - The content of this run was deleted (by an admin, no less) - -
-
- {/if} - - - {#if job?.job_kind === 'flow' || job?.job_kind === 'flowpreview'} -
- - {#snippet errorAction()} - {#if failedTopLevelStep} - at step {failedTopLevelStep} - {#if $enterpriseLicense && canRestart(failedRestart)} - · - {@render flowRestartButton(failedRestart, failedTopLevelStep, 'link')} - on this flow version, or on a new one after you fix it - {/if} - {/if} - {/snippet} - - {#if suspendStatus} - - {/if} -
- {/if} - - -
-
Inputs
-
- - {#if job && currentJobIsLongRunning && showExplicitProgressTip && !scriptProgress && 'running' in job} - - - - {/if} -
-
- - {#if job} - - {/if} - - {#if isNotFlow(job?.job_kind)} - {#if ['python3', 'bun', 'deno'].includes(job?.language ?? '') && (job?.job_kind == 'script' || isScriptPreview(job?.job_kind))} - - {/if} -
- {#if job?.workflow_as_code_status && job.job_kind !== 'aiagent'} -
-

Workflow Timeline

-
- -
-
- {/if} - {#if scriptProgress} - - {/if} - - - {#if job?.language === 'dbt' && job?.script_path} -
-

Models

- -
- {/if} - - - {#if job} -
-

Result

-
- {#if job.result_stream || (job.type == 'CompletedJob' && job.result !== undefined)} - - {:else} -
No output is available yet
- {/if} -
-
- {#if job.id && job.workspace_id} - - - {/if} - {/if} - - -
- - - - - - {#if isScriptPreview(job?.job_kind)} - - {/if} - - - - {#if job} -
- {#if viewTab == 'logs'} -
- -
- {:else if viewTab == 'assets'} -
- -
- {:else if viewTab == 'traces'} -
- -
- {:else if viewTab == 'code'} - {#if job && 'raw_code' in job && job.raw_code} -
- -
- {:else if job} - No code available - {:else} - - {/if} - {:else if viewTab == 'stats'} -
- -
- {:else} -
Select a tab to view content
- {/if} -
- {/if} -
-
- {:else if !job?.['deleted']} -
- -
- {#if job?.id} - { - job = newJob - }} - onDone={({ job: newJob }) => { - job = newJob - }} - initialJob={job} - workspaceId={$workspaceStore} - bind:selectedJobStep - bind:suspendStatus - bind:isOwner - bind:localModuleStates={graphModuleStates} - bind:expandedSubflows - /> - {:else} - - {/if} -
- {/if} -
-{/if} - - diff --git a/frontend/src/routes/(root)/(logged)/sessions/+page.svelte b/frontend/src/routes/(root)/(logged)/sessions/+page.svelte index 97ed4b95b6..19177dc463 100644 --- a/frontend/src/routes/(root)/(logged)/sessions/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/sessions/+page.svelte @@ -54,12 +54,12 @@ import { markSessionRecovered } from '$lib/components/sessions/sessionRecoveryNotice.svelte' import { isGlobalAiEnabled, - clearSessionsBetaOptOut + clearSessionsBetaOptOut, + sessionsAllowedFor } from '$lib/components/copilot/chat/global/gate' import { setToolCompletionListener } from '$lib/components/copilot/chat/shared' import { registerToolDisplayActionHandler } from '$lib/components/copilot/chat/createdResourceActions.svelte' import { previewTargetForSessionTarget } from '$lib/components/sessions/sessionPreviewTabs.svelte' - import { base } from '$lib/base' import { artifactKey, itemDisplayName, @@ -80,7 +80,7 @@ tabsToReload, viewerTabsToReload } from '$lib/components/sessions/previewReload' - import { isPageItemListPath, stripBase } from '$lib/components/sessions/previewPaths' + import { isPreviewListPath, barePath } from '$lib/components/sessions/previewPaths' import { leafKeyFor, loadKind, @@ -205,7 +205,7 @@ // load. `recovering` also guards re-entry: recovery mutates the session list // this effect tracks, while the URL that would stop it only updates on `goto`. $effect(() => { - if (embedded || !globalEnabled || $userStore?.operator) return + if (embedded || !globalEnabled || !sessionsAllowedFor($userStore?.operator)) return if (!sessionState.hydrated || recovering) return // A deliberate delete removes the open session ahead of its own navigation. // Claiming that gap would take over the URL and tell the user the session @@ -593,10 +593,10 @@ // Page path shown after the workspace breadcrumb — the active tab's observed // location, so the breadcrumb tracks where the user browses inside the tab. - const displayPath = $derived(owner?.activeTab?.loc ?? owner?.activeTab?.url ?? `${base}/`) + const displayPath = $derived(owner?.activeTab?.loc ?? owner?.activeTab?.url ?? '/') const activeArtifact = $derived(owner?.activeTab ? parseArtifactRoute(owner.activeTab.url) : null) const activeWorkspaceHref = $derived( - owner?.activeTab ? workspacePageHref(owner.activeTab.loc || owner.activeTab.url) : `${base}/` + owner?.activeTab ? workspacePageHref(owner.activeTab.loc || owner.activeTab.url) : '/' ) // The active session's artifacts, surfaced as an "Artifacts" branch in the // preview pickers. @@ -658,7 +658,7 @@ const tabHosts: Record = {} let reloadHandle: ReturnType | undefined - // Per workspace a chat round touched since the last flush: base-stripped list-page paths + // Per workspace a chat round touched since the last flush: list-page paths // (e.g. `/schedules`, see toolReloadEffect), the page items its tools named, as tab urls, // and the item paths whose deployed version changed. By workspace because a path names an // item only within one: a write in one fork must not remount the same path's editor in a @@ -889,7 +889,7 @@ // Leaving the preview for the standalone editor — carry the session // workspace so the app opens in the fork the session acts on, not the // navigation workspace. - goto(withWorkspaceParam(`${base}/apps/edit/${item.path}`, previewWorkspace)) + goto(withWorkspaceParam(`/apps/edit/${item.path}`, previewWorkspace)) return } owner?.navigate({ type: 'item', item }) @@ -928,7 +928,7 @@ // A preview frame navigating to a list page: re-point the active tab to the list // mounted in process, whose rows open as tabs of their own. if (d.type === 'wm.session.openList') { - if (typeof d.href !== 'string' || !isPageItemListPath(stripBase(d.href))) return + if (typeof d.href !== 'string' || !isPreviewListPath(barePath(d.href))) return owner?.navigate({ type: 'page', href: d.href, label: previewLocationLabel(d.href) }) return } @@ -966,7 +966,9 @@ so from then on the name comes from there, with its pen and its menu. --> Open sessions
- {:else if $userStore?.operator} - + {:else if !sessionsAllowedFor($userStore?.operator)} +

AI Sessions are not available for operators

Use the Ask AI chat instead.

@@ -1033,7 +1035,7 @@ try { localStorage.setItem('ai-chat-open', 'true') } catch {} - window.location.href = `${base}/` + window.location.href = '/' }} > Open Ask AI chat @@ -1045,7 +1047,7 @@

AI Sessions are deactivated

You switched back to the legacy chat. Activate AI Sessions (beta) to open this page.

-
diff --git a/frontend/src/routes/(root)/(logged)/svix/create-webhook/+page@(root).svelte b/frontend/src/routes/(root)/(logged)/svix/create-webhook/+page@(root).svelte index d4ac558cb8..212696782b 100644 --- a/frontend/src/routes/(root)/(logged)/svix/create-webhook/+page@(root).svelte +++ b/frontend/src/routes/(root)/(logged)/svix/create-webhook/+page@(root).svelte @@ -4,6 +4,8 @@ import ScriptPicker from '$lib/components/ScriptPicker.svelte' import { Button } from '$lib/components/common' import { page } from '$app/stores' + import { apiBaseUrl } from '$lib/apiBaseUrl.svelte' + import InstanceUiSync from '$lib/components/InstanceUiSync.svelte' import { userStore, workspaceStore } from '$lib/stores' import { sendUserToast } from '$lib/toast' import UserSettings from '$lib/components/UserSettings.svelte' @@ -26,11 +28,11 @@ let webhook: string switch (kind) { case 'script': - webhook = `${$page.url.origin}/api/w/${$workspaceStore}/jobs/run/p/${path}` + webhook = `${apiBaseUrl()}/api/w/${$workspaceStore}/jobs/run/p/${path}` redirectSuccess(webhook, token) break case 'flow': - webhook = `${$page.url.origin}/api/w/${$workspaceStore}/jobs/run/f/${path}` + webhook = `${apiBaseUrl()}/api/w/${$workspaceStore}/jobs/run/f/${path}` redirectSuccess(webhook, token) break default: @@ -72,6 +74,8 @@ }) + + { diff --git a/frontend/src/routes/(root)/(logged)/user/(user)/accept_invite/+page.svelte b/frontend/src/routes/(root)/(logged)/user/(user)/accept_invite/+page.svelte index e14a2113cb..6b731a4833 100644 --- a/frontend/src/routes/(root)/(logged)/user/(user)/accept_invite/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/user/(user)/accept_invite/+page.svelte @@ -2,7 +2,6 @@ import { run } from 'svelte/legacy'; import { goto } from '$lib/navigation' - import { base } from '$lib/base' import { SettingService, UserService, WorkspaceService } from '$lib/gen' import { validateUsername } from '$lib/utils' @@ -84,7 +83,7 @@ {/if}
- -

- Fetches the latest resource types directly from the Windmill Hub (requires internet - access). -

- {#if hubSyncStatus === 'success'} - - {hubSyncMessage} - - {:else if hubSyncStatus === 'error'} - - {hubSyncMessage} - - {/if}

- The daily schedule synchronizes resource types from the Hub every day at midnight UTC. + The server updates them from the Hub once a day, overwriting local edits to the types the + Hub also defines. You can change this later in the instance settings.

@@ -539,7 +496,7 @@
diff --git a/frontend/src/routes/(root)/(logged)/user/(user)/login/+page.svelte b/frontend/src/routes/(root)/(logged)/user/(user)/login/+page.svelte index 240eee8473..8bcd94ce24 100644 --- a/frontend/src/routes/(root)/(logged)/user/(user)/login/+page.svelte +++ b/frontend/src/routes/(root)/(logged)/user/(user)/login/+page.svelte @@ -1,5 +1,4 @@ {#if $superadmin || $devopsRole} + name)} + /> + +
@@ -1087,6 +1135,15 @@ {#if native_mode} Native {/if} + {#if draining} + + Draining + {#snippet text()} + This worker received a shutdown signal. It no longer pulls jobs + and exits once its current job is done. + {/snippet} + + {/if} {#if !config || !config.worker_tags || config.worker_tags.length === 0} @@ -1098,13 +1155,17 @@ {jobs_executed} {#if (!config || config?.dedicated_worker == undefined) && ($superadmin || $devopsRole)} - {#if last_job_id} + + {#if last_job_id && $workspaceStore} View last job
{last_job_workspace_id} + {:else if last_job_id} + {last_job_workspace_id} {/if}
@@ -1223,7 +1284,7 @@
{pingText}
- {#if $superadmin || $devopsRole} + {#if replAvailable} @@ -1582,7 +1667,7 @@ @@ -1634,9 +1719,9 @@ } }} onSelect={editSlackCommand} - connectHref="{base}/api/oauth/connect_slack" - createScriptHref="{base}/scripts/add?hub=hub%2F28071%2Fslack%2Fexample_of_responding_to_a_slack_command_slack" - createFlowHref="{base}/flows/add?hub=28" + connectHref="/api/oauth/connect_slack" + createScriptHref="/scripts/add?hub=hub%2F28071%2Fslack%2Fexample_of_responding_to_a_slack_command_slack" + createFlowHref="/flows/add?hub=28" documentationLink="https://www.windmill.dev/docs/integrations/slack" onLoadSettings={loadSettings} display_name={slack_team_name} @@ -1721,7 +1806,7 @@ Slack API . Set the redirect URI to:{' '} - {window.location.origin}{base}/oauth/callback_slack + {window.location.origin}/oauth/callback_slack @@ -1771,8 +1856,8 @@ }} onSelect={editTeamsCommand} connectHref={undefined} - createScriptHref="{base}/scripts/add?hub=hub%2F11591%2Fteams%2FExample%20of%20responding%20to%20a%20Microsoft%20Teams%20command" - createFlowHref="{base}/flows/add?hub=58" + createScriptHref="/scripts/add?hub=hub%2F11591%2Fteams%2FExample%20of%20responding%20to%20a%20Microsoft%20Teams%20command" + createFlowHref="/flows/add?hub=58" documentationLink="https://www.windmill.dev/docs/integrations/teams" onLoadSettings={loadSettings} display_name={teams_team_name} @@ -1825,7 +1910,7 @@ {:else} + {/if} + {:else} + Shared AI session + {/if} + + + +
+ {#if found} + {#if found.snapshot.messages.length > 0} + {#key found.session.id} + + {/key} + {:else} + + {/if} + {:else if shared.current?.state === 'signin'} + + + + {:else if shared.current?.state === 'gone'} + + {:else if shared.current?.state === 'error'} + + {:else} + + {/if} +
+ diff --git a/frontend/src/routes/a/[...path]/+page.svelte b/frontend/src/routes/a/[...path]/+page.svelte index d9affb4723..8bfd08a820 100644 --- a/frontend/src/routes/a/[...path]/+page.svelte +++ b/frontend/src/routes/a/[...path]/+page.svelte @@ -5,7 +5,6 @@ import type { GuestEntry } from '$lib/gen/types.gen' import type { UserExt } from '$lib/stores' import { page } from '$app/state' - import { base } from '$lib/base' import PublicApp from '$lib/components/apps/editor/PublicApp.svelte' import PublicAppFrame from '$lib/components/apps/editor/PublicAppFrame.svelte' import { @@ -74,7 +73,7 @@ // read it. Captured once (not reactively): the embedder mirrors the app's // hash/query back onto this page's URL, and re-deriving the src from it would // reload the app on its every navigation. - const viewerUrl = `${base}/a/${parsedCustomPath.path}${page.url.search}${page.url.hash}` + const viewerUrl = `/a/${parsedCustomPath.path}${page.url.search}${page.url.hash}` let workspace: string | undefined = $state(undefined) let embedWorkspace: string | undefined diff --git a/frontend/src/routes/public/[workspace]/[...secret]/+page.svelte b/frontend/src/routes/public/[workspace]/[...secret]/+page.svelte index 31bc49a5ab..fb32a8ac9b 100644 --- a/frontend/src/routes/public/[workspace]/[...secret]/+page.svelte +++ b/frontend/src/routes/public/[workspace]/[...secret]/+page.svelte @@ -5,7 +5,6 @@ import type { GuestEntry } from '$lib/gen/types.gen' import type { UserExt } from '$lib/stores' import { page } from '$app/state' - import { base } from '$lib/base' import PublicApp from '$lib/components/apps/editor/PublicApp.svelte' import PublicAppFrame from '$lib/components/apps/editor/PublicAppFrame.svelte' import { @@ -63,7 +62,7 @@ // Captured once (not reactively): the embedder mirrors the app's hash/query // back onto this page's URL, and re-deriving the src from it would reload the // app on its every navigation. - const viewerUrl = `${base}/public/${workspace}/${parsedSecret.secret}${page.url.search}${page.url.hash}` + const viewerUrl = `/public/${workspace}/${parsedSecret.secret}${page.url.search}${page.url.hash}` let refresh: (() => void) | undefined diff --git a/frontend/static/apple-touch-icon.png b/frontend/static/apple-touch-icon.png new file mode 100644 index 0000000000..211c5c1e81 Binary files /dev/null and b/frontend/static/apple-touch-icon.png differ diff --git a/frontend/static/manifest.webmanifest b/frontend/static/manifest.webmanifest new file mode 100644 index 0000000000..6ded55be6d --- /dev/null +++ b/frontend/static/manifest.webmanifest @@ -0,0 +1,22 @@ +{ + "id": "/", + "name": "Windmill", + "short_name": "Windmill", + "description": "Scripts, flows and apps for internal tools, workflows and background jobs", + "start_url": "/", + "scope": "/", + "display": "standalone", + "background_color": "#fbfbfd", + "theme_color": "#fbfbfd", + "icons": [ + { "src": "/pwa-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any" }, + { "src": "/pwa-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any" }, + { + "src": "/pwa-maskable-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + }, + { "src": "/logo.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any" } + ] +} diff --git a/frontend/static/pwa-192.png b/frontend/static/pwa-192.png new file mode 100644 index 0000000000..ced36d0455 Binary files /dev/null and b/frontend/static/pwa-192.png differ diff --git a/frontend/static/pwa-512.png b/frontend/static/pwa-512.png new file mode 100644 index 0000000000..b188f4f45b Binary files /dev/null and b/frontend/static/pwa-512.png differ diff --git a/frontend/static/pwa-maskable-512.png b/frontend/static/pwa-maskable-512.png new file mode 100644 index 0000000000..c1c4de333f Binary files /dev/null and b/frontend/static/pwa-maskable-512.png differ diff --git a/frontend/svelte.config.js b/frontend/svelte.config.js index 15634551e6..64b39b5d7d 100644 --- a/frontend/svelte.config.js +++ b/frontend/svelte.config.js @@ -35,9 +35,6 @@ const config = { // revisions (SvelteKit only full-page reloads on a missing chunk if this changed). version: { name: process.env.WM_BUILD_VERSION || pkg.version }, prerender: { entries: [] }, - paths: { - base: process.env.VITE_BASE_URL ?? '' - }, alias: { $system_prompts: '../system_prompts/auto-generated', $oauth_connect_registry: '../backend/oauth_connect.json', diff --git a/integration_tests/test/git_sync_test.py b/integration_tests/test/git_sync_test.py index 3f761e36f5..aee7ea1088 100644 --- a/integration_tests/test/git_sync_test.py +++ b/integration_tests/test/git_sync_test.py @@ -215,17 +215,46 @@ class GitSyncTestBase(unittest.TestCase): return repo return None + def _new_sync_jobs(self, seen: set, path: str) -> list: + """Completed deploy callbacks not in `seen` whose items include `path`. + A callback debounced into another completes as skipped with its items + still in its args, so skipped ones are left out: only the survivor, + whose args carry the accumulated items, ran the push.""" + jobs = [] + for listed in self._client.get_completed_jobs(job_kinds="deploymentcallback"): + if listed["id"] in seen: + continue + job = self._client._client.get( + f"/api/w/{self._client._workspace}/jobs_u/get/{listed['id']}" + ).json() + if job.get("is_skipped"): + continue + items = (job.get("args") or {}).get("items") or [] + if any(item.get("path") == path for item in items): + jobs.append(job) + return jobs + def _deploy_seed_script(self, name_prefix: str) -> str: - """Deploy a script and wait for its push to git. Returns the script path.""" - initial_count = self._client.count_deployment_callback_jobs() + """Deploy a script and wait for its push to git. Returns the script path. + + Waits on the callback that carries this script, not on the workspace's + callback count: a callback still finishing from an earlier test raises + the count before this push lands.""" + seen = {j["id"] for j in self._client.get_completed_jobs(job_kinds="deploymentcallback")} script_path = f"u/admin/{unique_name(name_prefix)}" self._client.create_script( path=script_path, content=ts_script("return 'seed'"), language="bun", ) - self._client.wait_for_sync_jobs(initial_count, min_new=1) - time.sleep(3) + self._wait_until( + lambda: self._new_sync_jobs(seen, script_path), + timeout=90, + interval=2, + message=f"no push job for {script_path}", + ) + failed = [j for j in self._new_sync_jobs(seen, script_path) if not j.get("success")] + self.assertEqual(failed, [], f"the push of {script_path} failed") return script_path def _repo_script_file(self, repo_name: str, script_path: str, branch: str = None) -> str: @@ -773,17 +802,7 @@ class TestGitSync(GitSyncTestBase): def _new_sync_job_results(self, seen: set, path: str) -> list: """Results of the deploy callbacks not in `seen` that pushed `path`.""" - results = [] - for listed in self._client.get_completed_jobs(job_kinds="deploymentcallback"): - if listed["id"] in seen: - continue - job = self._client._client.get( - f"/api/w/{self._client._workspace}/jobs_u/get/{listed['id']}" - ).json() - items = (job.get("args") or {}).get("items") or [] - if any(item.get("path") == path for item in items): - results.append(job.get("result")) - return results + return [job.get("result") for job in self._new_sync_jobs(seen, path)] def test_promotion_push_reports_whether_it_pushed(self): """The push job's result says whether a commit was pushed, and the diff --git a/integration_tests/test/identity_script_test.py b/integration_tests/test/identity_script_test.py index dc56c4956c..638919fb22 100644 --- a/integration_tests/test/identity_script_test.py +++ b/integration_tests/test/identity_script_test.py @@ -14,11 +14,6 @@ echo ${x} export async function main(x: number) { return x; } -""", - "deno": """ -export async function main(x: number) { - return x; -} """, "go": """ package inner @@ -72,11 +67,6 @@ class TestIdentityScript(unittest.TestCase): result = self._client.run_sync(path, {"x": 5}) self.assertEqual(result, 5) - def test_deno(self): - path = PATH_TEMPLATE.format(lang="deno") - result = self._client.run_sync(path, {"x": 5}) - self.assertEqual(result, 5) - def test_go(self): path = PATH_TEMPLATE.format(lang="go") result = self._client.run_sync(path, {"x": 5}) diff --git a/integration_tests/test/increment_flow_test.py b/integration_tests/test/increment_flow_test.py index c4682cb8b3..2a2f5b88d9 100644 --- a/integration_tests/test/increment_flow_test.py +++ b/integration_tests/test/increment_flow_test.py @@ -38,10 +38,10 @@ FLOW_VALUE = """ "value": { "tag": "", - "lock": "{\\n \\"version\\": \\"3\\",\\n \\"remote\\": {}\\n}\\n", + "lock": "{\\n \\"dependencies\\": {}\\n}\\n//bun.lockb\\n", "type": "rawscript", "content": "export async function main(x: number) {\\n return x + 1\\n}\\n", - "language": "deno", + "language": "bun", "input_transforms": { "x": diff --git a/integration_tests/test/windmill_sdk_test.py b/integration_tests/test/windmill_sdk_test.py index 6b5dcefbe9..11a4fa7886 100644 --- a/integration_tests/test/windmill_sdk_test.py +++ b/integration_tests/test/windmill_sdk_test.py @@ -8,15 +8,6 @@ from .wmill_integration_test_utils import WindmillClient VARIABLE_PATH = "u/admin/test_variable" VARIABLE_VALUE = "Hello world!" -DENO_SCRIPT_PATH = "u/admin/deno_sdk_test_script" -DENO_SCRIPT_VALUE = """ -import * as wmill from "npm:windmill-client@{version}" -export async function main() {{ - const val = await wmill.getVariable('u/admin/test_variable') - return val; -}} -""" - BUN_SCRIPT_PATH = "u/admin/bun_sdk_test_script" BUN_SCRIPT_VALUE = """ import * as wmill from "windmill-client@{version}" @@ -63,11 +54,6 @@ class TestWindmillSdk(unittest.TestCase): path=VARIABLE_PATH, value=VARIABLE_VALUE, ) - cls._client.create_script( - path=DENO_SCRIPT_PATH, - content=DENO_SCRIPT_VALUE.format(version=cls._dev_version), - language="deno", - ) # TODO: See skipped annotations below # cls._client.create_script( # path=BUN_SCRIPT_PATH, @@ -89,7 +75,6 @@ class TestWindmillSdk(unittest.TestCase): def tearDownClass(cls) -> None: if cls._running_latest: cls._client.set_npm_config_registry("") - cls._client.delete_script(path=DENO_SCRIPT_PATH) # TODO: See skipped annotations below # cls._client.delete_script(path=BUN_SCRIPT_PATH) # cls._client.delete_script(path=PYTHON_SCRIPT_PATH) @@ -97,13 +82,6 @@ class TestWindmillSdk(unittest.TestCase): cls._client.delete_variable(path=VARIABLE_PATH) cls._client.set_npm_config_registry("") - @unittest.skipUnless( - os.environ.get("WMILL_RUNNING_DEV", "0") == "1", "Runs on dev version only" - ) - def test_deno_sdk_usable(self): - result = self._client.run_sync(DENO_SCRIPT_PATH, {}) - self.assertEqual(result, VARIABLE_VALUE) - @unittest.skipUnless( # os.environ.get("WMILL_RUNNING_DEV", "0") == "1", "Runs on dev version only" False, diff --git a/lsp/Pipfile b/lsp/Pipfile index 4509187f28..46dab6afb9 100644 --- a/lsp/Pipfile +++ b/lsp/Pipfile @@ -4,7 +4,7 @@ verify_ssl = true name = "pypi" [packages] -wmill = ">=1.827.0" +wmill = ">=1.841.0" sendgrid = "*" mysql-connector-python = "*" pymongo = "*" diff --git a/lsp/pyls_launcher.py b/lsp/pyls_launcher.py index 9e522d8ce5..b3fbe7fd9a 100644 --- a/lsp/pyls_launcher.py +++ b/lsp/pyls_launcher.py @@ -1,6 +1,9 @@ +import asyncio import logging +import shutil import subprocess import threading +import time import os import urllib.request import urllib.error @@ -149,8 +152,221 @@ class LanguageServerWebSocketHandler(websocket.WebSocketHandler): class PyrightLS(LanguageServerWebSocketHandler): procargs = ["pipenv", "run", "pyright-langserver", "--stdio"] -class DiagnosticLS(LanguageServerWebSocketHandler): - procargs = ["diagnostic-languageserver", "--stdio", "--log-level", "4"] +SHELLCHECK_BIN = shutil.which("shellcheck") +# The linter is configured here rather than by the editor's initializationOptions. +SHELLCHECK_ARGS = ["--norc", "--format=json1", "-"] +SHELLCHECK_TIMEOUT_SECS = float(os.environ.get("SHELLCHECK_TIMEOUT_SECS", "10")) +SHELLCHECK_MAX_DOC_CHARS = int(os.environ.get("SHELLCHECK_MAX_DOC_CHARS", "200000")) +SHELLCHECK_MAX_DOCS_PER_CONN = 8 +# A document whose checks finish faster than this is checked on every change +# with no pause; see ShellcheckLS._changed. +SHELLCHECK_INSTANT_SECS = 0.05 +SHELLCHECK_MAX_DEBOUNCE_SECS = 1.0 +# Shared by every connection: shellcheck is CPU-bound and single-threaded, so +# more concurrent runs than cores only makes all of them slower. +_shellcheck_slots = asyncio.Semaphore(os.cpu_count() or 2) + +_SHELLCHECK_SEVERITIES = {"error": 1, "warning": 2, "info": 3, "style": 3} + + +def _utf16_col(line, col): + """shellcheck counts code points, LSP positions count UTF-16 code units.""" + col = max(col - 1, 0) + if line.isascii(): + return col + return len(line[:col].encode("utf-16-le")) // 2 + + +def shellcheck_diagnostics(text, output): + lines = text.split("\n") + + def position(line, col): + line = max(line - 1, 0) + return { + "line": line, + "character": _utf16_col(lines[line], col) if line < len(lines) else 0, + } + + diagnostics = [] + for c in json.loads(output).get("comments", []): + code = "SC%d" % c["code"] + diagnostics.append( + { + "range": { + "start": position(c["line"], c["column"]), + "end": position(c["endLine"], c["endColumn"]), + }, + "severity": _SHELLCHECK_SEVERITIES.get(c["level"], 3), + "code": code, + "codeDescription": {"href": "https://www.shellcheck.net/wiki/" + code}, + "source": "shellcheck", + "message": c["message"], + } + ) + return diagnostics + + +class ShellcheckLS(websocket.WebSocketHandler): + """Lints shell documents by running shellcheck itself, speaking only the + slice of LSP that takes: document sync in, diagnostics out.""" + + def open(self): + self.docs = {} + self.tasks = {} + self.cost = {} + self.linted = {} + + def check_origin(self, origin): + return True + + def on_message(self, message): + try: + msg = json.loads(message) + method = msg.get("method") + params = msg.get("params") or {} + if method == "initialize": + self._send( + { + "jsonrpc": "2.0", + "id": msg.get("id"), + "result": { + "capabilities": { + "textDocumentSync": {"openClose": True, "change": 1} + }, + "serverInfo": {"name": "windmill-shellcheck"}, + }, + } + ) + elif method == "textDocument/didOpen": + doc = params["textDocument"] + self._changed(doc["uri"], doc.get("version"), doc["text"]) + elif method == "textDocument/didChange": + doc = params["textDocument"] + self._changed( + doc["uri"], doc.get("version"), params["contentChanges"][-1]["text"] + ) + elif method == "textDocument/didClose": + self._forget(params["textDocument"]["uri"]) + elif method == "shutdown": + self._send({"jsonrpc": "2.0", "id": msg.get("id"), "result": None}) + elif method is not None and "id" in msg: + self._send( + { + "jsonrpc": "2.0", + "id": msg["id"], + "error": {"code": -32601, "message": "Method not found"}, + } + ) + except (ValueError, KeyError, IndexError, TypeError, AttributeError): + log.warning("shellcheck: dropping malformed message") + + def on_close(self): + for uri in list(self.docs): + self._forget(uri) + + def _send(self, msg): + try: + self.write_message(json.dumps(msg)) + except websocket.WebSocketClosedError: + pass + + def _forget(self, uri): + task = self.tasks.pop(uri, None) + if task: + task.cancel() + self.docs.pop(uri, None) + self.cost.pop(uri, None) + self.linted.pop(uri, None) + + def _changed(self, uri, version, text): + if not isinstance(uri, str) or not isinstance(text, str): + raise TypeError + if uri not in self.docs and len(self.docs) >= SHELLCHECK_MAX_DOCS_PER_CONN: + return + if len(text) > SHELLCHECK_MAX_DOC_CHARS: + # Not checked, so not kept either: reported as having no findings. + text = None + self.docs[uri] = (version, text) + if uri in self.linted and self.linted[uri] == text: + return + running = self.tasks.pop(uri, None) + # The pause before a check is what that document's checks cost: one that + # is cheap is checked at once, one that is not waits out a typing burst + # rather than burning a core on results the next keystroke discards. + delay = self.cost.get(uri, 0) + if delay < SHELLCHECK_INSTANT_SECS: + delay = 0 + if running and not running.done(): + running.cancel() + delay = max(delay, SHELLCHECK_INSTANT_SECS) + self.tasks[uri] = asyncio.ensure_future(self._lint(uri, version, text, delay)) + + async def _lint(self, uri, version, text, delay): + if delay: + await asyncio.sleep(delay) + diagnostics = [] + if SHELLCHECK_BIN and text is not None: + async with _shellcheck_slots: + started = time.monotonic() + try: + output = await self._run(text) + self.cost[uri] = 0 + finally: + # A killed check counts too, as a lower bound: it is the only + # measure a document edited faster than it can be checked gets. + if uri in self.docs: + self.cost[uri] = min( + max(time.monotonic() - started, self.cost.get(uri, 0)), + SHELLCHECK_MAX_DEBOUNCE_SECS, + ) + if output is None: + return + try: + diagnostics = shellcheck_diagnostics(text, output) + except (ValueError, KeyError, TypeError) as e: + log.warning("shellcheck: unreadable output: %s", e) + return + if self.docs.get(uri) != (version, text): + return + self.linted[uri] = text + params = {"uri": uri, "diagnostics": diagnostics} + if version is not None: + params["version"] = version + self._send( + { + "jsonrpc": "2.0", + "method": "textDocument/publishDiagnostics", + "params": params, + } + ) + + async def _run(self, text): + try: + proc = await asyncio.create_subprocess_exec( + SHELLCHECK_BIN, + *SHELLCHECK_ARGS, + stdin=asyncio.subprocess.PIPE, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.DEVNULL, + ) + except OSError as e: + log.warning("shellcheck: could not start: %s", e) + return None + try: + output, _ = await asyncio.wait_for( + proc.communicate(text.encode("utf-8", "replace")), + SHELLCHECK_TIMEOUT_SECS, + ) + return output + except asyncio.TimeoutError: + log.warning("shellcheck: timed out on a %d char document", len(text)) + return None + finally: + # Also reached when a newer change cancels this check mid-run. + if proc.returncode is None: + proc.kill() + await proc.wait() + class RuffLS(LanguageServerWebSocketHandler): procargs = ["ruff", "server"] @@ -201,11 +417,14 @@ if __name__ == "__main__": # spawned `ruff server` picks it up. start_ruff_config_poller() + if not SHELLCHECK_BIN: + log.warning("shellcheck is not on PATH: shell scripts will not be linted") + port = int(os.environ.get("PORT", "3001")) app = web.Application( [ (r"/ws/pyright", PyrightLS), - (r"/ws/diagnostic", DiagnosticLS), + (r"/ws/diagnostic", ShellcheckLS), (r"/ws/ruff", RuffLS), (r"/ws/deno", DenoLS), (r"/ws/go", GoLS), diff --git a/openflow.openapi.yaml b/openflow.openapi.yaml index 0fcf8a61dd..57e5009b90 100644 --- a/openflow.openapi.yaml +++ b/openflow.openapi.yaml @@ -1,7 +1,7 @@ openapi: '3.0.3' info: - version: 1.827.0 + version: 1.841.0 title: OpenFlow Spec contact: name: Ruben Fiszel @@ -112,7 +112,10 @@ components: description: Execution priority (higher numbers run first) early_return: type: string - description: JavaScript expression to return early from the flow + description: >- + Id of the step whose result a sync webhook returns as soon as that step completes, while + the rest of the flow keeps running. When the step does not run, or fails while the flow + has a failure module, the flow's final result is returned instead. chat_input_enabled: type: boolean description: Whether this flow accepts chat-style input @@ -1183,6 +1186,23 @@ components: description: | Number. Limits how many times the agent can loop through reasoning and tool use. Range: 1-1000. + model: + allOf: + - $ref: '#/components/schemas/InputTransform' + description: | + String. Only on a step linked to a saved agent (see `agent`): replaces the model + saved on the agent for this step's runs, on the agent's own provider resource. An + empty value keeps the saved model. Set it to an expression such as + `flow_input.model` to choose the model per run. + reasoning_effort: + allOf: + - $ref: '#/components/schemas/InputTransform' + description: | + String. Only on a step linked to a saved agent (see `agent`): replaces the reasoning + effort saved on the agent for this step's runs, as a provider-native token (e.g. + 'low', 'high', 'none'). An empty value sends no effort, so the model runs at its + default. Leave the input out to keep the saved effort, which holds only while the + step runs the saved model. A step that is not linked sets both inside `provider`. # Only the flow-local inputs are always present: a step linked to an `ai_agent` resource # (see `agent`) keeps just those and takes provider/output_type from the resource. Even # `user_message` may be absent, when memory is off and `previous_messages` is the prompt. @@ -1208,7 +1228,8 @@ components: Path of a reusable `ai_agent` resource (hybrid linking). When set, the agent brain config (provider/model/system prompt/etc.) and tool set are resolved at runtime from that resource; the module's input_transforms then only carry the flow-local inputs - (user_message, user_attachments, enabled_tools and the history inputs memory_id and previous_messages). + (user_message, user_attachments, enabled_tools and the history inputs memory_id and previous_messages) + and, optionally, the `model` and `reasoning_effort` overrides of what the agent saved. tool_inputs: type: object description: | diff --git a/powershell-client/WindmillClient/WindmillClient.psd1 b/powershell-client/WindmillClient/WindmillClient.psd1 index 62cf4298d6..35e7468900 100644 --- a/powershell-client/WindmillClient/WindmillClient.psd1 +++ b/powershell-client/WindmillClient/WindmillClient.psd1 @@ -12,7 +12,7 @@ RootModule = 'WindmillClient.psm1' # Version number of this module. - ModuleVersion = '1.827.0' + ModuleVersion = '1.841.0' # Supported PSEditions # CompatiblePSEditions = @() diff --git a/python-client/wmill/pyproject.toml b/python-client/wmill/pyproject.toml index 4ffcbddd89..2c9f5143bf 100644 --- a/python-client/wmill/pyproject.toml +++ b/python-client/wmill/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "wmill" -version = "1.827.0" +version = "1.841.0" description = "A client library for accessing Windmill server wrapping the Windmill client API" license = "Apache-2.0" homepage = "https://windmill.dev" diff --git a/python-client/wmill/tests/test_s3_proxy_settings.py b/python-client/wmill/tests/test_s3_proxy_settings.py new file mode 100644 index 0000000000..52db4fc8a9 --- /dev/null +++ b/python-client/wmill/tests/test_s3_proxy_settings.py @@ -0,0 +1,68 @@ +"""The default S3 connection settings go through the S3 proxy only when the server can verify +the token's SigV4 signature and serves the bucket-addressed routes; otherwise they keep the +storage's own credentials.""" + +import pytest + +from wmill.client import Windmill + +JOB_TOKEN = "jwt_header.payload.signature" + + +class _Response: + def __init__(self, status_code, body): + self.status_code = status_code + self._body = body + + def json(self): + return self._body + + +def _client(token, status_code=200, body=None): + client = Windmill(base_url="https://wm.example", token=token, workspace="ws") + calls = [] + + def get(endpoint, raise_for_status=True, **kwargs): + calls.append(endpoint) + return _Response(status_code, body if body is not None else {"bucket": "data"}) + + def post(endpoint, raise_for_status=True, **kwargs): + calls.append(endpoint) + resource = {"endPoint": "s3.example", "useSSL": True, "region": "eu-west-1"} + return _Response(200, {**resource, "accessKey": "raw", "secretKey": "raw-secret"}) + + client.get = get + client.post = post + return client, calls + + +def test_job_token_goes_through_the_proxy(): + client, _ = _client(JOB_TOKEN) + settings = client.get_boto3_connection_settings() + assert settings["endpoint_url"] == "https://wm.example/api/w/ws/s3_proxy/_wm_bucket_/_default_" + assert settings["aws_access_key_id"] == "jwt_header.payload" + assert settings["aws_secret_access_key"] == "signature" + assert client.get_polars_connection_settings()["s3_bucket"] == "data" + + +@pytest.mark.parametrize( + "token,status_code,body", + [ + ("personaltokenwithoutdots", 200, None), + ("jwt_ext_header.payload.signature", 200, None), + (JOB_TOKEN, 404, None), + (JOB_TOKEN, 200, {"bucket": None}), + ], + ids=["personal token", "external jwt", "older server", "non-S3 storage"], +) +def test_falls_back_to_the_storage_credentials(token, status_code, body): + client, calls = _client(token, status_code, body) + settings = client.get_boto3_connection_settings() + assert settings["aws_access_key_id"] == "raw" + assert calls[-1].endswith("/job_helpers/v2/s3_resource_info") + + +def test_explicit_resource_path_never_asks_for_the_proxy(): + client, calls = _client(JOB_TOKEN) + client.get_boto3_connection_settings("u/admin/s3") + assert calls == ["/w/ws/job_helpers/v2/s3_resource_info"] diff --git a/python-client/wmill/tests/test_workflow.py b/python-client/wmill/tests/test_workflow.py index ceed39bfeb..d32ae1458b 100644 --- a/python-client/wmill/tests/test_workflow.py +++ b/python-client/wmill/tests/test_workflow.py @@ -7,7 +7,7 @@ import pytest from datetime import datetime, timezone -from wmill.client import WorkflowCtx, _StepSuspend, TaskError, workflow, task, step, sleep, parallel, wait_for_approval, _run_workflow, _run_workflow_async +from wmill.client import WorkflowCtx, _StepSuspend, TaskError, workflow, task, task_script, step, sleep, parallel, wait_for_approval, _run_workflow, _run_workflow_async class _FakeItems(dict): @@ -752,6 +752,84 @@ class TestChildModeParallel: assert result["result"] == 8 +class TestSdkCallsInsideTaskBody: + """A task body runs as one child job, so the SDK calls it makes cannot be + dispatched as steps of their own.""" + + def _run_child(self, wf, key): + async def bounded(): + return await asyncio.wait_for( + _run_workflow_async(wf, {"completed_steps": {}, "_executing_key": key}, {}), + timeout=2, + ) + + return asyncio.run(bounded()) + + def test_nested_task_and_step_run_in_the_tasks_own_job(self): + @task + async def inner(x: str): + return f"inner:{x}" + + @task + def sync_leaf(x: str): + return f"sync:{x}" + + # A sync body calls its tasks without awaiting, whatever called it. + @task + def sync_inner(x: str): + return sync_leaf(x).upper().lower() + + @task + async def outer(x: str): + via_task = await inner(x) + via_sync = await sync_inner(x) + via_step = await step("s", lambda: "stepped") + return f"{via_task}+{via_sync}+{via_step}" + + @workflow + async def wf(): + return await outer("a") + + result = self._run_child(wf, "outer") + assert result == {"type": "complete", "result": "inner:a+sync:a+stepped"} + + def test_sibling_task_of_the_workflow_body_is_not_run(self): + # The workflow body keeps replaying beside the task body, and its own + # calls must stay parked: running them would execute a sibling task in + # this job. + ran = [] + + @task + async def inner(x: str): + ran.append(x) + return x + + @task + async def outer(x: str): + await asyncio.sleep(0) + return await inner("nested") + + @workflow + async def wf(): + return await asyncio.gather(outer("a"), inner("sibling")) + + result = self._run_child(wf, "outer") + assert result == {"type": "complete", "result": "nested"} + assert ran == ["nested"] + + def test_step_that_would_need_a_dispatch_fails_instead_of_hanging(self): + @task + async def dispatching(): + return await task_script("f/other/script")() + + @workflow + async def wf(): + return await dispatching() + + with pytest.raises(RuntimeError, match="cannot be called from inside a task"): + self._run_child(wf, "dispatching") + + class TestKeyDeterminism: def test_keys_consistent_across_replays(self): r1 = _run_workflow(det_wf, {}, {"n": 3}) diff --git a/python-client/wmill/wmill/client.py b/python-client/wmill/wmill/client.py index ffcb6a3fe1..f0d0134fa7 100644 --- a/python-client/wmill/wmill/client.py +++ b/python-client/wmill/wmill/client.py @@ -823,6 +823,22 @@ class Windmill: else: return r.json() + def worker_is_draining(self, job_id: Optional[str] = None) -> bool: + """Whether the worker running the job has received its shutdown signal. + + A draining worker waits for its current job to finish before exiting. A long-running + script can poll this and return early so the worker can be replaced. + + Args: + job_id: Job ID (defaults to current WM_JOB_ID) + + Returns: + True if the worker running the job is draining + """ + job_id = job_id or os.environ.get("WM_JOB_ID") + + return self.get(f"/w/{self.workspace}/jobs/worker_is_draining/{job_id}").json() + def set_flow_user_state(self, key: str, value: Any) -> None: """Set the user state of a flow at a given key""" flow_id = self.get_root_job_id() @@ -856,15 +872,75 @@ class Windmill: """ return self.get("version").text + def _s3_proxy_connection(self) -> dict | None: + """Where an S3 client reaches the workspace storage through Windmill's S3 proxy, so the + storage's permission rules apply and its credentials stay on the server. + + None when the workspace storage is not S3, when the token is not one the server signs + itself (the proxy re-derives the SigV4 secret from a ``jwt_`` token's header and payload, + which an external ``jwt_ext_`` token's signature does not match), or when the server + predates the proxy's bucket-addressed routes: the caller then connects with the + storage's own credentials. + """ + if ( + not self.token + or not self.token.startswith("jwt_") + or self.token.startswith(("jwt_ext_", "jwt_agent_")) + ): + return None + resp = self.get( + f"/w/{self.workspace}/job_helpers/v2/s3_proxy_bucket", + raise_for_status=False, + ) + if resp.status_code != 200: + return None + bucket = resp.json().get("bucket") + if bucket is None: + return None + access_key, secret_key = self.token.rsplit(".", 1) + return { + "endpoint_url": f"{self.base_url}/w/{self.workspace}/s3_proxy/_wm_bucket_/_default_", + "use_ssl": self.base_url.startswith("https://"), + "access_key": access_key, + "secret_key": secret_key, + # The proxy checks the signature with whatever region the client signed for. + "region": "us-east-1", + "bucket": bucket, + } + def get_duckdb_connection_settings( self, s3_resource_path: str = "", ) -> DuckDbConnectionSettings | None: """ Convenient helpers that takes an S3 resource as input and returns the settings necessary to - initiate an S3 connection from DuckDB + initiate an S3 connection from DuckDB. + + Without a resource path, the connection goes to the workspace storage through Windmill's + S3 proxy when that storage is S3: address it as ``s3:///`` with the + storage's own bucket, returned as ``s3_bucket``. Pass the resource path to connect with + the storage's own credentials instead. """ s3_resource_path = parse_resource_syntax(s3_resource_path) or s3_resource_path + proxy = self._s3_proxy_connection() if s3_resource_path == "" else None + if proxy is not None: + endpoint = proxy["endpoint_url"].split("://", 1)[1] + settings = ( + "SET home_directory='./';\n" + "INSTALL 'httpfs';\n" + "SET s3_url_style='path';\n" + f"SET s3_region='{proxy['region']}';\n" + f"SET s3_endpoint='{endpoint}';\n" + f"SET s3_access_key_id='{proxy['access_key']}';\n" + f"SET s3_secret_access_key='{proxy['secret_key']}';\n" + ) + if not proxy["use_ssl"]: + settings += "SET s3_use_ssl=0;\n" + if self.verify is False: + settings += "SET enable_server_cert_verification=false;\n" + return DuckDbConnectionSettings( + {"connection_settings_str": settings, "s3_bucket": proxy["bucket"]} + ) try: raw_obj = self.post( f"/w/{self.workspace}/job_helpers/v2/duckdb_connection_settings", @@ -872,6 +948,7 @@ class Windmill: if s3_resource_path == "" else {"s3_resource_path": s3_resource_path}, ).json() + raw_obj.setdefault("s3_bucket", None) return DuckDbConnectionSettings(raw_obj) except JSONDecodeError as e: raise Exception( @@ -884,9 +961,44 @@ class Windmill: ) -> PolarsConnectionSettings: """ Convenient helpers that takes an S3 resource as input and returns the settings necessary to - initiate an S3 connection from Polars + initiate an S3 connection from Polars. + + Without a resource path, the connection goes to the workspace storage through Windmill's + S3 proxy when that storage is S3: address it as ``s3:///`` with the + storage's own bucket, returned as ``s3_bucket``. Pass the resource path to connect with + the storage's own credentials instead. """ s3_resource_path = parse_resource_syntax(s3_resource_path) or s3_resource_path + proxy = self._s3_proxy_connection() if s3_resource_path == "" else None + if proxy is not None: + client_kwargs = {"region_name": proxy["region"]} + storage_options = { + "aws_endpoint_url": proxy["endpoint_url"], + "aws_access_key_id": proxy["access_key"], + "aws_secret_access_key": proxy["secret_key"], + "aws_region": proxy["region"], + "aws_allow_http": str(not proxy["use_ssl"]).lower(), + "aws_virtual_hosted_style_request": "false", + } + if self.verify is not True: + client_kwargs["verify"] = self.verify + if self.verify is False: + storage_options["allow_invalid_certificates"] = "true" + return PolarsConnectionSettings( + { + "s3fs_args": { + "endpoint_url": proxy["endpoint_url"], + "key": proxy["access_key"], + "secret": proxy["secret_key"], + "use_ssl": proxy["use_ssl"], + "cache_regions": False, + "client_kwargs": client_kwargs, + "config_kwargs": {"s3": {"addressing_style": "path"}}, + }, + "storage_options": storage_options, + "s3_bucket": proxy["bucket"], + } + ) try: raw_obj = self.post( f"/w/{self.workspace}/job_helpers/v2/polars_connection_settings", @@ -894,6 +1006,7 @@ class Windmill: if s3_resource_path == "" else {"s3_resource_path": s3_resource_path}, ).json() + raw_obj.setdefault("s3_bucket", None) return PolarsConnectionSettings(raw_obj) except JSONDecodeError as e: raise Exception( @@ -906,9 +1019,30 @@ class Windmill: ) -> Boto3ConnectionSettings: """ Convenient helpers that takes an S3 resource as input and returns the settings necessary to - initiate an S3 connection using boto3 + initiate an S3 connection using boto3. + + Without a resource path, the connection goes to the workspace storage through Windmill's + S3 proxy when that storage is S3: pass the storage's own bucket as ``Bucket``. The proxy + serves object reads, writes, deletes, listing and multipart uploads of that bucket only; + presigned URLs, other buckets and bucket-level APIs need the storage's own credentials, + which passing the resource path returns. """ s3_resource_path = parse_resource_syntax(s3_resource_path) or s3_resource_path + proxy = self._s3_proxy_connection() if s3_resource_path == "" else None + if proxy is not None: + # botocore addresses a custom endpoint path-style, which the proxy's routes need. + settings = Boto3ConnectionSettings( + { + "endpoint_url": proxy["endpoint_url"], + "region_name": proxy["region"], + "use_ssl": proxy["use_ssl"], + "aws_access_key_id": proxy["access_key"], + "aws_secret_access_key": proxy["secret_key"], + } + ) + if self.verify is not True: + settings["verify"] = self.verify + return settings try: s3_resource = self.post( f"/w/{self.workspace}/job_helpers/v2/s3_resource_info", @@ -2027,6 +2161,17 @@ def get_progress(job_id: Optional[str] = None) -> Any: return _client.get_progress(job_id) +@init_global_client +def worker_is_draining(job_id: Optional[str] = None) -> bool: + """ + Whether the worker running this job has received its shutdown signal. + + A draining worker waits for its current job to finish before exiting. A long-running + script can poll this and return early so the worker can be replaced. + """ + return _client.worker_is_draining(job_id) + + def set_shared_state_pickle(value: Any, path="state.pickle") -> None: """ Set the state in the shared folder using pickle @@ -2739,6 +2884,7 @@ def parse_sql_client_name(name: str) -> tuple[str, Optional[str]]: import asyncio as _asyncio import contextvars as _contextvars +import inspect as _inspect import sys as _sys import traceback as _traceback @@ -2966,6 +3112,64 @@ _workflow_ctx: _contextvars.ContextVar["WorkflowCtx"] = _contextvars.ContextVar( "_workflow_ctx" ) +# Set while a task body runs in its child job: ``"async"`` or ``"sync"`` after +# the kind of function the body is. A flag on the ctx cannot stand in: under +# ``asyncio.gather`` the workflow body keeps replaying beside the task body, and +# its calls must still park rather than run a sibling task's body in this job. +_in_task_body: _contextvars.ContextVar[Optional[str]] = _contextvars.ContextVar( + "_in_task_body", default=None +) + + +def _dispatch_ctx() -> "WorkflowCtx | None": + """The ctx SDK calls dispatch through, or None where they run in place: + outside a workflow, and inside a task body, which is one job and has no + rounds of its own to dispatch or checkpoint a step in.""" + if _in_task_body.get(): + return None + return _workflow_ctx.get(None) + + +async def _resolved(value): + return value + + +def _call_in_task_body(func, caller: str, args, kwargs): + """Run a task called from inside a task body in place, round-tripping its + result as a dispatched one would be. + + The workflow body awaits every task, sync ones included, so an async caller + gets an awaitable back either way; a sync caller gets the value. The scope + is re-marked for the nested body, which may be of the other kind.""" + + async def run_async(coro): + token = _in_task_body.set("async") + try: + return _json_round_trip(await coro) + finally: + _in_task_body.reset(token) + + if _inspect.iscoroutinefunction(func): + return run_async(func(*args, **kwargs)) + token = _in_task_body.set("sync") + try: + result = func(*args, **kwargs) + finally: + _in_task_body.reset(token) + if _asyncio.iscoroutine(result): + return run_async(result) + result = _json_round_trip(result) + return _resolved(result) if caller == "async" else result + + +def _assert_not_inside_task_body(what: str) -> None: + if _in_task_body.get(): + raise RuntimeError( + f"{what} cannot be called from inside a task: a task runs as a single " + "job and cannot suspend or dispatch steps. Call it from the @workflow " + "body instead." + ) + class WorkflowCtx: """Internal context for workflow replay/suspension. @@ -3090,15 +3294,20 @@ class WorkflowCtx: raise _StepSuspend({"mode": "sleep", "key": key, "seconds": seconds, "steps": []}) async def _resolved(self, value): - return value + return await _resolved(value) async def _execute_directly(self, func, **kwargs): + token = _in_task_body.set( + "async" if _inspect.iscoroutinefunction(func) else "sync" + ) try: result = func(**kwargs) if _asyncio.iscoroutine(result): result = await result except Exception as exc: raise _StepFailure(exc) from exc + finally: + _in_task_body.reset(token) raise _StepSuspend({"mode": "step_complete", "steps": [], "result": result}) async def _never_resolve(self): @@ -3340,7 +3549,9 @@ def task( - **v2 (inside @workflow)**: dispatches as a checkpoint step. - **v1 (WM_JOB_ID set, no @workflow)**: dispatches via HTTP API. - - **Standalone**: executes the function body directly. + - **Standalone, or called from inside another v2 task**: executes the + function body directly. A task runs as a single job, so the tasks it + calls run in that same job, without their own options. A task runs as its own job, so its result is always encoded as JSON and decoded back before the caller sees it: a ``datetime`` comes back as a @@ -3420,12 +3631,16 @@ def task( @functools.wraps(func) def wrapper(*args, **kwargs): # WAC v2: inside a @workflow context - ctx = _workflow_ctx.get(None) + ctx = _dispatch_ctx() if ctx is not None: script = task_path if task_path else task_name merged = _merge_args(args, kwargs) return ctx._next_step(task_name, script, func, _task_options=_task_opts, **merged) + caller = _in_task_body.get() + if caller is not None: + return _call_in_task_body(func, caller, args, kwargs) + # WAC v1: running inside a Windmill job but not in a @workflow if ( os.environ.get("WM_JOB_ID") is not None @@ -3504,6 +3719,7 @@ def task_script( _opts = {k: v for k, v in {"timeout": timeout, "tag": tag, "cache_ttl": cache_ttl, "priority": priority, "concurrent_limit": concurrency_limit, "concurrency_key": concurrency_key, "concurrency_time_window_s": concurrency_time_window_s, "retry": _checked_retry(retry)}.items() if v is not None} or None def wrapper(**kwargs): + _assert_not_inside_task_body(f'task_script("{path}")') ctx = _workflow_ctx.get(None) if ctx is not None: return ctx._next_step(name, path, dispatch_type="script", _task_options=_opts, **kwargs) @@ -3543,6 +3759,7 @@ def task_flow( _opts = {k: v for k, v in {"timeout": timeout, "tag": tag, "cache_ttl": cache_ttl, "priority": priority, "concurrent_limit": concurrency_limit, "concurrency_key": concurrency_key, "concurrency_time_window_s": concurrency_time_window_s, "retry": _checked_retry(retry)}.items() if v is not None} or None def wrapper(**kwargs): + _assert_not_inside_task_body(f'task_flow("{path}")') ctx = _workflow_ctx.get(None) if ctx is not None: return ctx._next_step(name, path, dispatch_type="flow", _task_options=_opts, **kwargs) @@ -3577,8 +3794,11 @@ async def step(name: str, fn): ``fn``'s result is encoded as JSON and decoded back before it is returned, so the round that runs the body sees the same types every replay sees: a ``datetime`` comes back as a string, a tuple as a list. + + Called from inside a task body, ``fn`` runs in place and nothing is + checkpointed: a task is a single job and is never replayed. """ - ctx: WorkflowCtx | None = _workflow_ctx.get(None) + ctx = _dispatch_ctx() if ctx is not None: return await ctx._run_inline_step(name, fn) result = fn() @@ -3593,9 +3813,9 @@ async def sleep(seconds: int): """Server-side sleep — suspend the workflow for the given duration without holding a worker. Inside a @workflow, the parent job suspends and auto-resumes after ``seconds``. - Outside a workflow, falls back to ``asyncio.sleep``. + Outside a workflow, or inside a task body, falls back to ``asyncio.sleep``. """ - ctx: WorkflowCtx | None = _workflow_ctx.get(None) + ctx = _dispatch_ctx() if ctx is not None: return await ctx._sleep(seconds) await _asyncio.sleep(seconds) @@ -3633,6 +3853,7 @@ async def wait_for_approval( await step("notify", lambda: send_email(urls["resume"], urls["cancel"])) result = await wait_for_approval(key="manager", timeout=3600) """ + _assert_not_inside_task_body("wait_for_approval()") ctx: WorkflowCtx | None = _workflow_ctx.get(None) if ctx is not None: return await ctx._wait_for_approval( diff --git a/python-client/wmill/wmill/s3_types.py b/python-client/wmill/wmill/s3_types.py index 1b43b65972..058eab68fe 100644 --- a/python-client/wmill/wmill/s3_types.py +++ b/python-client/wmill/wmill/s3_types.py @@ -57,6 +57,7 @@ class PolarsConnectionSettings(dict): """Polars S3 connection settings containing S3FS args and storage options.""" s3fs_args: S3FsArgs storage_options: StorageOptions + s3_bucket: Optional[str] def __getattr__(self, attr): return _item_as_attr(self, attr) @@ -78,6 +79,7 @@ class Boto3ConnectionSettings(dict): class DuckDbConnectionSettings(dict): """DuckDB S3 connection settings as a configuration string.""" connection_settings_str: str + s3_bucket: Optional[str] def __getattr__(self, attr): return _item_as_attr(self, attr) diff --git a/rust-client/src/client.rs b/rust-client/src/client.rs index bf47e7e95a..ea3d92bf28 100644 --- a/rust-client/src/client.rs +++ b/rust-client/src/client.rs @@ -412,6 +412,7 @@ impl Windmill { resource_type: resource_type.to_owned(), labels: None, ws_specific: None, + preserve_on_behalf_of: None, }, // Some(true), None, @@ -429,6 +430,7 @@ impl Windmill { resource_type: Some(resource_type.to_owned()), labels: None, ws_specific: None, + preserve_on_behalf_of: None, }, ) .await?; diff --git a/system_prompts/README.md b/system_prompts/README.md index cc16473c6c..9051a71112 100644 --- a/system_prompts/README.md +++ b/system_prompts/README.md @@ -46,6 +46,8 @@ a CLI-only workflow file (`flow-cli.md`, `script-cli.md`, `raw-app-cli.md`). | resources | `getResourcePrompt()` | `resources` | `resources.md` | | workflow-as-code | `getWorkflowAsCodePrompt(lang)` | `write-workflow-as-code` | `workflow-as-code.md`, the WAC SDK | | pipeline | `getPipelinePrompt()` | `write-pipeline` | `pipeline-base.md` | +| data tables | `getDatatablePrompt()` | `datatables` | `datatable.md` | +| workspace settings | `getWorkspaceSettingsPrompt()` | `workspace-settings` | `workspace-settings.md` | | triggers, schedules, preview, CLI commands | — | same names | CLI only | The app chat embeds `RAW_APP_BASE` directly (`chat/app/core.ts`). diff --git a/system_prompts/auto-generated/cli/cli-commands.md b/system_prompts/auto-generated/cli/cli-commands.md index 6fb6357b2b..c2d1c39ab9 100644 --- a/system_prompts/auto-generated/cli/cli-commands.md +++ b/system_prompts/auto-generated/cli/cli-commands.md @@ -30,7 +30,7 @@ app related commands - `app dev [app_folder:string]` - Start a development server for building apps with live reload and hot module replacement - `--port ` - Port to run the dev server on (will find next available port if occupied) - `--host ` - Host to bind the dev server to - - `--entry ` - Entry point file (default: index.ts for Svelte/Vue, index.tsx otherwise) + - `--entry ` - Entry point file (default: index.ts for Svelte, index.tsx otherwise) - `--no-open` - Don't automatically open the browser - `--recording` - Frame the app in a shell with a Record button, to capture a replayable session recording of the app under development - `app lint [app_folder:string]` - Lint a raw app folder to validate structure and buildability @@ -41,7 +41,7 @@ app related commands - `app new` - create a new raw app from a template - `--summary ` - App summary (short description). Skips the prompt when provided. Triggers non-interactive mode. - `--path ` - App path (e.g., f/folder/my_app or u/username/my_app). Skips the prompt when provided. Triggers non-interactive mode. - - `--framework ` - Framework template: react19 | react18 | svelte5 | vue. Skips the prompt when provided. Triggers non-interactive mode. + - `--framework ` - Framework template: react19 | react18 | svelte5. Skips the prompt when provided. Triggers non-interactive mode. - `--datatable ` - Datatable to wire up. Without this flag in non-interactive mode, no datatable is configured. - `--schema ` - Schema to use with --datatable. If it doesn't exist yet, a sql_to_apply/ migration (CREATE SCHEMA IF NOT EXISTS) is written for it. - `--overwrite` - Overwrite the target directory if it already exists, without prompting. @@ -84,8 +84,10 @@ datatable related commands - `datatable migrate` - manage datatable migrations - `datatable migrate new ` - scaffold a new migration (.up.sql / .down.sql files) - `-d --datatable ` - Target datatable (default: main) + - `-s --schemas ` - Comma-separated schemas the migration changes, written as its `-- schemas` line. Without it the migration applies to the whole database and every later migration waits for it - `datatable migrate up` - apply all pending migrations to the main datatable (or one via --datatable) - `-d --datatable ` - Target datatable (default: main) + - `--schema ` - Apply only the pending migrations that declare this schema; refused while an earlier overlapping migration is pending - `datatable migrate down` - roll back the most recent migration on the main datatable (or one via --datatable) - `-d --datatable ` - Target datatable (default: main) - `datatable migrate status` - show applied and pending migrations on the main datatable (or one via --datatable) @@ -181,6 +183,7 @@ flow related commands - `--remote` - Use deployed workspace scripts for PathScript steps instead of local files. - `--step ` - Run only the named step instead of the whole flow. Honors --data as the step's args and --remote / local-PathScript resolution the same way the full-flow preview does. - `--tag ` - Override the worker tag the preview is dispatched to (e.g. to route it to dev workers instead of the flow's default tag). + - `--on-behalf-of ` - Run the preview as this user or group (an email, u/ or g/) instead of yourself, e.g. to reproduce a run_on_behalf_of identity. Requires being an admin or a member of wm_deployers. - `flow new ` - create a new empty flow - `--summary ` - flow summary - `--description ` - flow description @@ -579,6 +582,7 @@ script related commands - `-d --data ` - Inputs specified as a JSON string or a file using @ or stdin using @-. A resource argument is the bare string $res: as its whole value, and a variable argument is the bare string $var: — not an object wrapper keyed on $res/$var, and not a plain path. - `-s --silent` - Do not output anything other than the final output. Useful for scripting. - `--tag ` - Override the worker tag the preview is dispatched to (e.g. to route it to dev workers instead of the script's default tag). + - `--on-behalf-of ` - Run the preview as this user or group (an email, u/ or g/) instead of yourself, e.g. to reproduce a run_on_behalf_of identity. Requires being an admin or a member of wm_deployers. - `script new ` - create a new script - `--summary ` - script summary - `--description ` - script description @@ -616,6 +620,7 @@ sync local with a remote workspaces or the opposite (push or pull) - `--include-users` - Include syncing users - `--include-groups` - Include syncing groups - `--include-settings` - Include syncing workspace settings + - `--include-datatable-permissions` - With --include-settings, also sync who may connect to each data table as which role - `--include-key` - Include workspace encryption key - `--keep-deleted` - Do not delete local files for items that no longer exist on the remote workspace. Only adds and updates. - `--skip-branch-validation` - Skip git branch validation and prompts @@ -647,6 +652,7 @@ sync local with a remote workspaces or the opposite (push or pull) - `--include-users` - Include syncing users - `--include-groups` - Include syncing groups - `--include-settings` - Include syncing workspace settings + - `--include-datatable-permissions` - With --include-settings, also sync who may connect to each data table as which role - `--include-key` - Include workspace encryption key - `--skip-reencrypt-on-key-change` - When the pushed encryption key differs from the remote, do NOT re-encrypt existing remote secrets. Only safe if they are already encrypted with the new key (e.g. workspace/instance migration). Default is to re-encrypt. - `--keep-deleted` - Do not delete remote items that no longer exist locally. Only adds and updates. @@ -840,6 +846,13 @@ Arguments (omit both to be prompted interactively): - `--team-id ` - Slack team id - `--team-name ` - Slack team name - `workspace disconnect-slack` - Clear slack_team_id / slack_name on the active workspace (marks the workspace as disconnected). Does NOT remove the bot token variable/resource/folder/group — delete those from the local sync folder and run 'wmill sync push' to tear them down. Does NOT remove the workspace-level OAuth override — set slack_oauth_client_id/_secret to '' in settings.yaml and push. +- `workspace get-settings` - Print the active workspace's settings in the layout of the settings.yaml that 'wmill sync' writes. Secrets show as __SENSITIVE_AND_UNCHANGED__ unless --encrypted. Admin only. + - `--encrypted` - Write secrets encrypted with the workspace key, as 'wmill sync pull' does + - `--json` - Output as JSON +- `workspace apply-settings ` - Apply a settings document (YAML or JSON, in the layout of settings.yaml) to the active workspace. Only the settings the file states are changed, unless --replace; a setting set to null is cleared. A secret left as __SENSITIVE_AND_UNCHANGED__ keeps its value. Shows the changes and asks before applying. Admin only. + - `--dry-run` - Only show the changes + - `--replace` - Also clear the settings the file omits, as 'wmill sync push' does + - `-y --yes` - Apply without asking diff --git a/system_prompts/auto-generated/flow.md b/system_prompts/auto-generated/flow.md index e5dd862a3b..b6ba8de664 100644 --- a/system_prompts/auto-generated/flow.md +++ b/system_prompts/auto-generated/flow.md @@ -149,6 +149,10 @@ needs becomes unreachable. references. A spread, a call or a computed key leaves the composer unable to tell which input feeds which field, so it offers no control at all — a bare `flow_input.x` for the whole object is read instead as that one input carrying every field +- A step linked to a saved agent (`agent` set) has no `provider` of its own. It exposes the same + two controls through its `model` and `reasoning_effort` inputs, which replace what the agent + saved: `"model": { "type": "javascript", "expr": "flow_input.model" }`. An empty model keeps the + saved one, an empty effort sends none, and the provider resource always stays the agent's - `memory` is what lets the agent see earlier turns; without it every message starts from nothing - `streaming` on makes the answer and its thinking appear token by token instead of all at once - `user_attachments` points at a flow input typed as an array of s3 objects @@ -582,6 +586,14 @@ In the flow schema, set the property type to `"object"` with format `"resource-{ } ``` +### When No Resource Type Fits + +A connection still comes in as one resource input, not as separate string inputs (a URL, a token) or a variable read inside a step: type the input `resource-c_` with a custom resource type holding the service's connection fields, its secret in a variable the resource references. The `c_` prefix of custom types keeps one apart from a hub type synced later under the same name. + +- If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. +- Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it. +- A plain variable is fine when the user asks for it. + ### As Step Input (Static Reference) Reference a specific resource using `$res:` prefix: @@ -598,4 +610,4 @@ Reference a specific resource using `$res:` prefix: ## OpenFlow Schema -{"OpenFlow":{"type":"object","description":"Top-level flow definition containing metadata, configuration, and the flow structure","properties":{"summary":{"type":"string","description":"Short description of what this flow does"},"description":{"type":"string","description":"Detailed documentation for this flow"},"value":{"$ref":"#/components/schemas/FlowValue"},"schema":{"type":"object","description":"JSON Schema for flow inputs. Use this to define input parameters, their types, defaults, and validation. For resource inputs, set type to 'object' and format to 'resource-' (e.g., 'resource-stripe')"},"on_behalf_of_email":{"type":"string","description":"Address of the account the flow runs on behalf of. Derived from on_behalf_of on read; accepted on write, where it is resolved to the account it names."},"on_behalf_of":{"type":"string","description":"The flow runs with the permissions of this identity: u/{username}, g/{group}, or a bare email when the username is itself email-shaped. The only stored half of the identity; on_behalf_of_email is derived from it. Omit it when writing and it is resolved from that address instead."}},"required":["summary","value"]},"FlowValue":{"type":"object","description":"The flow structure containing modules and optional preprocessor/failure handlers","properties":{"modules":{"type":"array","description":"Array of steps that execute in sequence. Each step can be a script, subflow, loop, or branch","items":{"$ref":"#/components/schemas/FlowModule"}},"failure_module":{"description":"Special module that executes when the flow fails. Receives error object with message, name, stack, and step_id. Must have id 'failure'. Only supports script/rawscript types","$ref":"#/components/schemas/FlowModule"},"preprocessor_module":{"description":"Special module that runs before the first step on external triggers. Must have id 'preprocessor'. Only supports script/rawscript types. Cannot reference other step results","$ref":"#/components/schemas/FlowModule"},"same_worker":{"type":"boolean","description":"If true, all steps run on the same worker for better performance"},"preserve_step_tags":{"type":"boolean","description":"If true and the flow runs on a custom worker tag, steps that declare their own non-empty tag run on it instead of inheriting the flow tag. Steps without their own tag still inherit the flow tag."},"concurrent_limit":{"type":"number","description":"Maximum number of concurrent executions of this flow"},"concurrency_key":{"type":"string","description":"Expression to group concurrent executions (e.g., by user ID)"},"concurrency_time_window_s":{"type":"number","description":"Time window in seconds for concurrent_limit"},"debounce_delay_s":{"type":"integer","description":"Delay in seconds to debounce flow executions"},"debounce_key":{"type":"string","description":"Expression to group debounced executions"},"debounce_args_to_accumulate":{"type":"array","description":"Arguments to accumulate across debounced executions","items":{"type":"string"}},"max_total_debouncing_time":{"type":"integer","description":"Maximum total time in seconds that a job can be debounced"},"max_total_debounces_amount":{"type":"integer","description":"Maximum number of times a job can be debounced"},"skip_expr":{"type":"string","description":"JavaScript expression to conditionally skip the entire flow"},"cache_ttl":{"type":"number","description":"Cache duration in seconds for flow results"},"cache_ignore_s3_path":{"type":"boolean"},"delete_after_secs":{"type":"integer","description":"If set, delete the flow job's args, result and logs after this many seconds following job completion"},"flow_env":{"type":"object","description":"Environment variables available to all steps. Values can be strings, JSON values, or special references: '$var:path' (workspace variable) or '$res:path' (resource).","additionalProperties":{}},"priority":{"type":"number","description":"Execution priority (higher numbers run first)"},"early_return":{"type":"string","description":"JavaScript expression to return early from the flow"},"chat_input_enabled":{"type":"boolean","description":"Whether this flow accepts chat-style input"},"notes":{"type":"array","description":"Sticky notes attached to the flow","items":{"$ref":"#/components/schemas/FlowNote"}},"groups":{"type":"array","description":"Semantic groups of modules for organizational purposes","items":{"$ref":"#/components/schemas/FlowGroup"}}},"required":["modules"]},"Retry":{"type":"object","description":"Retry configuration for failed module executions","properties":{"constant":{"type":"object","description":"Retry with constant delay between attempts","properties":{"attempts":{"type":"integer","description":"Number of retry attempts"},"seconds":{"type":"integer","description":"Seconds to wait between retries"}}},"exponential":{"type":"object","description":"Retry with exponential backoff: the n-th retry waits multiplier \u00d7 seconds^n","properties":{"attempts":{"type":"integer","description":"Number of retry attempts"},"multiplier":{"type":"integer","description":"Multiplier for exponential backoff"},"seconds":{"type":"integer","minimum":1,"description":"Base of the exponential (seconds); the n-th retry waits multiplier \u00d7 seconds^n, where n counts constant retries too"},"random_factor":{"type":"integer","minimum":0,"maximum":100,"description":"Random jitter percentage (0-100) to avoid thundering herd"}}},"retry_if":{"$ref":"#/components/schemas/RetryIf"}}},"FlowNote":{"type":"object","description":"A sticky note attached to a flow for documentation and annotation","properties":{"id":{"type":"string","description":"Unique identifier for the note"},"text":{"type":"string","description":"Content of the note"},"position":{"type":"object","description":"Position of the note in the flow editor","properties":{"x":{"type":"number","description":"X coordinate"},"y":{"type":"number","description":"Y coordinate"}},"required":["x","y"]},"size":{"type":"object","description":"Size of the note in the flow editor","properties":{"width":{"type":"number","description":"Width in pixels"},"height":{"type":"number","description":"Height in pixels"}},"required":["width","height"]},"color":{"type":"string","description":"Color of the note, one of: yellow, blue, green, purple, pink, orange, red, cyan, lime, gray. Any other value renders unstyled."},"type":{"type":"string","enum":["free","group"],"description":"Type of note - 'free' for standalone notes. 'group' notes are deprecated; segment a flow with FlowValue.groups instead."},"locked":{"type":"boolean","default":false,"description":"Whether the note is locked and cannot be edited or moved"},"contained_node_ids":{"type":"array","items":{"type":"string"},"description":"For group notes, the IDs of nodes contained within this group"}},"required":["id","text","color","type"]},"FlowGroup":{"type":"object","description":"A semantic group of flow modules for organizational purposes. Does not affect execution \u2014 modules remain in their original position in the flow. Groups provide naming and collapsibility in the editor. Members are computed dynamically from all nodes on paths between start_id and end_id.","properties":{"summary":{"type":"string","description":"Display name for this group"},"note":{"type":"string","description":"Markdown note shown below the group header"},"autocollapse":{"type":"boolean","default":false,"description":"If true, this group is collapsed by default in the flow editor. UI hint only."},"start_id":{"type":"string","description":"ID of the first flow module in this group (topological entry point)"},"end_id":{"type":"string","description":"ID of the last flow module in this group (topological exit point)"},"color":{"type":"string","description":"Color for the group in the flow editor, one of: yellow, blue, green, purple, pink, orange, red, cyan, lime, gray. Omit it to let the editor pick one."}},"required":["start_id","end_id"]},"RetryIf":{"type":"object","description":"Conditional retry based on error or result","properties":{"expr":{"type":"string","description":"JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables"}},"required":["expr"]},"StopAfterIf":{"type":"object","description":"Early termination condition for a module","properties":{"skip_if_stopped":{"type":"boolean","description":"If true, following steps are skipped when this condition triggers"},"expr":{"type":"string","description":"JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"},"error_message":{"type":"string","nullable":true,"description":"Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised."},"error_include_result":{"type":"boolean","description":"When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false."}},"required":["expr"]},"FlowModule":{"type":"object","description":"A single step in a flow. Can be a script, subflow, loop, or branch","properties":{"id":{"type":"string","description":"Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"},"value":{"$ref":"#/components/schemas/FlowModuleValue"},"stop_after_if":{"description":"Early termination condition evaluated after this step completes","$ref":"#/components/schemas/StopAfterIf"},"stop_after_all_iters_if":{"description":"For loops only - early termination condition evaluated after all iterations complete","$ref":"#/components/schemas/StopAfterIf"},"skip_if":{"type":"object","description":"Conditionally skip this step based on previous results or flow inputs","properties":{"expr":{"type":"string","description":"JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.'"}},"required":["expr"]},"sleep":{"description":"Delay before executing this step (in seconds or as expression)","$ref":"#/components/schemas/InputTransform"},"cache_ttl":{"type":"number","description":"Cache duration in seconds for this step's results"},"cache_ignore_s3_path":{"type":"boolean"},"timeout":{"description":"Maximum execution time in seconds (static value or expression)","$ref":"#/components/schemas/InputTransform"},"delete_after_secs":{"type":"integer","description":"If set, delete the step's args, result and logs after this many seconds following job completion"},"summary":{"type":"string","description":"Short description of what this step does"},"mock":{"type":"object","description":"Mock configuration for testing without executing the actual step","properties":{"enabled":{"type":"boolean","description":"If true, return mock value instead of executing"},"return_value":{"description":"Value to return when mocked"}}},"suspend":{"type":"object","description":"Configuration for approval/resume steps that wait for user input","properties":{"required_events":{"type":"integer","description":"Number of approvals required before continuing"},"timeout":{"type":"integer","description":"Timeout in seconds before auto-continuing or canceling"},"resume_form":{"type":"object","description":"Form schema for collecting input when resuming","properties":{"schema":{"type":"object","description":"JSON Schema for the resume form"}}},"user_auth_required":{"type":"boolean","description":"If true, only authenticated users can approve"},"user_groups_required":{"description":"Expression or list of groups that can approve","$ref":"#/components/schemas/InputTransform"},"self_approval_disabled":{"type":"boolean","description":"If true, the user who started the flow cannot approve"},"hide_cancel":{"type":"boolean","description":"If true, hide the cancel button on the approval form"},"continue_on_disapprove_timeout":{"type":"boolean","description":"If true, continue flow on timeout instead of canceling"},"skin":{"type":"string","enum":["detailed","minimal"],"description":"How the approval request is presented, on the approval page and in Slack/Teams approval messages. 'detailed' (used when unset) shows the flow details (arguments, graph, approvers); 'minimal' shows only the request: the step description, form and approve/reject actions"}}},"priority":{"type":"number","description":"Execution priority for this step (higher numbers run first)"},"continue_on_error":{"type":"boolean","description":"If true, flow continues even if this step fails"},"job_token_scopes":{"type":"array","nullable":true,"items":{"type":"string"},"description":"Scopes the token of this step's jobs is restricted to (domain:action[:resource], e.g. oidc:write), on top of the flow's own restriction: a step can only narrow it. Applies to everything the step runs (loop and branch bodies, AI agent tools)."},"retry":{"description":"Retry configuration if this step fails","$ref":"#/components/schemas/Retry"},"debouncing":{"description":"Debounce configuration for this step (EE only)","type":"object","properties":{"debounce_delay_s":{"type":"integer","description":"Delay in seconds to debounce this step's executions across flow runs"},"debounce_key":{"type":"string","description":"Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/-"},"debounce_args_to_accumulate":{"type":"array","description":"Array-type arguments to accumulate across debounced executions","items":{"type":"string"}},"max_total_debouncing_time":{"type":"integer","description":"Maximum total time in seconds before forced execution"},"max_total_debounces_amount":{"type":"integer","description":"Maximum number of debounces before forced execution"}}}},"required":["value","id"]},"InputTransform":{"description":"Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs","oneOf":[{"$ref":"#/components/schemas/StaticTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type","mapping":{"static":"#/components/schemas/StaticTransform","javascript":"#/components/schemas/JavascriptTransform","ai":"#/components/schemas/AiTransform"}}},"StaticTransform":{"type":"object","description":"Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'","properties":{"value":{"description":"The static value. For resources, use format '$res:path/to/resource'"},"type":{"type":"string","enum":["static"]}},"required":["type"]},"JavascriptTransform":{"type":"object","description":"JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')","properties":{"expr":{"type":"string","description":"JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"},"type":{"type":"string","enum":["javascript"]}},"required":["expr","type"]},"AiTransform":{"type":"object","description":"Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.","properties":{"type":{"type":"string","enum":["ai"]}},"required":["type"]},"AIProviderKind":{"type":"string","description":"Supported AI provider types","enum":["openai","azure_openai","azure_foundry","anthropic","mistral","deepseek","googleai","groq","openrouter","togetherai","customai","aws_bedrock","typesafe","cloudflare"]},"ProviderConfig":{"type":"object","description":"Complete AI provider configuration with resource reference and model selection","properties":{"kind":{"$ref":"#/components/schemas/AIProviderKind"},"resource":{"type":"string","description":"Resource reference in format '$res:{resource_path}' pointing to provider credentials"},"model":{"type":"string","description":"Model identifier (e.g., 'gpt-4', 'claude-3-opus-20240229', 'gemini-pro')"},"reasoning_effort":{"type":"string","description":"Provider-native reasoning effort token (e.g. 'low', 'high', 'none') for models that support extended thinking. Optional; unset leaves the provider default."}},"required":["kind","resource","model"]},"StaticProviderTransform":{"type":"object","description":"Static provider configuration passed directly to the AI agent","properties":{"value":{"$ref":"#/components/schemas/ProviderConfig"},"type":{"type":"string","enum":["static"]}},"required":["type","value"]},"ProviderTransform":{"description":"Provider configuration - can be static (ProviderConfig), JavaScript expression, or AI-determined","oneOf":[{"$ref":"#/components/schemas/StaticProviderTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type","mapping":{"static":"#/components/schemas/StaticProviderTransform","javascript":"#/components/schemas/JavascriptTransform","ai":"#/components/schemas/AiTransform"}}},"MemoryOff":{"type":"object","description":"No conversation memory/context","properties":{"kind":{"type":"string","enum":["off"]}},"required":["kind"]},"MemoryWindow":{"type":"object","description":"Keeps the most recent messages of the memory named by the run's memory id (or the step's\n`memory_id`). Without a memory id the agent runs without memory.\n","properties":{"kind":{"type":"string","enum":["window"]},"context_length":{"type":"integer","description":"Number of most recent messages to load and store. 0 turns memory off."}},"required":["kind","context_length"]},"MemoryAuto":{"type":"object","deprecated":true,"description":"Deprecated, still read as it was written: the run's memory id, else the `memory_id` here.\nThe step's own `memory_id` is not read while this kind is set; switch the kind to `window`\nto use it. Without a `context_length`, or with 0, it is `off` and reads `previous_messages`.\n","properties":{"kind":{"type":"string","enum":["auto"]},"context_length":{"type":"integer","description":"Maximum number of messages to retain in context"},"memory_id":{"type":"string","description":"Identifier for persistent memory across agent invocations"}},"required":["kind"]},"MemoryCompaction":{"type":"object","description":"Keeps the whole memory named by the run's memory id (or the step's `memory_id`), replacing\nits older part with a summary as the conversation approaches the model's context window.\nWithout a memory id the agent runs without memory, and compaction bounds the run's own loop.\n","properties":{"kind":{"type":"string","enum":["compaction"]},"context_window":{"type":"integer","description":"Overrides the context window looked up from the model, in tokens. Only a model\nWindmill does not know needs one; those fall back to 128000.\n"}},"required":["kind"]},"MemoryMessage":{"type":"object","description":"A single message in conversation history","properties":{"role":{"type":"string","enum":["user","assistant","system"]},"content":{"type":"string"}},"required":["role","content"]},"MemoryManual":{"type":"object","deprecated":true,"description":"Deprecated, still read as it was written. Move the step to `off` with `previous_messages` instead.","properties":{"kind":{"type":"string","enum":["manual"]},"messages":{"type":"array","items":{"$ref":"#/components/schemas/MemoryMessage"}}},"required":["kind","messages"]},"MemoryConfig":{"description":"Managed memory, stored by Windmill and replayed with each request. The memory is named by a memory id, see `memory_id`. While it is off, a step can supply its history in `previous_messages`.","oneOf":[{"$ref":"#/components/schemas/MemoryOff"},{"$ref":"#/components/schemas/MemoryWindow"},{"$ref":"#/components/schemas/MemoryCompaction"},{"$ref":"#/components/schemas/MemoryAuto"},{"$ref":"#/components/schemas/MemoryManual"}],"discriminator":{"propertyName":"kind","mapping":{"off":"#/components/schemas/MemoryOff","window":"#/components/schemas/MemoryWindow","compaction":"#/components/schemas/MemoryCompaction","auto":"#/components/schemas/MemoryAuto","manual":"#/components/schemas/MemoryManual"}}},"StaticMemoryTransform":{"type":"object","description":"Static memory configuration passed directly to the AI agent","properties":{"value":{"$ref":"#/components/schemas/MemoryConfig"},"type":{"type":"string","enum":["static"]}},"required":["type","value"]},"MemoryTransform":{"description":"Memory configuration - can be static (MemoryConfig), JavaScript expression, or AI-determined","oneOf":[{"$ref":"#/components/schemas/StaticMemoryTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type","mapping":{"static":"#/components/schemas/StaticMemoryTransform","javascript":"#/components/schemas/JavascriptTransform","ai":"#/components/schemas/AiTransform"}}},"FlowModuleValue":{"description":"The actual implementation of a flow step. Can be a script (inline or referenced), subflow, loop, branch, or special module type","oneOf":[{"$ref":"#/components/schemas/RawScript"},{"$ref":"#/components/schemas/PathScript"},{"$ref":"#/components/schemas/PathFlow"},{"$ref":"#/components/schemas/ForloopFlow"},{"$ref":"#/components/schemas/WhileloopFlow"},{"$ref":"#/components/schemas/BranchOne"},{"$ref":"#/components/schemas/BranchAll"},{"$ref":"#/components/schemas/Identity"},{"$ref":"#/components/schemas/AiAgent"},{"$ref":"#/components/schemas/AiDecision"}],"discriminator":{"propertyName":"type","mapping":{"rawscript":"#/components/schemas/RawScript","script":"#/components/schemas/PathScript","flow":"#/components/schemas/PathFlow","forloopflow":"#/components/schemas/ForloopFlow","whileloopflow":"#/components/schemas/WhileloopFlow","branchone":"#/components/schemas/BranchOne","branchall":"#/components/schemas/BranchAll","identity":"#/components/schemas/Identity","aiagent":"#/components/schemas/AiAgent","aidecision":"#/components/schemas/AiDecision"}}},"RawScript":{"type":"object","description":"Inline script with code defined directly in the flow. Use 'bun' as default language if unspecified. The script receives arguments from input_transforms","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"content":{"type":"string","description":"The script source code. Should export a 'main' function"},"language":{"type":"string","description":"Programming language for this script","enum":["deno","bun","bunnative","python3","go","bash","powershell","postgresql","mysql","bigquery","snowflake","mssql","oracledb","graphql","nativets","php","rust","ansible","csharp","nu","java","ruby","rlang","duckdb"]},"path":{"type":"string","description":"Optional path for saving this script"},"lock":{"type":"string","description":"Lock file content for dependencies"},"type":{"type":"string","enum":["rawscript"]},"tag":{"type":"string","description":"Worker group tag for execution routing"},"concurrent_limit":{"type":"number","description":"Maximum concurrent executions of this script"},"concurrency_time_window_s":{"type":"number","description":"Time window for concurrent_limit"},"custom_concurrency_key":{"type":"string","description":"Custom key for grouping concurrent executions"},"is_trigger":{"type":"boolean","description":"If true, this script is a trigger that can start the flow"},"assets":{"type":"array","description":"External resources this script accesses (S3 objects, resources, etc.)","items":{"type":"object","required":["path","kind"],"properties":{"path":{"type":"string","description":"Path to the asset"},"kind":{"type":"string","description":"Type of asset","enum":["s3object","resource","ducklake","datatable","volume","dbt"]},"access_type":{"type":"string","nullable":true,"description":"Access level for this asset","enum":["r","w","rw"]},"alt_access_type":{"type":"string","nullable":true,"description":"Alternative access level","enum":["r","w","rw"]}}}}},"required":["type","content","language","input_transforms"]},"PathScript":{"type":"object","description":"Reference to an existing script by path. Use this when calling a previously saved script instead of writing inline code","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"path":{"type":"string","description":"Path to the script in the workspace (e.g., 'f/scripts/send_email')"},"hash":{"type":"string","description":"Optional specific version hash of the script to use"},"type":{"type":"string","enum":["script"]},"tag_override":{"type":"string","description":"Override the script's default worker group tag"},"is_trigger":{"type":"boolean","description":"If true, this script is a trigger that can start the flow"}},"required":["type","path","input_transforms"]},"PathFlow":{"type":"object","description":"Reference to an existing flow by path. Use this to call another flow as a subflow","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the subflow's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"path":{"type":"string","description":"Path to the flow in the workspace (e.g., 'f/flows/process_user')"},"type":{"type":"string","enum":["flow"]}},"required":["type","path","input_transforms"]},"ForloopFlow":{"type":"object","description":"Executes nested modules in a loop over an iterator. Inside the loop, use 'flow_input.iter.value' to access the current iteration value, and 'flow_input.iter.index' for the index. Supports parallel execution for better performance on I/O-bound operations","properties":{"modules":{"type":"array","description":"Steps to execute for each iteration. These can reference the iteration value via 'flow_input.iter.value'","items":{"$ref":"#/components/schemas/FlowModule"}},"iterator":{"description":"JavaScript expression that returns an array to iterate over. Can reference 'results.step_id' or 'flow_input'","$ref":"#/components/schemas/InputTransform"},"skip_failures":{"type":"boolean","description":"If true, iteration failures don't stop the loop. Failed iterations return null"},"type":{"type":"string","enum":["forloopflow"]},"parallel":{"type":"boolean","description":"If true, iterations run concurrently (faster for I/O-bound operations). Use with parallelism to control concurrency"},"parallelism":{"description":"Maximum number of concurrent iterations when parallel=true. Limits resource usage. Can be static number or expression","$ref":"#/components/schemas/InputTransform"},"squash":{"type":"boolean"}},"required":["modules","iterator","skip_failures","type"]},"WhileloopFlow":{"type":"object","description":"Executes nested modules repeatedly until stopped. The implicit iterator is the iteration counter, so 'flow_input.iter.value' equals 'flow_input.iter.index' (0, 1, 2, ...) and never carries state. To carry state across iterations, a step reads its own previous-iteration result via 'results.' with a first-iteration fallback - the loop's stop_after_if must then be on that inner step (a plain single-step body with stop_after_if on the loop module does not resolve 'results' across iterations and never terminates); plain counters can instead be derived from 'flow_input.iter.index', which works in every configuration. stop_after_if is evaluated after each iteration - on the loop module 'result' is the last iteration's result","properties":{"modules":{"type":"array","description":"Steps to execute in each iteration","items":{"$ref":"#/components/schemas/FlowModule"}},"skip_failures":{"type":"boolean","description":"If true, iteration failures don't stop the loop. Failed iterations return null"},"type":{"type":"string","enum":["whileloopflow"]},"parallel":{"type":"boolean","description":"If true, iterations run concurrently (use with caution in while loops)"},"parallelism":{"description":"Maximum number of concurrent iterations when parallel=true","$ref":"#/components/schemas/InputTransform"},"squash":{"type":"boolean"}},"required":["modules","skip_failures","type"]},"BranchOne":{"type":"object","description":"Conditional branching where only the first matching branch executes. Branches are evaluated in order, and the first one with a true expression runs. If no branches match, the default branch executes","properties":{"branches":{"type":"array","description":"Array of branches to evaluate in order. The first branch with expr evaluating to true executes","items":{"type":"object","properties":{"summary":{"type":"string","description":"Short description of this branch condition"},"expr":{"type":"string","description":"JavaScript expression that returns boolean. Can use 'results.step_id' or 'flow_input'. First true expr wins"},"modules":{"type":"array","description":"Steps to execute if this branch's expr is true","items":{"$ref":"#/components/schemas/FlowModule"}}},"required":["modules","expr"]}},"default":{"type":"array","description":"Steps to execute if no branch expressions match","items":{"$ref":"#/components/schemas/FlowModule"}},"type":{"type":"string","enum":["branchone"]}},"required":["branches","default","type"]},"BranchAll":{"type":"object","description":"Parallel branching where all branches execute simultaneously. Unlike BranchOne, all branches run regardless of conditions. Useful for executing independent tasks concurrently","properties":{"branches":{"type":"array","description":"Array of branches that all execute (either in parallel or sequentially)","items":{"type":"object","properties":{"summary":{"type":"string","description":"Short description of this branch's purpose"},"skip_failure":{"type":"boolean","description":"If true, failure in this branch doesn't fail the entire flow"},"modules":{"type":"array","description":"Steps to execute in this branch","items":{"$ref":"#/components/schemas/FlowModule"}}},"required":["modules"]}},"type":{"type":"string","enum":["branchall"]},"parallel":{"type":"boolean","description":"If true, all branches execute concurrently. If false, they execute sequentially"}},"required":["branches","type"]},"AgentTool":{"type":"object","description":"A tool available to an AI agent. Can be a flow module or an external MCP (Model Context Protocol) tool","properties":{"id":{"type":"string","description":"Unique identifier for this tool. Cannot contain spaces - use underscores instead (e.g., 'get_user_data' not 'get user data')"},"summary":{"type":"string","description":"The name the AI agent calls this tool by, not a human label. On a flowmodule tool it must match ^[a-zA-Z0-9_]+$ - letters, numbers and underscores only (e.g. 'search_documentation', not 'Search documentation') - and always be set; on an mcp or websearch tool it is a plain label. Put the human-readable explanation in 'description'."},"description":{"type":"string","description":"Free-text description of the tool given to the AI to decide when and how to call it. Overrides the description auto-derived from the underlying script."},"job_token_scopes":{"type":"array","nullable":true,"items":{"type":"string"},"description":"Scopes the token of this tool's jobs is restricted to, on top of the agent step's own restriction: a tool can only narrow it."},"value":{"$ref":"#/components/schemas/ToolValue"}},"required":["id","value"]},"ToolValue":{"description":"The implementation of a tool. Can be a flow module (script/flow) or an MCP tool reference","oneOf":[{"$ref":"#/components/schemas/FlowModuleTool"},{"$ref":"#/components/schemas/McpToolValue"},{"$ref":"#/components/schemas/WebsearchToolValue"}],"discriminator":{"propertyName":"tool_type","mapping":{"flowmodule":"#/components/schemas/FlowModuleTool","mcp":"#/components/schemas/McpToolValue","websearch":"#/components/schemas/WebsearchToolValue"}}},"FlowModuleTool":{"description":"A tool implemented as a flow module (script, flow, etc.). The AI can call this like any other flow module","allOf":[{"type":"object","properties":{"tool_type":{"type":"string","enum":["flowmodule"]}},"required":["tool_type"]},{"$ref":"#/components/schemas/FlowModuleValue"}]},"WebsearchToolValue":{"type":"object","description":"A tool implemented as a websearch tool. The AI can call this like any other websearch tool","properties":{"tool_type":{"type":"string","enum":["websearch"]}},"required":["tool_type"]},"McpToolValue":{"type":"object","description":"Reference to an external MCP (Model Context Protocol) tool. The AI can call tools from MCP servers","properties":{"tool_type":{"type":"string","enum":["mcp"]},"resource_path":{"type":"string","description":"Path to the MCP resource/server configuration"},"include_tools":{"type":"array","description":"Whitelist of specific tools to include from this MCP server","items":{"type":"string"}},"exclude_tools":{"type":"array","description":"Blacklist of tools to exclude from this MCP server","items":{"type":"string"}}},"required":["tool_type","resource_path"]},"AiAgent":{"type":"object","description":"AI agent step that can use tools to accomplish tasks. The agent receives inputs and can call any of its configured tools to complete the task","properties":{"input_transforms":{"type":"object","description":"Input parameters for the AI agent mapped to their values","properties":{"provider":{"$ref":"#/components/schemas/ProviderTransform"},"output_type":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Output format type.\nValid values: 'text' (default) - plain text response, 'image' - image generation\n"},"user_message":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"The user's prompt/message to the AI agent. Supports variable interpolation with\nflow.input syntax. Required unless memory is off and `previous_messages` supplies\nthe prompt; image output always needs it.\n"},"system_prompt":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"System instructions that guide the AI's behavior, persona, and response style. Optional."},"streaming":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Boolean. If true, stream the AI response incrementally.\nStreaming events include: token_delta, reasoning_token_delta, tool_call, tool_call_arguments, tool_execution, tool_result\n"},"memory":{"$ref":"#/components/schemas/MemoryTransform"},"memory_id":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"String. Names the memory this step reads and writes, overriding the memory id the run\nwas started with (the chat conversation, an app chat session or the `memory_id` run\nparameter). Leave unset to use the run's memory id. A fixed value shares one memory\nacross every run; an expression such as `flow_input.customer_id` keeps one memory per\nkey. When it evaluates to an empty value the agent runs without memory. Read only\nwhile `memory` is `window` or `compaction`: it is ignored when memory is off, and an\nolder `auto` or `manual` memory reads neither history input.\n"},"previous_messages":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Array of MemoryMessage. History supplied by the flow, sent between the system prompt\nand the user message. Read only while `memory` is off or absent: managed memory\nignores it, and an older `auto` or `manual` memory reads neither history input.\n"},"output_schema":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"JSON Schema object defining structured output format. Used when you need the AI to return data in a specific shape.\nSupports standard JSON Schema properties: type, properties, required, items, enum, pattern, minLength, maxLength, minimum, maximum, etc.\nExample: { type: 'object', properties: { name: { type: 'string' }, age: { type: 'integer' } }, required: ['name'] }\n"},"user_attachments":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Array of file references (images or PDFs) for the AI agent.\nFormat: Array<{ bucket: string, key: string }> - S3 object references\nExample: [{ bucket: 'my-bucket', key: 'documents/report.pdf' }]\n"},"enabled_tools":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Array of strings naming which of the tools configured in `tools` the agent may call\nthis run. Leaving it unset carries every one of them; an empty array carries none.\nA tool is named as the model is shown it. An entry the model is shown nothing of is\nnamed by what identifies it instead: an MCP server by its resource path, carrying\nevery tool it exposes (which of them stays that entry's include_tools/exclude_tools),\nand a websearch entry by the reserved name '__wm_web_search', whatever summary it carries\n(no tool may take that name).\nExample: ['get_user', 'u/admin/github_mcp', '__wm_web_search']\n"},"max_completion_tokens":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Integer. Maximum number of tokens the AI will generate in its response.\nRange: 1 to 4,294,967,295. Typical values: 256-4096 for most use cases.\n"},"temperature":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Float. Controls randomness/creativity of responses.\nRange: 0.0 to 2.0 (provider-dependent)\n- 0.0 = deterministic, focused responses\n- 0.7 = balanced (common default)\n- 1.0+ = more creative/random\n"},"max_iterations":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Number. Limits how many times the agent can loop through reasoning and tool use.\nRange: 1-1000.\n"}}},"tools":{"type":"array","description":"Array of tools the agent can use. The agent decides which tools to call based on the task","items":{"$ref":"#/components/schemas/AgentTool"}},"type":{"type":"string","enum":["aiagent"]},"tag":{"type":"string","description":"Worker group tag for execution routing. If not set, the AI agent step runs on the flow's tag (default `flow`)"},"omit_output_from_conversation":{"type":"boolean","default":false,"description":"If true, this AI agent step does not persist its assistant or tool messages to the flow conversation when chat mode is enabled."},"agent":{"type":"string","description":"Path of a reusable `ai_agent` resource (hybrid linking). When set, the agent brain\nconfig (provider/model/system prompt/etc.) and tool set are resolved at runtime from\nthat resource; the module's input_transforms then only carry the flow-local inputs\n(user_message, user_attachments, enabled_tools and the history inputs memory_id and previous_messages).\n"},"tool_inputs":{"type":"object","description":"Host-local wiring for an agent's tool inputs, keyed by tool id then input key. Binds the\nreferenced agent's tools to this flow's context (flow_input/results) without mutating the\nshared resource; overlaid onto the tools' input_transforms at runtime \u2014 including when\n`agent` is unset, since a step forked for editing keeps these overrides until it is saved\nback or unlinked.\n","additionalProperties":{"type":"object","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}}},"parallel":{"type":"boolean","description":"If true, the agent can execute multiple tool calls in parallel"}},"required":["type","input_transforms"]},"AiDecision":{"type":"object","description":"AI decision step: one call to a decision model (TypeSafe's Jev, Cloudflare's\nJev-compatible Clef, or OpenAI's Decisions API) that answers typed questions about a\nstate with calibrated probabilities, instead of generating text.\nPrefer it over an AI agent to classify, route, score or check something: it is fast,\ncheap and its answers are structured. Its result is { output: { : answer },\nmodel, usage }, so a later step reads e.g. results..output.intent.choice. To route on\nthe answers, follow it with a branchone whose branch exprs read\nresults..output..choice. Usable as an AI agent tool, where the calling agent\nsupplies the state.\n","properties":{"input_transforms":{"type":"object","description":"Input parameters for the decision mapped to their values","properties":{"provider":{"$ref":"#/components/schemas/ProviderTransform"},"state":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"What the questions are asked about: a string, an object or an array of strings.\nAn object with descriptive keys holding only what the questions need works best.\nExample: { message: flow_input.message, plan: results.a.plan }\n"},"questions":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Object mapping each question name to { type, instructions, criteria }, where type is:\n- 'choice': criteria maps each option to its description (up to 255); the answer\n has choice, probabilities and confidence\n- 'score': criteria is an ordered array of 2 to 10 level descriptions; the answer\n has score, legend, probabilities and confidence\n- 'noul': yes/no, criteria optionally { true, false } descriptions; the answer has\n noul, the probability of yes (0 to 1)\nExample: { intent: { type: 'choice', instructions: 'What does the customer want?',\ncriteria: { refund: 'Money back', bug: 'Something is broken' } } }\n"}},"required":["provider","state","questions"]},"type":{"type":"string","enum":["aidecision"]},"tag":{"type":"string","description":"Worker group tag for execution routing. If not set, the step runs on the flow's tag (default `flow`)"}},"required":["type","input_transforms"]},"Identity":{"type":"object","description":"Pass-through module that returns its input unchanged. Useful for flow structure or as a placeholder","properties":{"type":{"type":"string","enum":["identity"]},"flow":{"type":"boolean","description":"If true, marks this as a flow identity (special handling)"}},"required":["type"]},"FlowStatus":{"type":"object","properties":{"step":{"type":"integer"},"modules":{"type":"array","items":{"$ref":"#/components/schemas/FlowStatusModule"}},"user_states":{"additionalProperties":true},"preprocessor_module":{"allOf":[{"$ref":"#/components/schemas/FlowStatusModule"}]},"failure_module":{"allOf":[{"$ref":"#/components/schemas/FlowStatusModule"},{"type":"object","properties":{"parent_module":{"type":"string"}}}]},"retry":{"type":"object","properties":{"fail_count":{"type":"integer"},"failed_jobs":{"type":"array","items":{"type":"string","format":"uuid"}}}}},"required":["step","modules","failure_module"]},"FlowStatusModule":{"type":"object","properties":{"type":{"type":"string","enum":["WaitingForPriorSteps","WaitingForEvents","WaitingForExecutor","InProgress","Success","Failure"]},"id":{"type":"string"},"job":{"type":"string","format":"uuid"},"count":{"type":"integer"},"progress":{"type":"integer"},"iterator":{"type":"object","properties":{"index":{"type":"integer"},"itered":{"type":"array","items":{}},"itered_len":{"type":"integer"},"args":{}}},"flow_jobs":{"type":"array","items":{"type":"string"}},"flow_jobs_success":{"type":"array","items":{"type":"boolean"}},"flow_jobs_duration":{"type":"object","properties":{"started_at":{"type":"array","items":{"type":"string"}},"duration_ms":{"type":"array","items":{"type":"integer"}}}},"branch_chosen":{"type":"object","properties":{"type":{"type":"string","enum":["branch","default"]},"branch":{"type":"integer"}},"required":["type"]},"branchall":{"type":"object","properties":{"branch":{"type":"integer"},"len":{"type":"integer"}},"required":["branch","len"]},"approvers":{"type":"array","items":{"type":"object","properties":{"resume_id":{"type":"integer"},"approver":{"type":"string"}},"required":["resume_id","approver"]}},"failed_retries":{"type":"array","items":{"type":"string","format":"uuid"}},"skipped":{"type":"boolean"},"agent_actions":{"type":"array","items":{"type":"object","oneOf":[{"type":"object","properties":{"job_id":{"type":"string","format":"uuid"},"function_name":{"type":"string"},"type":{"type":"string","enum":["tool_call"]},"module_id":{"type":"string"}},"required":["job_id","function_name","type","module_id"]},{"type":"object","properties":{"call_id":{"type":"string","format":"uuid"},"function_name":{"type":"string"},"resource_path":{"type":"string"},"type":{"type":"string","enum":["mcp_tool_call"]},"arguments":{"type":"object"}},"required":["call_id","function_name","resource_path","type"]},{"type":"object","properties":{"type":{"type":"string","enum":["web_search"]}},"required":["type"]},{"type":"object","properties":{"type":{"type":"string","enum":["message"]}},"required":["content","type"]}]}},"agent_actions_success":{"type":"array","items":{"type":"boolean"}}},"required":["type"]}} \ No newline at end of file +{"OpenFlow":{"type":"object","description":"Top-level flow definition containing metadata, configuration, and the flow structure","properties":{"summary":{"type":"string","description":"Short description of what this flow does"},"description":{"type":"string","description":"Detailed documentation for this flow"},"value":{"$ref":"#/components/schemas/FlowValue"},"schema":{"type":"object","description":"JSON Schema for flow inputs. Use this to define input parameters, their types, defaults, and validation. For resource inputs, set type to 'object' and format to 'resource-' (e.g., 'resource-stripe')"},"on_behalf_of_email":{"type":"string","description":"Address of the account the flow runs on behalf of. Derived from on_behalf_of on read; accepted on write, where it is resolved to the account it names."},"on_behalf_of":{"type":"string","description":"The flow runs with the permissions of this identity: u/{username}, g/{group}, or a bare email when the username is itself email-shaped. The only stored half of the identity; on_behalf_of_email is derived from it. Omit it when writing and it is resolved from that address instead."}},"required":["summary","value"]},"FlowValue":{"type":"object","description":"The flow structure containing modules and optional preprocessor/failure handlers","properties":{"modules":{"type":"array","description":"Array of steps that execute in sequence. Each step can be a script, subflow, loop, or branch","items":{"$ref":"#/components/schemas/FlowModule"}},"failure_module":{"description":"Special module that executes when the flow fails. Receives error object with message, name, stack, and step_id. Must have id 'failure'. Only supports script/rawscript types","$ref":"#/components/schemas/FlowModule"},"preprocessor_module":{"description":"Special module that runs before the first step on external triggers. Must have id 'preprocessor'. Only supports script/rawscript types. Cannot reference other step results","$ref":"#/components/schemas/FlowModule"},"same_worker":{"type":"boolean","description":"If true, all steps run on the same worker for better performance"},"preserve_step_tags":{"type":"boolean","description":"If true and the flow runs on a custom worker tag, steps that declare their own non-empty tag run on it instead of inheriting the flow tag. Steps without their own tag still inherit the flow tag."},"concurrent_limit":{"type":"number","description":"Maximum number of concurrent executions of this flow"},"concurrency_key":{"type":"string","description":"Expression to group concurrent executions (e.g., by user ID)"},"concurrency_time_window_s":{"type":"number","description":"Time window in seconds for concurrent_limit"},"debounce_delay_s":{"type":"integer","description":"Delay in seconds to debounce flow executions"},"debounce_key":{"type":"string","description":"Expression to group debounced executions"},"debounce_args_to_accumulate":{"type":"array","description":"Arguments to accumulate across debounced executions","items":{"type":"string"}},"max_total_debouncing_time":{"type":"integer","description":"Maximum total time in seconds that a job can be debounced"},"max_total_debounces_amount":{"type":"integer","description":"Maximum number of times a job can be debounced"},"skip_expr":{"type":"string","description":"JavaScript expression to conditionally skip the entire flow"},"cache_ttl":{"type":"number","description":"Cache duration in seconds for flow results"},"cache_ignore_s3_path":{"type":"boolean"},"delete_after_secs":{"type":"integer","description":"If set, delete the flow job's args, result and logs after this many seconds following job completion"},"flow_env":{"type":"object","description":"Environment variables available to all steps. Values can be strings, JSON values, or special references: '$var:path' (workspace variable) or '$res:path' (resource).","additionalProperties":{}},"priority":{"type":"number","description":"Execution priority (higher numbers run first)"},"early_return":{"type":"string","description":"Id of the step whose result a sync webhook returns as soon as that step completes, while the rest of the flow keeps running. When the step does not run, or fails while the flow has a failure module, the flow's final result is returned instead."},"chat_input_enabled":{"type":"boolean","description":"Whether this flow accepts chat-style input"},"notes":{"type":"array","description":"Sticky notes attached to the flow","items":{"$ref":"#/components/schemas/FlowNote"}},"groups":{"type":"array","description":"Semantic groups of modules for organizational purposes","items":{"$ref":"#/components/schemas/FlowGroup"}}},"required":["modules"]},"Retry":{"type":"object","description":"Retry configuration for failed module executions","properties":{"constant":{"type":"object","description":"Retry with constant delay between attempts","properties":{"attempts":{"type":"integer","description":"Number of retry attempts"},"seconds":{"type":"integer","description":"Seconds to wait between retries"}}},"exponential":{"type":"object","description":"Retry with exponential backoff: the n-th retry waits multiplier \u00d7 seconds^n","properties":{"attempts":{"type":"integer","description":"Number of retry attempts"},"multiplier":{"type":"integer","description":"Multiplier for exponential backoff"},"seconds":{"type":"integer","minimum":1,"description":"Base of the exponential (seconds); the n-th retry waits multiplier \u00d7 seconds^n, where n counts constant retries too"},"random_factor":{"type":"integer","minimum":0,"maximum":100,"description":"Random jitter percentage (0-100) to avoid thundering herd"}}},"retry_if":{"$ref":"#/components/schemas/RetryIf"}}},"FlowNote":{"type":"object","description":"A sticky note attached to a flow for documentation and annotation","properties":{"id":{"type":"string","description":"Unique identifier for the note"},"text":{"type":"string","description":"Content of the note"},"position":{"type":"object","description":"Position of the note in the flow editor","properties":{"x":{"type":"number","description":"X coordinate"},"y":{"type":"number","description":"Y coordinate"}},"required":["x","y"]},"size":{"type":"object","description":"Size of the note in the flow editor","properties":{"width":{"type":"number","description":"Width in pixels"},"height":{"type":"number","description":"Height in pixels"}},"required":["width","height"]},"color":{"type":"string","description":"Color of the note, one of: yellow, blue, green, purple, pink, orange, red, cyan, lime, gray. Any other value renders unstyled."},"type":{"type":"string","enum":["free","group"],"description":"Type of note - 'free' for standalone notes. 'group' notes are deprecated; segment a flow with FlowValue.groups instead."},"locked":{"type":"boolean","default":false,"description":"Whether the note is locked and cannot be edited or moved"},"contained_node_ids":{"type":"array","items":{"type":"string"},"description":"For group notes, the IDs of nodes contained within this group"}},"required":["id","text","color","type"]},"FlowGroup":{"type":"object","description":"A semantic group of flow modules for organizational purposes. Does not affect execution \u2014 modules remain in their original position in the flow. Groups provide naming and collapsibility in the editor. Members are computed dynamically from all nodes on paths between start_id and end_id.","properties":{"summary":{"type":"string","description":"Display name for this group"},"note":{"type":"string","description":"Markdown note shown below the group header"},"autocollapse":{"type":"boolean","default":false,"description":"If true, this group is collapsed by default in the flow editor. UI hint only."},"start_id":{"type":"string","description":"ID of the first flow module in this group (topological entry point)"},"end_id":{"type":"string","description":"ID of the last flow module in this group (topological exit point)"},"color":{"type":"string","description":"Color for the group in the flow editor, one of: yellow, blue, green, purple, pink, orange, red, cyan, lime, gray. Omit it to let the editor pick one."}},"required":["start_id","end_id"]},"RetryIf":{"type":"object","description":"Conditional retry based on error or result","properties":{"expr":{"type":"string","description":"JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables"}},"required":["expr"]},"StopAfterIf":{"type":"object","description":"Early termination condition for a module","properties":{"skip_if_stopped":{"type":"boolean","description":"If true, following steps are skipped when this condition triggers"},"expr":{"type":"string","description":"JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"},"error_message":{"type":"string","nullable":true,"description":"Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised."},"error_include_result":{"type":"boolean","description":"When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false."}},"required":["expr"]},"FlowModule":{"type":"object","description":"A single step in a flow. Can be a script, subflow, loop, or branch","properties":{"id":{"type":"string","description":"Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"},"value":{"$ref":"#/components/schemas/FlowModuleValue"},"stop_after_if":{"description":"Early termination condition evaluated after this step completes","$ref":"#/components/schemas/StopAfterIf"},"stop_after_all_iters_if":{"description":"For loops only - early termination condition evaluated after all iterations complete","$ref":"#/components/schemas/StopAfterIf"},"skip_if":{"type":"object","description":"Conditionally skip this step based on previous results or flow inputs","properties":{"expr":{"type":"string","description":"JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.'"}},"required":["expr"]},"sleep":{"description":"Delay before executing this step (in seconds or as expression)","$ref":"#/components/schemas/InputTransform"},"cache_ttl":{"type":"number","description":"Cache duration in seconds for this step's results"},"cache_ignore_s3_path":{"type":"boolean"},"timeout":{"description":"Maximum execution time in seconds (static value or expression)","$ref":"#/components/schemas/InputTransform"},"delete_after_secs":{"type":"integer","description":"If set, delete the step's args, result and logs after this many seconds following job completion"},"summary":{"type":"string","description":"Short description of what this step does"},"mock":{"type":"object","description":"Mock configuration for testing without executing the actual step","properties":{"enabled":{"type":"boolean","description":"If true, return mock value instead of executing"},"return_value":{"description":"Value to return when mocked"}}},"suspend":{"type":"object","description":"Configuration for approval/resume steps that wait for user input","properties":{"required_events":{"type":"integer","description":"Number of approvals required before continuing"},"timeout":{"type":"integer","description":"Timeout in seconds before auto-continuing or canceling"},"resume_form":{"type":"object","description":"Form schema for collecting input when resuming","properties":{"schema":{"type":"object","description":"JSON Schema for the resume form"}}},"user_auth_required":{"type":"boolean","description":"If true, only authenticated users can approve"},"user_groups_required":{"description":"Expression or list of groups that can approve","$ref":"#/components/schemas/InputTransform"},"self_approval_disabled":{"type":"boolean","description":"If true, the user who started the flow cannot approve"},"hide_cancel":{"type":"boolean","description":"If true, hide the cancel button on the approval form"},"continue_on_disapprove_timeout":{"type":"boolean","description":"If true, continue flow on timeout instead of canceling"},"skin":{"type":"string","enum":["detailed","minimal"],"description":"How the approval request is presented, on the approval page and in Slack/Teams approval messages. 'detailed' (used when unset) shows the flow details (arguments, graph, approvers); 'minimal' shows only the request: the step description, form and approve/reject actions"}}},"priority":{"type":"number","description":"Execution priority for this step (higher numbers run first)"},"continue_on_error":{"type":"boolean","description":"If true, flow continues even if this step fails"},"job_token_scopes":{"type":"array","nullable":true,"items":{"type":"string"},"description":"Scopes the token of this step's jobs is restricted to (domain:action[:resource], e.g. oidc:write), on top of the flow's own restriction: a step can only narrow it. Applies to everything the step runs (loop and branch bodies, AI agent tools)."},"retry":{"description":"Retry configuration if this step fails","$ref":"#/components/schemas/Retry"},"debouncing":{"description":"Debounce configuration for this step (EE only)","type":"object","properties":{"debounce_delay_s":{"type":"integer","description":"Delay in seconds to debounce this step's executions across flow runs"},"debounce_key":{"type":"string","description":"Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/-"},"debounce_args_to_accumulate":{"type":"array","description":"Array-type arguments to accumulate across debounced executions","items":{"type":"string"}},"max_total_debouncing_time":{"type":"integer","description":"Maximum total time in seconds before forced execution"},"max_total_debounces_amount":{"type":"integer","description":"Maximum number of debounces before forced execution"}}}},"required":["value","id"]},"InputTransform":{"description":"Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs","oneOf":[{"$ref":"#/components/schemas/StaticTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type","mapping":{"static":"#/components/schemas/StaticTransform","javascript":"#/components/schemas/JavascriptTransform","ai":"#/components/schemas/AiTransform"}}},"StaticTransform":{"type":"object","description":"Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'","properties":{"value":{"description":"The static value. For resources, use format '$res:path/to/resource'"},"type":{"type":"string","enum":["static"]}},"required":["type"]},"JavascriptTransform":{"type":"object","description":"JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')","properties":{"expr":{"type":"string","description":"JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"},"type":{"type":"string","enum":["javascript"]}},"required":["expr","type"]},"AiTransform":{"type":"object","description":"Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.","properties":{"type":{"type":"string","enum":["ai"]}},"required":["type"]},"AIProviderKind":{"type":"string","description":"Supported AI provider types","enum":["openai","azure_openai","azure_foundry","anthropic","mistral","deepseek","googleai","groq","openrouter","togetherai","customai","aws_bedrock","typesafe","cloudflare"]},"ProviderConfig":{"type":"object","description":"Complete AI provider configuration with resource reference and model selection","properties":{"kind":{"$ref":"#/components/schemas/AIProviderKind"},"resource":{"type":"string","description":"Resource reference in format '$res:{resource_path}' pointing to provider credentials"},"model":{"type":"string","description":"Model identifier (e.g., 'gpt-4', 'claude-3-opus-20240229', 'gemini-pro')"},"reasoning_effort":{"type":"string","description":"Provider-native reasoning effort token (e.g. 'low', 'high', 'none') for models that support extended thinking. Optional; unset leaves the provider default."}},"required":["kind","resource","model"]},"StaticProviderTransform":{"type":"object","description":"Static provider configuration passed directly to the AI agent","properties":{"value":{"$ref":"#/components/schemas/ProviderConfig"},"type":{"type":"string","enum":["static"]}},"required":["type","value"]},"ProviderTransform":{"description":"Provider configuration - can be static (ProviderConfig), JavaScript expression, or AI-determined","oneOf":[{"$ref":"#/components/schemas/StaticProviderTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type","mapping":{"static":"#/components/schemas/StaticProviderTransform","javascript":"#/components/schemas/JavascriptTransform","ai":"#/components/schemas/AiTransform"}}},"MemoryOff":{"type":"object","description":"No conversation memory/context","properties":{"kind":{"type":"string","enum":["off"]}},"required":["kind"]},"MemoryWindow":{"type":"object","description":"Keeps the most recent messages of the memory named by the run's memory id (or the step's\n`memory_id`). Without a memory id the agent runs without memory.\n","properties":{"kind":{"type":"string","enum":["window"]},"context_length":{"type":"integer","description":"Number of most recent messages to load and store. 0 turns memory off."}},"required":["kind","context_length"]},"MemoryAuto":{"type":"object","deprecated":true,"description":"Deprecated, still read as it was written: the run's memory id, else the `memory_id` here.\nThe step's own `memory_id` is not read while this kind is set; switch the kind to `window`\nto use it. Without a `context_length`, or with 0, it is `off` and reads `previous_messages`.\n","properties":{"kind":{"type":"string","enum":["auto"]},"context_length":{"type":"integer","description":"Maximum number of messages to retain in context"},"memory_id":{"type":"string","description":"Identifier for persistent memory across agent invocations"}},"required":["kind"]},"MemoryCompaction":{"type":"object","description":"Keeps the whole memory named by the run's memory id (or the step's `memory_id`), replacing\nits older part with a summary as the conversation approaches the model's context window.\nWithout a memory id the agent runs without memory, and compaction bounds the run's own loop.\n","properties":{"kind":{"type":"string","enum":["compaction"]},"context_window":{"type":"integer","description":"Overrides the context window looked up from the model, in tokens. Only a model\nWindmill does not know needs one; those fall back to 128000.\n"}},"required":["kind"]},"MemoryMessage":{"type":"object","description":"A single message in conversation history","properties":{"role":{"type":"string","enum":["user","assistant","system"]},"content":{"type":"string"}},"required":["role","content"]},"MemoryManual":{"type":"object","deprecated":true,"description":"Deprecated, still read as it was written. Move the step to `off` with `previous_messages` instead.","properties":{"kind":{"type":"string","enum":["manual"]},"messages":{"type":"array","items":{"$ref":"#/components/schemas/MemoryMessage"}}},"required":["kind","messages"]},"MemoryConfig":{"description":"Managed memory, stored by Windmill and replayed with each request. The memory is named by a memory id, see `memory_id`. While it is off, a step can supply its history in `previous_messages`.","oneOf":[{"$ref":"#/components/schemas/MemoryOff"},{"$ref":"#/components/schemas/MemoryWindow"},{"$ref":"#/components/schemas/MemoryCompaction"},{"$ref":"#/components/schemas/MemoryAuto"},{"$ref":"#/components/schemas/MemoryManual"}],"discriminator":{"propertyName":"kind","mapping":{"off":"#/components/schemas/MemoryOff","window":"#/components/schemas/MemoryWindow","compaction":"#/components/schemas/MemoryCompaction","auto":"#/components/schemas/MemoryAuto","manual":"#/components/schemas/MemoryManual"}}},"StaticMemoryTransform":{"type":"object","description":"Static memory configuration passed directly to the AI agent","properties":{"value":{"$ref":"#/components/schemas/MemoryConfig"},"type":{"type":"string","enum":["static"]}},"required":["type","value"]},"MemoryTransform":{"description":"Memory configuration - can be static (MemoryConfig), JavaScript expression, or AI-determined","oneOf":[{"$ref":"#/components/schemas/StaticMemoryTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type","mapping":{"static":"#/components/schemas/StaticMemoryTransform","javascript":"#/components/schemas/JavascriptTransform","ai":"#/components/schemas/AiTransform"}}},"FlowModuleValue":{"description":"The actual implementation of a flow step. Can be a script (inline or referenced), subflow, loop, branch, or special module type","oneOf":[{"$ref":"#/components/schemas/RawScript"},{"$ref":"#/components/schemas/PathScript"},{"$ref":"#/components/schemas/PathFlow"},{"$ref":"#/components/schemas/ForloopFlow"},{"$ref":"#/components/schemas/WhileloopFlow"},{"$ref":"#/components/schemas/BranchOne"},{"$ref":"#/components/schemas/BranchAll"},{"$ref":"#/components/schemas/Identity"},{"$ref":"#/components/schemas/AiAgent"},{"$ref":"#/components/schemas/AiDecision"}],"discriminator":{"propertyName":"type","mapping":{"rawscript":"#/components/schemas/RawScript","script":"#/components/schemas/PathScript","flow":"#/components/schemas/PathFlow","forloopflow":"#/components/schemas/ForloopFlow","whileloopflow":"#/components/schemas/WhileloopFlow","branchone":"#/components/schemas/BranchOne","branchall":"#/components/schemas/BranchAll","identity":"#/components/schemas/Identity","aiagent":"#/components/schemas/AiAgent","aidecision":"#/components/schemas/AiDecision"}}},"RawScript":{"type":"object","description":"Inline script with code defined directly in the flow. Use 'bun' as default language if unspecified. The script receives arguments from input_transforms","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"content":{"type":"string","description":"The script source code. Should export a 'main' function"},"language":{"type":"string","description":"Programming language for this script","enum":["deno","bun","bunnative","python3","go","bash","powershell","postgresql","mysql","bigquery","snowflake","mssql","oracledb","graphql","nativets","php","rust","ansible","csharp","nu","java","ruby","rlang","duckdb"]},"path":{"type":"string","description":"Optional path for saving this script"},"lock":{"type":"string","description":"Lock file content for dependencies"},"type":{"type":"string","enum":["rawscript"]},"tag":{"type":"string","description":"Worker group tag for execution routing"},"concurrent_limit":{"type":"number","description":"Maximum concurrent executions of this script"},"concurrency_time_window_s":{"type":"number","description":"Time window for concurrent_limit"},"custom_concurrency_key":{"type":"string","description":"Custom key for grouping concurrent executions"},"is_trigger":{"type":"boolean","description":"If true, this script is a trigger that can start the flow"},"assets":{"type":"array","description":"External resources this script accesses (S3 objects, resources, etc.)","items":{"type":"object","required":["path","kind"],"properties":{"path":{"type":"string","description":"Path to the asset"},"kind":{"type":"string","description":"Type of asset","enum":["s3object","resource","ducklake","datatable","volume","dbt"]},"access_type":{"type":"string","nullable":true,"description":"Access level for this asset","enum":["r","w","rw"]},"alt_access_type":{"type":"string","nullable":true,"description":"Alternative access level","enum":["r","w","rw"]}}}}},"required":["type","content","language","input_transforms"]},"PathScript":{"type":"object","description":"Reference to an existing script by path. Use this when calling a previously saved script instead of writing inline code","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"path":{"type":"string","description":"Path to the script in the workspace (e.g., 'f/scripts/send_email')"},"hash":{"type":"string","description":"Optional specific version hash of the script to use"},"type":{"type":"string","enum":["script"]},"tag_override":{"type":"string","description":"Override the script's default worker group tag"},"is_trigger":{"type":"boolean","description":"If true, this script is a trigger that can start the flow"}},"required":["type","path","input_transforms"]},"PathFlow":{"type":"object","description":"Reference to an existing flow by path. Use this to call another flow as a subflow","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the subflow's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"path":{"type":"string","description":"Path to the flow in the workspace (e.g., 'f/flows/process_user')"},"type":{"type":"string","enum":["flow"]}},"required":["type","path","input_transforms"]},"ForloopFlow":{"type":"object","description":"Executes nested modules in a loop over an iterator. Inside the loop, use 'flow_input.iter.value' to access the current iteration value, and 'flow_input.iter.index' for the index. Supports parallel execution for better performance on I/O-bound operations","properties":{"modules":{"type":"array","description":"Steps to execute for each iteration. These can reference the iteration value via 'flow_input.iter.value'","items":{"$ref":"#/components/schemas/FlowModule"}},"iterator":{"description":"JavaScript expression that returns an array to iterate over. Can reference 'results.step_id' or 'flow_input'","$ref":"#/components/schemas/InputTransform"},"skip_failures":{"type":"boolean","description":"If true, iteration failures don't stop the loop. Failed iterations return null"},"type":{"type":"string","enum":["forloopflow"]},"parallel":{"type":"boolean","description":"If true, iterations run concurrently (faster for I/O-bound operations). Use with parallelism to control concurrency"},"parallelism":{"description":"Maximum number of concurrent iterations when parallel=true. Limits resource usage. Can be static number or expression","$ref":"#/components/schemas/InputTransform"},"squash":{"type":"boolean"}},"required":["modules","iterator","skip_failures","type"]},"WhileloopFlow":{"type":"object","description":"Executes nested modules repeatedly until stopped. The implicit iterator is the iteration counter, so 'flow_input.iter.value' equals 'flow_input.iter.index' (0, 1, 2, ...) and never carries state. To carry state across iterations, a step reads its own previous-iteration result via 'results.' with a first-iteration fallback - the loop's stop_after_if must then be on that inner step (a plain single-step body with stop_after_if on the loop module does not resolve 'results' across iterations and never terminates); plain counters can instead be derived from 'flow_input.iter.index', which works in every configuration. stop_after_if is evaluated after each iteration - on the loop module 'result' is the last iteration's result","properties":{"modules":{"type":"array","description":"Steps to execute in each iteration","items":{"$ref":"#/components/schemas/FlowModule"}},"skip_failures":{"type":"boolean","description":"If true, iteration failures don't stop the loop. Failed iterations return null"},"type":{"type":"string","enum":["whileloopflow"]},"parallel":{"type":"boolean","description":"If true, iterations run concurrently (use with caution in while loops)"},"parallelism":{"description":"Maximum number of concurrent iterations when parallel=true","$ref":"#/components/schemas/InputTransform"},"squash":{"type":"boolean"}},"required":["modules","skip_failures","type"]},"BranchOne":{"type":"object","description":"Conditional branching where only the first matching branch executes. Branches are evaluated in order, and the first one with a true expression runs. If no branches match, the default branch executes","properties":{"branches":{"type":"array","description":"Array of branches to evaluate in order. The first branch with expr evaluating to true executes","items":{"type":"object","properties":{"summary":{"type":"string","description":"Short description of this branch condition"},"expr":{"type":"string","description":"JavaScript expression that returns boolean. Can use 'results.step_id' or 'flow_input'. First true expr wins"},"modules":{"type":"array","description":"Steps to execute if this branch's expr is true","items":{"$ref":"#/components/schemas/FlowModule"}}},"required":["modules","expr"]}},"default":{"type":"array","description":"Steps to execute if no branch expressions match","items":{"$ref":"#/components/schemas/FlowModule"}},"type":{"type":"string","enum":["branchone"]}},"required":["branches","default","type"]},"BranchAll":{"type":"object","description":"Parallel branching where all branches execute simultaneously. Unlike BranchOne, all branches run regardless of conditions. Useful for executing independent tasks concurrently","properties":{"branches":{"type":"array","description":"Array of branches that all execute (either in parallel or sequentially)","items":{"type":"object","properties":{"summary":{"type":"string","description":"Short description of this branch's purpose"},"skip_failure":{"type":"boolean","description":"If true, failure in this branch doesn't fail the entire flow"},"modules":{"type":"array","description":"Steps to execute in this branch","items":{"$ref":"#/components/schemas/FlowModule"}}},"required":["modules"]}},"type":{"type":"string","enum":["branchall"]},"parallel":{"type":"boolean","description":"If true, all branches execute concurrently. If false, they execute sequentially"}},"required":["branches","type"]},"AgentTool":{"type":"object","description":"A tool available to an AI agent. Can be a flow module or an external MCP (Model Context Protocol) tool","properties":{"id":{"type":"string","description":"Unique identifier for this tool. Cannot contain spaces - use underscores instead (e.g., 'get_user_data' not 'get user data')"},"summary":{"type":"string","description":"The name the AI agent calls this tool by, not a human label. On a flowmodule tool it must match ^[a-zA-Z0-9_]+$ - letters, numbers and underscores only (e.g. 'search_documentation', not 'Search documentation') - and always be set; on an mcp or websearch tool it is a plain label. Put the human-readable explanation in 'description'."},"description":{"type":"string","description":"Free-text description of the tool given to the AI to decide when and how to call it. Overrides the description auto-derived from the underlying script."},"job_token_scopes":{"type":"array","nullable":true,"items":{"type":"string"},"description":"Scopes the token of this tool's jobs is restricted to, on top of the agent step's own restriction: a tool can only narrow it."},"value":{"$ref":"#/components/schemas/ToolValue"}},"required":["id","value"]},"ToolValue":{"description":"The implementation of a tool. Can be a flow module (script/flow) or an MCP tool reference","oneOf":[{"$ref":"#/components/schemas/FlowModuleTool"},{"$ref":"#/components/schemas/McpToolValue"},{"$ref":"#/components/schemas/WebsearchToolValue"}],"discriminator":{"propertyName":"tool_type","mapping":{"flowmodule":"#/components/schemas/FlowModuleTool","mcp":"#/components/schemas/McpToolValue","websearch":"#/components/schemas/WebsearchToolValue"}}},"FlowModuleTool":{"description":"A tool implemented as a flow module (script, flow, etc.). The AI can call this like any other flow module","allOf":[{"type":"object","properties":{"tool_type":{"type":"string","enum":["flowmodule"]}},"required":["tool_type"]},{"$ref":"#/components/schemas/FlowModuleValue"}]},"WebsearchToolValue":{"type":"object","description":"A tool implemented as a websearch tool. The AI can call this like any other websearch tool","properties":{"tool_type":{"type":"string","enum":["websearch"]}},"required":["tool_type"]},"McpToolValue":{"type":"object","description":"Reference to an external MCP (Model Context Protocol) tool. The AI can call tools from MCP servers","properties":{"tool_type":{"type":"string","enum":["mcp"]},"resource_path":{"type":"string","description":"Path to the MCP resource/server configuration"},"include_tools":{"type":"array","description":"Whitelist of specific tools to include from this MCP server","items":{"type":"string"}},"exclude_tools":{"type":"array","description":"Blacklist of tools to exclude from this MCP server","items":{"type":"string"}}},"required":["tool_type","resource_path"]},"AiAgent":{"type":"object","description":"AI agent step that can use tools to accomplish tasks. The agent receives inputs and can call any of its configured tools to complete the task","properties":{"input_transforms":{"type":"object","description":"Input parameters for the AI agent mapped to their values","properties":{"provider":{"$ref":"#/components/schemas/ProviderTransform"},"output_type":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Output format type.\nValid values: 'text' (default) - plain text response, 'image' - image generation\n"},"user_message":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"The user's prompt/message to the AI agent. Supports variable interpolation with\nflow.input syntax. Required unless memory is off and `previous_messages` supplies\nthe prompt; image output always needs it.\n"},"system_prompt":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"System instructions that guide the AI's behavior, persona, and response style. Optional."},"streaming":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Boolean. If true, stream the AI response incrementally.\nStreaming events include: token_delta, reasoning_token_delta, tool_call, tool_call_arguments, tool_execution, tool_result\n"},"memory":{"$ref":"#/components/schemas/MemoryTransform"},"memory_id":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"String. Names the memory this step reads and writes, overriding the memory id the run\nwas started with (the chat conversation, an app chat session or the `memory_id` run\nparameter). Leave unset to use the run's memory id. A fixed value shares one memory\nacross every run; an expression such as `flow_input.customer_id` keeps one memory per\nkey. When it evaluates to an empty value the agent runs without memory. Read only\nwhile `memory` is `window` or `compaction`: it is ignored when memory is off, and an\nolder `auto` or `manual` memory reads neither history input.\n"},"previous_messages":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Array of MemoryMessage. History supplied by the flow, sent between the system prompt\nand the user message. Read only while `memory` is off or absent: managed memory\nignores it, and an older `auto` or `manual` memory reads neither history input.\n"},"output_schema":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"JSON Schema object defining structured output format. Used when you need the AI to return data in a specific shape.\nSupports standard JSON Schema properties: type, properties, required, items, enum, pattern, minLength, maxLength, minimum, maximum, etc.\nExample: { type: 'object', properties: { name: { type: 'string' }, age: { type: 'integer' } }, required: ['name'] }\n"},"user_attachments":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Array of file references (images or PDFs) for the AI agent.\nFormat: Array<{ bucket: string, key: string }> - S3 object references\nExample: [{ bucket: 'my-bucket', key: 'documents/report.pdf' }]\n"},"enabled_tools":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Array of strings naming which of the tools configured in `tools` the agent may call\nthis run. Leaving it unset carries every one of them; an empty array carries none.\nA tool is named as the model is shown it. An entry the model is shown nothing of is\nnamed by what identifies it instead: an MCP server by its resource path, carrying\nevery tool it exposes (which of them stays that entry's include_tools/exclude_tools),\nand a websearch entry by the reserved name '__wm_web_search', whatever summary it carries\n(no tool may take that name).\nExample: ['get_user', 'u/admin/github_mcp', '__wm_web_search']\n"},"max_completion_tokens":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Integer. Maximum number of tokens the AI will generate in its response.\nRange: 1 to 4,294,967,295. Typical values: 256-4096 for most use cases.\n"},"temperature":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Float. Controls randomness/creativity of responses.\nRange: 0.0 to 2.0 (provider-dependent)\n- 0.0 = deterministic, focused responses\n- 0.7 = balanced (common default)\n- 1.0+ = more creative/random\n"},"max_iterations":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Number. Limits how many times the agent can loop through reasoning and tool use.\nRange: 1-1000.\n"},"model":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"String. Only on a step linked to a saved agent (see `agent`): replaces the model\nsaved on the agent for this step's runs, on the agent's own provider resource. An\nempty value keeps the saved model. Set it to an expression such as\n`flow_input.model` to choose the model per run.\n"},"reasoning_effort":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"String. Only on a step linked to a saved agent (see `agent`): replaces the reasoning\neffort saved on the agent for this step's runs, as a provider-native token (e.g.\n'low', 'high', 'none'). An empty value sends no effort, so the model runs at its\ndefault. Leave the input out to keep the saved effort, which holds only while the\nstep runs the saved model. A step that is not linked sets both inside `provider`.\n"}}},"tools":{"type":"array","description":"Array of tools the agent can use. The agent decides which tools to call based on the task","items":{"$ref":"#/components/schemas/AgentTool"}},"type":{"type":"string","enum":["aiagent"]},"tag":{"type":"string","description":"Worker group tag for execution routing. If not set, the AI agent step runs on the flow's tag (default `flow`)"},"omit_output_from_conversation":{"type":"boolean","default":false,"description":"If true, this AI agent step does not persist its assistant or tool messages to the flow conversation when chat mode is enabled."},"agent":{"type":"string","description":"Path of a reusable `ai_agent` resource (hybrid linking). When set, the agent brain\nconfig (provider/model/system prompt/etc.) and tool set are resolved at runtime from\nthat resource; the module's input_transforms then only carry the flow-local inputs\n(user_message, user_attachments, enabled_tools and the history inputs memory_id and previous_messages)\nand, optionally, the `model` and `reasoning_effort` overrides of what the agent saved.\n"},"tool_inputs":{"type":"object","description":"Host-local wiring for an agent's tool inputs, keyed by tool id then input key. Binds the\nreferenced agent's tools to this flow's context (flow_input/results) without mutating the\nshared resource; overlaid onto the tools' input_transforms at runtime \u2014 including when\n`agent` is unset, since a step forked for editing keeps these overrides until it is saved\nback or unlinked.\n","additionalProperties":{"type":"object","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}}},"parallel":{"type":"boolean","description":"If true, the agent can execute multiple tool calls in parallel"}},"required":["type","input_transforms"]},"AiDecision":{"type":"object","description":"AI decision step: one call to a decision model (TypeSafe's Jev, Cloudflare's\nJev-compatible Clef, or OpenAI's Decisions API) that answers typed questions about a\nstate with calibrated probabilities, instead of generating text.\nPrefer it over an AI agent to classify, route, score or check something: it is fast,\ncheap and its answers are structured. Its result is { output: { : answer },\nmodel, usage }, so a later step reads e.g. results..output.intent.choice. To route on\nthe answers, follow it with a branchone whose branch exprs read\nresults..output..choice. Usable as an AI agent tool, where the calling agent\nsupplies the state.\n","properties":{"input_transforms":{"type":"object","description":"Input parameters for the decision mapped to their values","properties":{"provider":{"$ref":"#/components/schemas/ProviderTransform"},"state":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"What the questions are asked about: a string, an object or an array of strings.\nAn object with descriptive keys holding only what the questions need works best.\nExample: { message: flow_input.message, plan: results.a.plan }\n"},"questions":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Object mapping each question name to { type, instructions, criteria }, where type is:\n- 'choice': criteria maps each option to its description (up to 255); the answer\n has choice, probabilities and confidence\n- 'score': criteria is an ordered array of 2 to 10 level descriptions; the answer\n has score, legend, probabilities and confidence\n- 'noul': yes/no, criteria optionally { true, false } descriptions; the answer has\n noul, the probability of yes (0 to 1)\nExample: { intent: { type: 'choice', instructions: 'What does the customer want?',\ncriteria: { refund: 'Money back', bug: 'Something is broken' } } }\n"}},"required":["provider","state","questions"]},"type":{"type":"string","enum":["aidecision"]},"tag":{"type":"string","description":"Worker group tag for execution routing. If not set, the step runs on the flow's tag (default `flow`)"}},"required":["type","input_transforms"]},"Identity":{"type":"object","description":"Pass-through module that returns its input unchanged. Useful for flow structure or as a placeholder","properties":{"type":{"type":"string","enum":["identity"]},"flow":{"type":"boolean","description":"If true, marks this as a flow identity (special handling)"}},"required":["type"]},"FlowStatus":{"type":"object","properties":{"step":{"type":"integer"},"modules":{"type":"array","items":{"$ref":"#/components/schemas/FlowStatusModule"}},"user_states":{"additionalProperties":true},"preprocessor_module":{"allOf":[{"$ref":"#/components/schemas/FlowStatusModule"}]},"failure_module":{"allOf":[{"$ref":"#/components/schemas/FlowStatusModule"},{"type":"object","properties":{"parent_module":{"type":"string"}}}]},"retry":{"type":"object","properties":{"fail_count":{"type":"integer"},"failed_jobs":{"type":"array","items":{"type":"string","format":"uuid"}}}}},"required":["step","modules","failure_module"]},"FlowStatusModule":{"type":"object","properties":{"type":{"type":"string","enum":["WaitingForPriorSteps","WaitingForEvents","WaitingForExecutor","InProgress","Success","Failure"]},"id":{"type":"string"},"job":{"type":"string","format":"uuid"},"count":{"type":"integer"},"progress":{"type":"integer"},"iterator":{"type":"object","properties":{"index":{"type":"integer"},"itered":{"type":"array","items":{}},"itered_len":{"type":"integer"},"args":{}}},"flow_jobs":{"type":"array","items":{"type":"string"}},"flow_jobs_success":{"type":"array","items":{"type":"boolean"}},"flow_jobs_duration":{"type":"object","properties":{"started_at":{"type":"array","items":{"type":"string"}},"duration_ms":{"type":"array","items":{"type":"integer"}}}},"branch_chosen":{"type":"object","properties":{"type":{"type":"string","enum":["branch","default"]},"branch":{"type":"integer"}},"required":["type"]},"branchall":{"type":"object","properties":{"branch":{"type":"integer"},"len":{"type":"integer"}},"required":["branch","len"]},"approvers":{"type":"array","items":{"type":"object","properties":{"resume_id":{"type":"integer"},"approver":{"type":"string"}},"required":["resume_id","approver"]}},"failed_retries":{"type":"array","items":{"type":"string","format":"uuid"}},"skipped":{"type":"boolean"},"agent_actions":{"type":"array","items":{"type":"object","oneOf":[{"type":"object","properties":{"job_id":{"type":"string","format":"uuid"},"function_name":{"type":"string"},"type":{"type":"string","enum":["tool_call"]},"module_id":{"type":"string"}},"required":["job_id","function_name","type","module_id"]},{"type":"object","properties":{"call_id":{"type":"string","format":"uuid"},"function_name":{"type":"string"},"resource_path":{"type":"string"},"type":{"type":"string","enum":["mcp_tool_call"]},"arguments":{"type":"object"}},"required":["call_id","function_name","resource_path","type"]},{"type":"object","properties":{"type":{"type":"string","enum":["web_search"]}},"required":["type"]},{"type":"object","properties":{"type":{"type":"string","enum":["message"]}},"required":["content","type"]}]}},"agent_actions_success":{"type":"array","items":{"type":"boolean"}}},"required":["type"]}} \ No newline at end of file diff --git a/system_prompts/auto-generated/index.d.ts b/system_prompts/auto-generated/index.d.ts index d77f699a33..fee83d38b5 100644 --- a/system_prompts/auto-generated/index.d.ts +++ b/system_prompts/auto-generated/index.d.ts @@ -4,5 +4,7 @@ export declare function getFlowPrompt(): string; export declare function getResourcePrompt(): string; export declare function getRawAppPrompt(language?: string): string; export declare function getPipelinePrompt(): string; +export declare function getDatatablePrompt(): string; +export declare function getWorkspaceSettingsPrompt(): string; export declare function getDatatableSdkReference(language?: string): string; export declare function getWorkflowAsCodePrompt(language?: string): string; diff --git a/system_prompts/auto-generated/index.ts b/system_prompts/auto-generated/index.ts index ade95efe9e..da3b622046 100644 --- a/system_prompts/auto-generated/index.ts +++ b/system_prompts/auto-generated/index.ts @@ -73,6 +73,20 @@ export function getPipelinePrompt(): string { ].filter(Boolean).join('\n\n'); } +// Helper for data table schema changes, migrations and permissions (chat consumers) +export function getDatatablePrompt(): string { + return [ + prompts.DATATABLE_BASE + ].filter(Boolean).join('\n\n'); +} + +// Helper for the workspace settings document (chat consumers) +export function getWorkspaceSettingsPrompt(): string { + return [ + prompts.WORKSPACE_SETTINGS_BASE + ].filter(Boolean).join('\n\n'); +} + // Helper to get the datatable SQL SDK reference (wmill.datatable()). // Pass a language to get only that SDK; omit it to get both. export function getDatatableSdkReference(language?: string): string { diff --git a/system_prompts/auto-generated/prompts.d.ts b/system_prompts/auto-generated/prompts.d.ts index e74555504e..5cb7e336b3 100644 --- a/system_prompts/auto-generated/prompts.d.ts +++ b/system_prompts/auto-generated/prompts.d.ts @@ -5,6 +5,8 @@ export declare const FLOW_BASE: string; export declare const RESOURCES_BASE: string; export declare const RAW_APP_BASE: string; export declare const PIPELINE_BASE: string; +export declare const DATATABLE_BASE: string; +export declare const WORKSPACE_SETTINGS_BASE: string; export declare const WORKFLOW_AS_CODE_BASE: string; export declare const FLOW_CHAT_SPECIAL_MODULES: string; export declare const SDK_TYPESCRIPT: string; diff --git a/system_prompts/auto-generated/prompts.ts b/system_prompts/auto-generated/prompts.ts index 00e5655154..5b8c3cbe8c 100644 --- a/system_prompts/auto-generated/prompts.ts +++ b/system_prompts/auto-generated/prompts.ts @@ -5,6 +5,8 @@ export const SCRIPT_BASE = `# Windmill Script Writing Guide ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named \`c_\`, which keeps it apart from a hub type synced later: the parameter takes \`RT.C\` in TypeScript, a \`c_\` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (\`type Stripe = { token: string }\`), which is still the \`stripe\` resource type; in code you write, name it the way the language section shows (\`RT.Stripe\` in TypeScript) rather than copying the inline declaration - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it \`main\` (\`Main\` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no \`main\`: their language section shows how they take arguments - Where the language has a Windmill client (\`wmill\`), use it to interact with the platform @@ -176,6 +178,10 @@ needs becomes unreachable. references. A spread, a call or a computed key leaves the composer unable to tell which input feeds which field, so it offers no control at all — a bare \`flow_input.x\` for the whole object is read instead as that one input carrying every field +- A step linked to a saved agent (\`agent\` set) has no \`provider\` of its own. It exposes the same + two controls through its \`model\` and \`reasoning_effort\` inputs, which replace what the agent + saved: \`"model": { "type": "javascript", "expr": "flow_input.model" }\`. An empty model keeps the + saved one, an empty effort sends none, and the provider resource always stays the agent's - \`memory\` is what lets the agent see earlier turns; without it every message starts from nothing - \`streaming\` on makes the answer and its thinking appear token by token instead of all at once - \`user_attachments\` points at a flow input typed as an array of s3 objects @@ -609,6 +615,14 @@ In the flow schema, set the property type to \`"object"\` with format \`"resourc } \`\`\` +### When No Resource Type Fits + +A connection still comes in as one resource input, not as separate string inputs (a URL, a token) or a variable read inside a step: type the input \`resource-c_\` with a custom resource type holding the service's connection fields, its secret in a variable the resource references. The \`c_\` prefix of custom types keeps one apart from a hub type synced later under the same name. + +- If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. +- Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it. +- A plain variable is fine when the user asks for it. + ### As Step Input (Static Reference) Reference a specific resource using \`$res:\` prefix: @@ -648,6 +662,12 @@ Resources store credentials and configuration for external services. - \`value\` - Object containing the resource configuration - \`resource_type\` - Name of the resource type (e.g., "postgresql", "slack") +## Agents + +An agent, as the Agents page lists it, is a resource of type \`ai_agent\`. Its value holds the +agent's provider, system prompt, tools and memory settings, and a flow step uses a saved agent by +linking its path. + ## Variable References Reference variables in resource values: @@ -827,13 +847,23 @@ The prefix must be on the string itself. } \`\`\` +## When No Resource Type Fits + +The Windmill Hub publishes resource types for most services, and an instance gets them by syncing with the hub. When none fits the service: + +- If the instance is reported as not having synced the hub's types, mention that a superadmin can sync them: the hub most likely has one for the service. That holds for a type a hub script takes too: it is missing here until the sync, so say so before asking for a resource of it. Create one of your own only if the user still wants it, since after a sync the workspace would hold both. +- Otherwise, or when the user prefers it to syncing, propose a custom resource type named \`c_\` holding the service's connection fields (base URL, account or region identifiers, credentials), as in "Custom Resource Types" below, and ask the user before creating it: every resource of that type and every script taking one depends on its fields. +- A plain variable instead of a resource is fine when the user asks for it; without that, default to the resource, its secret in a variable it references. + ## Custom Resource Types +A custom type's name starts with \`c_\`: the hub's types reach every instance under their plain names, so the prefix keeps a custom type from clashing with one synced later. Scripts and flows refer to the full name: \`format: resource-c_custom_api\`, \`RT.CCustomApi\` in TypeScript, a \`c_custom_api\` TypedDict in Python. + Create custom resource types with JSON Schema: \`\`\`json { - "name": "custom_api", + "name": "c_custom_api", "schema": { "type": "object", "properties": { @@ -847,7 +877,7 @@ Create custom resource types with JSON Schema: } \`\`\` -Save as: \`custom_api.resource-type.json\` +Save as: \`c_custom_api.resource-type.json\` ## OAuth Resources @@ -890,7 +920,7 @@ def main(db: postgresql): export const RAW_APP_BASE = `# Windmill Raw Apps -Raw apps let you build custom frontends with React, Svelte, or Vue that connect to Windmill backend runnables and datatables. +Raw apps let you build custom frontends with React or Svelte that connect to Windmill backend runnables and datatables. ## App shape @@ -906,7 +936,7 @@ A new app gets the setup Windmill's own new-app dialog gives one: a framework, t ### Framework -Use the framework the user named. When they named none, follow what there is to follow: the app being edited, or the apps the request points at. With nothing to follow, use **React 19**, the recommended default, **without asking**. React 18, Svelte 5 and Vue are for when they are asked for. +Use the framework the user named. When they named none, follow what there is to follow: the app being edited, or the apps the request points at. With nothing to follow, use **React 19**, the recommended default, **without asking**. React 18 and Svelte 5 are for when they are asked for. These three are the only frameworks the raw app bundler builds. When the user asks to build or convert an app in another framework, write no code in it: say it is not available and offer these three instead. ### Data setup @@ -939,7 +969,7 @@ An app the user just started from the new-app dialog is already set up: its file ### Entrypoint -The entrypoint is \`index.tsx\` for React and \`index.ts\` for Svelte and Vue. It is both the bundling entrypoint (the bundler is esbuild) and the **mount** entrypoint: the preview executes the bundle against an empty \`
\` and auto-renders nothing, so the entrypoint must mount a top-level \`App\` itself. Keep the UI in \`App.tsx\` / \`App.svelte\` / \`App.vue\` and keep the entrypoint as the mount shim. +The entrypoint is \`index.tsx\` for React and \`index.ts\` for Svelte. It is both the bundling entrypoint (the bundler is esbuild) and the **mount** entrypoint: the preview executes the bundle against an empty \`
\` and auto-renders nothing, so the entrypoint must mount a top-level \`App\` itself. Keep the UI in \`App.tsx\` / \`App.svelte\` and keep the entrypoint as the mount shim. React (\`index.tsx\`): @@ -951,10 +981,12 @@ import App from './App' createRoot(document.getElementById('root')!).render() \`\`\` -Svelte (\`index.ts\`): \`mount(App, { target: document.getElementById('root')! })\`. Vue (\`index.ts\`): \`createApp(App).mount('#root')\`. +Svelte (\`index.ts\`): \`mount(App, { target: document.getElementById('root')! })\`. **Never replace the entrypoint with a bare component** (\`export default function App() { ... }\` and no mount call). A component that is defined but never mounted renders a blank screen with **no error thrown** — it never executes, so nothing reaches the console or the error overlay. If an app renders blank, check that the entrypoint still mounts \`App\` into \`#root\`. +**Set the browser tab title with \`document.title = '...'\`** (or a \`\` the framework renders into \`<head>\`). The app has no \`index.html\` of its own, so a \`<title>\` written there is never served; the deployed app's page shows whatever \`document.title\` holds, and follows it when it changes. + **Always begin every React file (\`.tsx\`/\`.jsx\`) that uses JSX with \`import React from 'react'\`.** esbuild uses the classic JSX transform, so \`React\` must be in scope wherever JSX appears — a missing import compiles fine but throws \`React is not defined\` at runtime, leaving a blank screen. ### Generated bindings (\`wmill.d.ts\` / \`wmill.ts\`) @@ -1024,16 +1056,16 @@ Apply it to customer data, internal notes and anything else a viewer of the demo ### Chat UIs over a flow in chat mode -A flow deployed with chat mode on is a chat backend (streaming answer, tool calls, memory, conversation history). Do not drive it through a runnable: add \`windmill-chat\` to \`package.json\` and use it directly, it detects the app's Windmill and credential. +A flow deployed with chat mode on is a chat backend (streaming answer, tool calls, memory, conversation history). Do not drive it through a runnable: add \`@windmill-labs/chat-sdk\` to \`package.json\` and use it directly, it detects the app's Windmill and credential. \`\`\`tsx -import { useWindmillChat } from 'windmill-chat/react' +import { useWindmillChat } from '@windmill-labs/chat-sdk/react' const chat = useWindmillChat({ flowPath: 'f/support/assistant' }) // chat.messages ({ role, content, pending, success, tool? }), chat.status, chat.sendMessage(text), chat.stop() \`\`\` -\`windmill-chat/ai-sdk\` gives a \`ChatTransport\` for the Vercel AI SDK's \`useChat\`, \`windmill-chat/assistant-ui\` a runtime for assistant-ui. The flow must be deployed, not a draft. A sandboxed app needs \`jobs:run\` in its frontend SDK scopes, plus \`flow_conversations:write\` for the conversation sidebar; without them the chat keeps history in the browser. +\`@windmill-labs/chat-sdk/ai-sdk\` gives a \`ChatTransport\` for the Vercel AI SDK's \`useChat\`, \`@windmill-labs/chat-sdk/assistant-ui\` a runtime for assistant-ui. The flow must be deployed, not a draft. A sandboxed app needs \`jobs:run\` in its frontend SDK scopes, plus \`flow_conversations:write\` for the conversation sidebar; without them the chat keeps history in the browser. ## Backend runnables @@ -1073,6 +1105,10 @@ def main(user_id: str): return user \`\`\` +#### Sharing code between runnables + +An inline runnable can import another inline runnable of the same app by its id, as a relative import: \`import { getDb } from './shared'\` (TypeScript, Bun) or \`from .shared import get_db\` (Python). This works across TypeScript (Bun) runnables and across Python runnables, not between the two. The imported runnable's own dependencies are picked up, and it can import further runnables in turn. A runnable that only holds helpers needs no \`main\`; the frontend just never calls it. A TypeScript runnable whose id is \`main\` cannot be imported, because that name is taken by the entrypoint file of every TypeScript job: give shared code any other id. + #### The \`wmill\` client is already authenticated An inline runnable runs as an ordinary Windmill job. \`import * as wmill from 'windmill-client'\` (TypeScript) and \`import wmill\` (Python) are already pointed at this instance and this workspace — there is nothing to configure. @@ -1116,6 +1152,18 @@ A draft app is reachable by nobody; deploying is what exposes it, and its backen Either one lets those people run the app's backend runnables, so never open an app up unless the user asks. When a deploy widens who may open the app, tell the user in plain words. +## Sandbox isolation and frontend API access + +New apps are sandboxed: the frontend is isolated from the viewer's own Windmill session and reaches Windmill only through its backend runnables, plus whatever frontend API scopes the app declares, which each viewer approves before the app runs. With isolation turned off, the frontend runs with the viewer's full session. The scopes are \`jobs:run\`, \`jobs:read\`, \`resources:read\`, \`variables:read\`, \`flow_conversations:read\` and \`flow_conversations:write\`; grant only the ones the frontend calls. The viewer's identity needs no scope: it is in \`window.ctx\`, and whoami works with any of them. + +Inside the sandbox, IndexedDB is unavailable, third-party sign-in and OAuth redirects fail, and requests to other services carry \`Origin: null\`, which an API that checks the origin rejects. Work around these first: call the service from a backend runnable, keep state in a data table or \`localStorage\`, or grant the frontend API scope the code needs. Suggest turning isolation off only when none of that works, and say plainly that it is a security risk: the app's code, and any XSS bug in it, then runs with the full Windmill permissions of everyone who opens the app. +You cannot turn isolation off; the user does it in the app's deploy settings. + +## Reading data as the viewer + +A backend runnable reads data as the app's identity (the publisher in publisher mode), the same for every viewer. An inline runnable can instead read data as the person using the app: its data table connections that name no role hold that viewer's roles, and object storage permission rules (which paths may be listed, read, written) are checked against the viewer. Resources, variables and everything else stay the app's, and an anonymous viewer is refused. Turn it on only when what the runnable reads should differ per viewer: row-level security on a data table, or per-user paths in object storage. Both are Enterprise Edition features. +Set it with \`viewerDataAccess: true\` on the backend runnable. + ## Data Tables Data tables are PostgreSQL databases managed by Windmill. Backend runnables query them via the \`wmill\` client; the frontend never queries them directly. **When the app needs to store or persist data** (user data, settings, application state, records, logs), use a data table. @@ -1127,6 +1175,7 @@ Data tables are PostgreSQL databases managed by Windmill. Backend runnables quer 3. **No DDL inside runnables**: runnables only read and write rows (SELECT, INSERT, UPDATE, DELETE) on existing tables. Never CREATE, ALTER or DROP a table from a runnable. 4. **Qualify table names**: an unqualified name means the \`public\` schema, so write every other table as \`schema.table\`, in table creation and queries alike. The app's \`data\` config sets the default datatable and schema its tables go in; use them consistently across runnables. 5. **Pass the role**: when the app's \`data.roles\` gives a data table a role, every \`wmill.datatable\` call on it passes that role (\`wmill.datatable('main', { role: 'analyst' })\` in TypeScript, \`wmill.datatable('main', role='analyst')\` in Python). The role only reaches what it was granted, so a query outside it fails with \`permission denied\`. +6. **Per-viewer rows**: a data table with no entry in \`data.roles\` is called with no role. Unless its default role is \`admin\`, the connection then holds the default role, if it may use it, plus every role it is a tenant of, and is refused when that is none. Whose roles those are follows the runnable's identity (see "Reading data as the viewer"). Row-level security policies written as \`pg_has_role(current_user, '<role>', 'member')\` then return the right rows with nothing added to the code. A role pins the connection to that one role either way, so a data table whose rows should differ per viewer gets no \`data.roles\` entry. Data table roles are an Enterprise Edition feature, self-hosted only. ### Querying in TypeScript (Bun/Deno) @@ -1178,7 +1227,7 @@ def main(user_id: str): 7. **Mark sensitive UI with \`data-wm-no-record\`** — it is what keeps that data out of a recorded demo; passwords are handled for you. 8. **Reach for \`backendAsync\` + \`waitJob\`** for long work — never a hand-written job-polling runnable. 9. **Deploy what a path runnable points at** — a path runnable aimed at a draft fails at runtime; tell the user what needs deploying. -10. **Use \`windmill-chat\` for a chat over a chat-mode flow** — never a runnable that runs the flow and polls its stream. +10. **Use \`@windmill-labs/chat-sdk\` for a chat over a chat-mode flow** — never a runnable that runs the flow and polls its stream. `; export const PIPELINE_BASE = `# Data pipeline authoring @@ -1190,10 +1239,48 @@ A **data pipeline** is NOT a flow. A flow is one runnable that orchestrates step A pipeline node that produces a table should almost always be a **\`duckdb\`** node that materializes its output into a **DuckLake** table with \`-- materialize ducklake://<name>/<table>\` (in a DuckDB node the annotation uses SQL \`--\` comment syntax; write the body as a bare \`SELECT\` and let the runtime do the write). DuckLake is the default lakehouse store for pipelines and is the shape the pipeline editor is built around, so prefer it unless the work specifically calls for something else: - \`postgresql\` / data tables — only for row-level, OLTP-style mutations against an existing Postgres data table (frequent single-row upserts/updates, transactional reads that an app queries live). -- \`bun\` / \`python3\` — only for non-tabular work that doesn't map to SQL: calling an external API, wrangling files, arbitrary glue. When such a node still produces tabular data for downstream steps, land it in DuckLake (write it with the wmill SDK / ducklake helpers) rather than inventing a parallel store. +- \`bun\` / \`python3\` — only for work that doesn't map to SQL: calling an external API, wrangling files, arbitrary glue. When such a node produces tabular data for downstream steps, write it **straight into DuckLake** (or a data table) from the same script — see "Ingesting from Python / TypeScript" below — rather than inventing a parallel store. Do not spread a pipeline across postgres, S3, and DuckLake when one DuckLake lake would do; a consistent DuckLake lakehouse is the goal. +## Ingesting from Python / TypeScript + +A node that fetches data in code (an API, a SaaS export, a scraper) writes the rows **directly** into their DuckLake table with \`wmill.ducklake()\`, or into a data table with \`wmill.datatable()\`. DuckLake already stores every table as parquet files in the workspace object storage, so **never stage the raw payload first** — no intermediate JSON / CSV / parquet file in S3 and no second "load the raw file" node. One ingestion node, one table. + +Pass the rows as a query argument (a list of dicts / array of objects is sent as JSON) and let SQL unnest them; declare the column types so the table gets a real schema: + +\`\`\`python +# pipeline +# on schedule +import wmill + +def main(): + rows = fetch_charges() # list[dict] + lake = wmill.ducklake() + lake.query(""" + CREATE OR REPLACE TABLE stripe_charges AS + SELECT unnest(from_json($rows, '[{"id":"VARCHAR","amount":"BIGINT","created":"BIGINT"}]'), recursive := true) + """, rows=rows).fetch() +\`\`\` + +\`\`\`ts +// pipeline +// on schedule +import * as wmill from "windmill-client" + +export async function main() { + const rows = await fetchCharges() + const lake = wmill.ducklake() + await lake\`CREATE OR REPLACE TABLE stripe_charges AS + SELECT unnest(from_json(\${rows}, '[{"id":"VARCHAR","amount":"BIGINT","created":"BIGINT"}]'), recursive := true)\`.fetch() +} +\`\`\` + +- Use \`INSERT INTO <table> SELECT ...\` instead of \`CREATE OR REPLACE\` to append (an incremental pull), with a one-time \`CREATE TABLE IF NOT EXISTS\` first. +- Assign the client to a variable (\`lake = wmill.ducklake()\`) and keep the SQL a **string literal** (Python) or a template without \`sql.raw\` (TS): that is what lets the graph record the node's write to \`ducklake://main/<table>\`. A chained \`wmill.ducklake().query(...)\` or SQL built in a variable records no output, so the downstream edge never forms. +- \`wmill.ducklake("<name>")\` targets a non-default catalog; \`wmill.datatable("<name>")\` writes a Postgres data table the same way (Python \`db.query(sql, *args)\` with \`$1\` placeholders, TS the same template form) — use it only when the data belongs in Postgres (see above). +- The downstream node triggers on the table itself: \`-- on ducklake://main/stripe_charges\`. + ## Storage prerequisites A DuckLake pipeline only runs once the workspace has **object storage** (S3 / Azure Blob / GCS) **and a DuckLake catalog** configured — DuckLake tables and \`s3://\` assets can't be materialized or read without it. Check which DuckLake catalogs the workspace has before you build. @@ -1236,7 +1323,7 @@ The key must be a **string literal** — the graph parser is static and cannot f ## Materialize (the managed output) -> **A MANAGED \`// materialize\` is DuckDB-only**, and its target must be a DuckLake table (\`ducklake://<name>/<table>\`). Deploy **rejects** a \`ducklake://\` \`// materialize\` on any other language (\`python3\`, \`bun\`, \`postgresql\`). For a non-DuckDB node writing the lake, do **not** use \`// materialize\` — write the output via the SDK (\`wmill.writeS3File(...)\`, ducklake helpers, …) and let it be inferred. Use \`duckdb\` when a node should materialize a DuckLake table. +> **A MANAGED \`// materialize\` is DuckDB-only**, and its target must be a DuckLake table (\`ducklake://<name>/<table>\`). Deploy **rejects** a \`ducklake://\` \`// materialize\` on any other language (\`python3\`, \`bun\`, \`postgresql\`). For a non-DuckDB node writing the lake, do **not** use \`// materialize\` — write the table itself with \`wmill.ducklake()\` (see "Ingesting from Python / TypeScript") and let the output be inferred. Use \`duckdb\` when a node should materialize a DuckLake table. > > The one target ANY language may declare (except a dbt script, whose writes come from its manifest) is a **warehouse relation**: \`// materialize manual dbt://<warehouse>/<schema>/<name>\`, where \`<warehouse>\` is a warehouse the workspace configures under Settings → dbt. \`manual\` is the only mode it has — nothing generates warehouse DDL, so the node issues its own write (a postgresql \`CREATE TABLE\` / \`INSERT\`, an SDK load, …) and the annotation records the outcome. Use it on an ingestion node whose output a dbt project reads as a \`source\`: the declared relation and the dbt model land on ONE graph node, and a downstream \`// on dbt://<warehouse>/<schema>/<name>\` fires when the ingestion node completes. @@ -1295,6 +1382,108 @@ FROM ducklake.main.orders GROUP BY 1 \`\`\` `; +export const DATATABLE_BASE = `# Data tables: schema changes, migrations and permissions + +A data table is a PostgreSQL database managed by Windmill and shared by the whole workspace: scripts, flows and apps reach it by name, \`main\` being the default. It is configured in the workspace settings (Data Tables), never created by SQL. + +## Changing the schema + +A data table with migrations enabled keeps its schema as an ordered list of versioned SQL migrations, each an \`up\` and an optional \`down\`. That list is what git sync and a workspace merge carry, and what rebuilds the schema in another workspace. So first find out whether migrations are enabled on the data table: + +- **Enabled**: make every schema change (CREATE, ALTER, DROP, anything but row data) as a new migration. A change made with plain SQL exists in that one database only, and the history no longer describes it. +- **Not enabled**: schema changes are plain SQL. Enabling migrations is a workspace admin's decision, made in the Data Tables settings, not a step to take on the way to something else. + +Writing a migration: + +- Wrap the statements in \`BEGIN; ... END;\` so it applies atomically. Leave the frame out only for a statement that cannot run in a transaction, such as \`CREATE INDEX CONCURRENTLY\`: such a migration can fail half applied. +- Give it a \`down\` that undoes the \`up\` whenever the change is reversible. Without one it cannot be rolled back. +- Declare the schemas it changes on a leading line of its \`up\`, \`-- schemas sales, billing\`, and qualify every name with its schema (\`sales.orders\`). A migration waits only on earlier migrations whose schemas overlap its own. One that declares none applies to the whole database and every later migration waits for it, so leave the line out only for a change that really spans the database, such as an extension. +- Migrations apply oldest first. One that is applied is not edited: correct it with a new migration. +- Row data is not schema. Insert, update and delete rows with plain SQL, migrations or not. + +## A migration is not a draft + +A migration is saved to the workspace and changes the database as soon as it is applied, for everything that reads those tables. To try a schema out without touching tables already in use: + +- put the new tables in a schema of their own, created by the same migration (\`CREATE SCHEMA IF NOT EXISTS\`), and point what you are building at it. A raw app names its schema in its \`data\` config, which is why a new app gets a new schema by default; +- or work in a workspace fork whose data table was cloned when the fork was created ("Clone schema only" or "Clone schema and data"): migrations applied there change that copy alone, and reach the parent workspace when the fork is merged. A fork that kept the original data table points at the parent's database, so a migration applied in it changes the parent's tables at once. + +Altering or dropping a table other scripts or apps use is neither of those: say what depends on it before doing it. + +## Roles and permissions + +Data table roles are a self-hosted Enterprise Edition feature, for data tables on managed Postgres (the instance database or the external managed instance). Without them, and always on a data table backed by a Postgres resource, everyone who can use the data table reaches all of it: there is no per-user, per-schema or per-row access to promise. + +A data table under roles is reached as a Postgres role, and Postgres enforces what that role was granted: + +- roles are assigned, per data table, to users, groups or folders. \`admin\` is the connection the data table had before roles: it owns the existing objects and ignores grants; +- a connection either names a role (\`wmill.datatable('main', { role: 'analyst' })\`, \`role='analyst'\` in Python, \`datatable://main?role=analyst\`) and holds that role alone, or names none and is resolved from the data table's default role; +- \`permission denied\` means the role in use lacks a grant. Say which role and which object: the grant is a data table admin's to give, in the roles drawer of the Database Manager. Do not switch to \`admin\` to get past it; +- a migration runs as the role its SQL declares on its first line, \`-- role <name>\`, the same one in its \`down\`. One that declares none runs as \`admin\`, which only those who may use \`admin\` can do. + +Read the Permissions section of https://www.windmill.dev/docs/core_concepts/persistent_storage/data_tables before designing who reaches what: it covers tenants, grants, the default role and the roles a connection that names none ends up holding, rows that differ per viewer through row-level security, and how forks and raw apps behave under roles. +`; + +export const WORKSPACE_SETTINGS_BASE = `# Workspace settings + +Everything an admin sets on the Workspace settings page is one document: a mapping of top-level +keys, the same layout as the \`settings.yaml\` file \`wmill sync\` keeps. Only a workspace admin can +read or change it. + +## Applying a document + +- A partial document changes only the keys it states; every key it omits is left as it is. +- Each key is replaced whole, so read its current value and send it back edited: a nested object + given with one field replaces the stored object with that one field. +- A key set to \`null\` clears that setting; an on/off switch cleared this way reads as \`false\`. +- Each setting is written through the same path the settings page uses, with the same validation + and audit log. The writes are not one transaction: when one fails the apply stops, and the + error says what was already written. +- A dry run reports the changes, as \`before\` / \`after\` per key, without writing anything. +- \`name\` is never applied: rename a workspace on the settings page. \`color\` is applied only when + set to a value, so \`null\` does not clear it. +- A key the server does not know is ignored and named in the warnings: check them, since a typo + otherwise reads as "nothing to change". +- A setting this edition does not offer (Enterprise only) is refused, by the dry run too. + +## Secrets + +\`slack_oauth_client_secret\` is the one secret. A read shows \`__SENSITIVE_AND_UNCHANGED__\` in place +of a set secret; sending that placeholder back keeps the stored value. A value starting with +\`$encrypted:\` is decrypted with the workspace key, and one encrypted with another workspace's key +is left unchanged with a warning; any other value is taken as plaintext. Never +write a secret you were not given: keep the placeholder. + +## Keys + +| Key | Value | +|---|---| +| \`auto_invite\` | \`{ enabled, mode: invite \\| add, operator, instance_groups?, instance_groups_roles? }\`. The instance groups are managed only when \`instance_groups\` is stated; clearing a group removes the members it added. | +| \`error_handler\` / \`success_handler\` | \`{ path, extra_args?, muted_on_cancel?, muted_on_user_path? }\`, \`path\` being \`script/<path>\` or \`flow/<path>\`. | +| \`error_handler_fallback_to_instance_alerts\` | Report failures to the instance critical alert channels when no error handler is set. | +| \`webhook\` | URL POSTed a JSON event on every change to the workspace's items. | +| \`ai_config\` | Providers, default and completion models, custom prompts, \`copilot_disabled\`. | +| \`large_file_storage\` | Workspace object storage: \`{ type, s3_resource_path \\| azure_blob_resource_path \\| gcs_resource_path, public_resource?, secondary_storage?, advanced_permissions? }\`. | +| \`git_sync\` | \`{ repositories: [...] }\`, each with \`git_repo_resource_path\`, \`script_path\` and \`settings\` (include/exclude paths and types). Server-owned fields (webhook secrets, sync state, credentials) are never read nor written. | +| \`datatable\` | \`{ datatables: { <name>: { database: { resource_type, resource_path? } } } }\`. Role permissions are \`datatable_permissions\`. | +| \`datatable_permissions\` | \`{ <data table>: { default_role, roles: { <role>: [tenants] } } }\`: who may connect to each data table as which role. Tenants are \`u/<user>\`, \`g/<group>\`, \`f/<folder>\` or \`*\`; \`admin\` is always a role, and \`default_role: null\` means no default. A data table the value omits is no longer under roles. Only a data table on a cluster Windmill manages can be. | +| \`protection_rules\` | \`{ <rule name>: { rules: [...], bypass_groups: [...], bypass_users: [...] } }\`, rules among \`DisableDirectDeployment\`, \`DisableWorkspaceForking\`, \`RestrictDeployToDeployers\`, \`RestrictAnonymousAppDeployment\`, \`RestrictPublicRunSharing\`, \`RestrictGuestAppDeployment\`, \`RequireIsolatedForks\`. A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. | +| \`ducklake\` | \`{ ducklakes: { <name>: { catalog, storage, ... } } }\`. | +| \`dbt_warehouses\` | dbt warehouse connections. | +| \`default_app\` | Path of the app shown as the workspace home. | +| \`default_scripts\` | \`{ order?, hidden?, default_script_content? }\` for the script language picker. | +| \`deploy_ui\` | \`{ include_path?, include_type? }\`: what the deploy-to-workspace UI offers. | +| \`operator_settings\` | What operators see and do: page visibility flags (\`runs\`, \`schedules\`, \`resources\`, \`variables\`, \`assets\`, \`audit_logs\`, \`groups\`, \`folders\`, \`workers\`, \`triggers\`) and write rights (\`manage_schedules\`, \`manage_triggers\`, \`builder_flows\`, \`builder_apps\`). A write right the value omits keeps its stored value. | +| \`mute_critical_alerts\` | Mute the workspace's critical alerts. | +| \`slack_team_id\`, \`slack_name\` | Read only: set by connecting Slack on the settings page. | +| \`slack_command_script\` / \`teams_command_script\` | Script or flow handling the Slack / Teams command. | +| \`slack_oauth_client_id\` / \`slack_oauth_client_secret\` | The workspace's own Slack OAuth app. Clearing either removes both. | +| \`public_app_execution_limit_per_minute\` | Rate limit for public apps, \`null\` for none. | +| \`guest_access_enabled\`, \`guest_jwt_public_key\`, \`guest_jwt_jwks_url\` | Guest access to public apps and the key that signs guest JWTs. | +| \`add_admins_and_developers_to_forks\` | Add the workspace's admins and developers to each fork. | +| \`color\` | Workspace color, \`#rrggbb\`. | +`; + export const WORKFLOW_AS_CODE_BASE = `# Windmill Workflow-as-Code Writing Guide ## Scope @@ -1389,6 +1578,8 @@ async def enrich(customer_id: str): In TypeScript, prefer assigning each task to a named top-level const. In Python, prefer top-level async functions decorated with \`@task()\` or \`@task\`. +Only the workflow body dispatches steps. A task runs as a single job, so a task or \`step()\` called from inside a task body runs in place in that job, as a plain function call: no child job, no checkpoint, and its task options (retry, timeout, tag) do not apply. \`sleep()\` there waits in the job, and \`taskScript()\` / \`taskFlow()\` / \`waitForApproval()\` (\`task_script()\` / \`task_flow()\` / \`wait_for_approval()\`) throw. To get separate jobs, call the tasks one after another from the workflow body and pass results between them. + For existing scripts: \`\`\`typescript @@ -1724,6 +1915,14 @@ async setProgress(percent: number, jobId?: any): Promise<void> */ async getProgress(jobId?: any): Promise<number | null> +/** + * Whether the worker running this job has received its shutdown signal. + * A draining worker waits for its current job to finish before exiting, so a + * long-running script can poll this and return early to let the worker be replaced. + * @param jobId? Job to check, defaults to the current job + */ +async workerIsDraining(jobId?: string): Promise<boolean> + /** * Set a flow user state * @param key key of the state @@ -1983,6 +2182,9 @@ async sleep(seconds: number): Promise<void> * \`fn\`'s result is encoded as JSON and decoded back before it is returned, so * the round that runs the body sees the same types every replay sees: a \`Date\` * comes back as a string, a \`Map\` as \`{}\`. {@link Jsonified} is that shape. + * + * Called from inside a task body, \`fn\` runs in place and nothing is + * checkpointed: a task is a single job and is never replayed. */ async step<T>(name: string, fn: () => T | Promise<T>,): Promise<Jsonified<Awaited<T>>> @@ -2396,6 +2598,18 @@ def set_progress(value: int, job_id: Optional[str] = None) # Progress value (0-100) or None if not set def get_progress(job_id: Optional[str] = None) -> Any +# Whether the worker running the job has received its shutdown signal. +# +# A draining worker waits for its current job to finish before exiting. A long-running +# script can poll this and return early so the worker can be replaced. +# +# Args: +# job_id: Job ID (defaults to current WM_JOB_ID) +# +# Returns: +# True if the worker running the job is draining +def worker_is_draining(job_id: Optional[str] = None) -> bool + # Set the user state of a flow at a given key def set_flow_user_state(key: str, value: Any) -> None @@ -2409,15 +2623,31 @@ def get_flow_user_state(key: str) -> Any def version() # Convenient helpers that takes an S3 resource as input and returns the settings necessary to -# initiate an S3 connection from DuckDB +# initiate an S3 connection from DuckDB. +# +# Without a resource path, the connection goes to the workspace storage through Windmill's +# S3 proxy when that storage is S3: address it as \`\`s3://<bucket>/<key>\`\` with the +# storage's own bucket, returned as \`\`s3_bucket\`\`. Pass the resource path to connect with +# the storage's own credentials instead. def get_duckdb_connection_settings(s3_resource_path: str = '') -> DuckDbConnectionSettings | None # Convenient helpers that takes an S3 resource as input and returns the settings necessary to -# initiate an S3 connection from Polars +# initiate an S3 connection from Polars. +# +# Without a resource path, the connection goes to the workspace storage through Windmill's +# S3 proxy when that storage is S3: address it as \`\`s3://<bucket>/<key>\`\` with the +# storage's own bucket, returned as \`\`s3_bucket\`\`. Pass the resource path to connect with +# the storage's own credentials instead. def get_polars_connection_settings(s3_resource_path: str = '') -> PolarsConnectionSettings # Convenient helpers that takes an S3 resource as input and returns the settings necessary to -# initiate an S3 connection using boto3 +# initiate an S3 connection using boto3. +# +# Without a resource path, the connection goes to the workspace storage through Windmill's +# S3 proxy when that storage is S3: pass the storage's own bucket as \`\`Bucket\`\`. The proxy +# serves object reads, writes, deletes, listing and multipart uploads of that bucket only; +# presigned URLs, other buckets and bucket-level APIs need the storage's own credentials, +# which passing the resource path returns. def get_boto3_connection_settings(s3_resource_path: str = '') -> Boto3ConnectionSettings # Load a file from the workspace s3 bucket and returns its content as bytes. @@ -2813,7 +3043,9 @@ def parse_sql_client_name(name: str) -> tuple[str, Optional[str]] # # - **v2 (inside @workflow)**: dispatches as a checkpoint step. # - **v1 (WM_JOB_ID set, no @workflow)**: dispatches via HTTP API. -# - **Standalone**: executes the function body directly. +# - **Standalone, or called from inside another v2 task**: executes the +# function body directly. A task runs as a single job, so the tasks it +# calls run in that same job, without their own options. # # A task runs as its own job, so its result is always encoded as JSON and # decoded back before the caller sees it: a \`\`datetime\`\` comes back as a @@ -2899,12 +3131,15 @@ def workflow(func) # \`\`fn\`\`'s result is encoded as JSON and decoded back before it is returned, # so the round that runs the body sees the same types every replay sees: # a \`\`datetime\`\` comes back as a string, a tuple as a list. +# +# Called from inside a task body, \`\`fn\`\` runs in place and nothing is +# checkpointed: a task is a single job and is never replayed. async def step(name: str, fn) # Server-side sleep — suspend the workflow for the given duration without holding a worker. # # Inside a @workflow, the parent job suspends and auto-resumes after \`\`seconds\`\`. -# Outside a workflow, falls back to \`\`asyncio.sleep\`\`. +# Outside a workflow, or inside a task body, falls back to \`\`asyncio.sleep\`\`. async def sleep(seconds: int) # Suspend the workflow and wait for an external approval. @@ -3026,8 +3261,9 @@ export async function getResumeUrls(approver?: string, flowLevel?: boolean): Pro * const call_api = task(fetchOrders, { retry: { attempts: 3, delay: 30, multiplier: 2 } }); * * Inside a \`workflow()\`, calling a task dispatches it as a step. - * Outside a workflow, the function body executes directly and - * {@link TaskOptions} — retry included — does not apply. + * Outside a workflow, or called from inside another task, the function body + * executes directly and {@link TaskOptions} — retry included — does not apply: + * a task runs as a single job, so the tasks it calls run in that same job. * * A task runs as its own job, so its result is always encoded as JSON and * decoded back before the caller sees it: a \`Date\` comes back as a string, a @@ -3071,6 +3307,9 @@ export function workflow<T>(fn: (...args: any[]) => Promise<T>) * \`fn\`'s result is encoded as JSON and decoded back before it is returned, so * the round that runs the body sees the same types every replay sees: a \`Date\` * comes back as a string, a \`Map\` as \`{}\`. {@link Jsonified} is that shape. + * + * Called from inside a task body, \`fn\` runs in place and nothing is + * checkpointed: a task is a single job and is never replayed. */ export async function step<T>(name: string, fn: () => T | Promise<T>,): Promise<Jsonified<Awaited<T>>> @@ -3169,7 +3408,9 @@ def get_resume_urls(approver: str = None, flow_level: bool = None) -> dict # # - **v2 (inside @workflow)**: dispatches as a checkpoint step. # - **v1 (WM_JOB_ID set, no @workflow)**: dispatches via HTTP API. -# - **Standalone**: executes the function body directly. +# - **Standalone, or called from inside another v2 task**: executes the +# function body directly. A task runs as a single job, so the tasks it +# calls run in that same job, without their own options. # # A task runs as its own job, so its result is always encoded as JSON and # decoded back before the caller sees it: a \`\`datetime\`\` comes back as a @@ -3255,12 +3496,15 @@ def workflow(func) # \`\`fn\`\`'s result is encoded as JSON and decoded back before it is returned, # so the round that runs the body sees the same types every replay sees: # a \`\`datetime\`\` comes back as a string, a tuple as a list. +# +# Called from inside a task body, \`\`fn\`\` runs in place and nothing is +# checkpointed: a task is a single job and is never replayed. async def step(name: str, fn) # Server-side sleep — suspend the workflow for the given duration without holding a worker. # # Inside a @workflow, the parent job suspends and auto-resumes after \`\`seconds\`\`. -# Outside a workflow, falls back to \`\`asyncio.sleep\`\`. +# Outside a workflow, or inside a task body, falls back to \`\`asyncio.sleep\`\`. async def sleep(seconds: int) # Suspend the workflow and wait for an external approval. @@ -3485,7 +3729,7 @@ class SqlQuery: export const OPENFLOW_SCHEMA = `## OpenFlow Schema -{"OpenFlow":{"type":"object","description":"Top-level flow definition containing metadata, configuration, and the flow structure","properties":{"summary":{"type":"string","description":"Short description of what this flow does"},"description":{"type":"string","description":"Detailed documentation for this flow"},"value":{"$ref":"#/components/schemas/FlowValue"},"schema":{"type":"object","description":"JSON Schema for flow inputs. Use this to define input parameters, their types, defaults, and validation. For resource inputs, set type to 'object' and format to 'resource-<type>' (e.g., 'resource-stripe')"},"on_behalf_of_email":{"type":"string","description":"Address of the account the flow runs on behalf of. Derived from on_behalf_of on read; accepted on write, where it is resolved to the account it names."},"on_behalf_of":{"type":"string","description":"The flow runs with the permissions of this identity: u/{username}, g/{group}, or a bare email when the username is itself email-shaped. The only stored half of the identity; on_behalf_of_email is derived from it. Omit it when writing and it is resolved from that address instead."}},"required":["summary","value"]},"FlowValue":{"type":"object","description":"The flow structure containing modules and optional preprocessor/failure handlers","properties":{"modules":{"type":"array","description":"Array of steps that execute in sequence. Each step can be a script, subflow, loop, or branch","items":{"$ref":"#/components/schemas/FlowModule"}},"failure_module":{"description":"Special module that executes when the flow fails. Receives error object with message, name, stack, and step_id. Must have id 'failure'. Only supports script/rawscript types","$ref":"#/components/schemas/FlowModule"},"preprocessor_module":{"description":"Special module that runs before the first step on external triggers. Must have id 'preprocessor'. Only supports script/rawscript types. Cannot reference other step results","$ref":"#/components/schemas/FlowModule"},"same_worker":{"type":"boolean","description":"If true, all steps run on the same worker for better performance"},"preserve_step_tags":{"type":"boolean","description":"If true and the flow runs on a custom worker tag, steps that declare their own non-empty tag run on it instead of inheriting the flow tag. Steps without their own tag still inherit the flow tag."},"concurrent_limit":{"type":"number","description":"Maximum number of concurrent executions of this flow"},"concurrency_key":{"type":"string","description":"Expression to group concurrent executions (e.g., by user ID)"},"concurrency_time_window_s":{"type":"number","description":"Time window in seconds for concurrent_limit"},"debounce_delay_s":{"type":"integer","description":"Delay in seconds to debounce flow executions"},"debounce_key":{"type":"string","description":"Expression to group debounced executions"},"debounce_args_to_accumulate":{"type":"array","description":"Arguments to accumulate across debounced executions","items":{"type":"string"}},"max_total_debouncing_time":{"type":"integer","description":"Maximum total time in seconds that a job can be debounced"},"max_total_debounces_amount":{"type":"integer","description":"Maximum number of times a job can be debounced"},"skip_expr":{"type":"string","description":"JavaScript expression to conditionally skip the entire flow"},"cache_ttl":{"type":"number","description":"Cache duration in seconds for flow results"},"cache_ignore_s3_path":{"type":"boolean"},"delete_after_secs":{"type":"integer","description":"If set, delete the flow job's args, result and logs after this many seconds following job completion"},"flow_env":{"type":"object","description":"Environment variables available to all steps. Values can be strings, JSON values, or special references: '$var:path' (workspace variable) or '$res:path' (resource).","additionalProperties":{}},"priority":{"type":"number","description":"Execution priority (higher numbers run first)"},"early_return":{"type":"string","description":"JavaScript expression to return early from the flow"},"chat_input_enabled":{"type":"boolean","description":"Whether this flow accepts chat-style input"},"notes":{"type":"array","description":"Sticky notes attached to the flow","items":{"$ref":"#/components/schemas/FlowNote"}},"groups":{"type":"array","description":"Semantic groups of modules for organizational purposes","items":{"$ref":"#/components/schemas/FlowGroup"}}},"required":["modules"]},"Retry":{"type":"object","description":"Retry configuration for failed module executions","properties":{"constant":{"type":"object","description":"Retry with constant delay between attempts","properties":{"attempts":{"type":"integer","description":"Number of retry attempts"},"seconds":{"type":"integer","description":"Seconds to wait between retries"}}},"exponential":{"type":"object","description":"Retry with exponential backoff: the n-th retry waits multiplier \\u00d7 seconds^n","properties":{"attempts":{"type":"integer","description":"Number of retry attempts"},"multiplier":{"type":"integer","description":"Multiplier for exponential backoff"},"seconds":{"type":"integer","minimum":1,"description":"Base of the exponential (seconds); the n-th retry waits multiplier \\u00d7 seconds^n, where n counts constant retries too"},"random_factor":{"type":"integer","minimum":0,"maximum":100,"description":"Random jitter percentage (0-100) to avoid thundering herd"}}},"retry_if":{"$ref":"#/components/schemas/RetryIf"}}},"FlowNote":{"type":"object","description":"A sticky note attached to a flow for documentation and annotation","properties":{"id":{"type":"string","description":"Unique identifier for the note"},"text":{"type":"string","description":"Content of the note"},"position":{"type":"object","description":"Position of the note in the flow editor","properties":{"x":{"type":"number","description":"X coordinate"},"y":{"type":"number","description":"Y coordinate"}},"required":["x","y"]},"size":{"type":"object","description":"Size of the note in the flow editor","properties":{"width":{"type":"number","description":"Width in pixels"},"height":{"type":"number","description":"Height in pixels"}},"required":["width","height"]},"color":{"type":"string","description":"Color of the note, one of: yellow, blue, green, purple, pink, orange, red, cyan, lime, gray. Any other value renders unstyled."},"type":{"type":"string","enum":["free","group"],"description":"Type of note - 'free' for standalone notes. 'group' notes are deprecated; segment a flow with FlowValue.groups instead."},"locked":{"type":"boolean","default":false,"description":"Whether the note is locked and cannot be edited or moved"},"contained_node_ids":{"type":"array","items":{"type":"string"},"description":"For group notes, the IDs of nodes contained within this group"}},"required":["id","text","color","type"]},"FlowGroup":{"type":"object","description":"A semantic group of flow modules for organizational purposes. Does not affect execution \\u2014 modules remain in their original position in the flow. Groups provide naming and collapsibility in the editor. Members are computed dynamically from all nodes on paths between start_id and end_id.","properties":{"summary":{"type":"string","description":"Display name for this group"},"note":{"type":"string","description":"Markdown note shown below the group header"},"autocollapse":{"type":"boolean","default":false,"description":"If true, this group is collapsed by default in the flow editor. UI hint only."},"start_id":{"type":"string","description":"ID of the first flow module in this group (topological entry point)"},"end_id":{"type":"string","description":"ID of the last flow module in this group (topological exit point)"},"color":{"type":"string","description":"Color for the group in the flow editor, one of: yellow, blue, green, purple, pink, orange, red, cyan, lime, gray. Omit it to let the editor pick one."}},"required":["start_id","end_id"]},"RetryIf":{"type":"object","description":"Conditional retry based on error or result","properties":{"expr":{"type":"string","description":"JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables"}},"required":["expr"]},"StopAfterIf":{"type":"object","description":"Early termination condition for a module","properties":{"skip_if_stopped":{"type":"boolean","description":"If true, following steps are skipped when this condition triggers"},"expr":{"type":"string","description":"JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"},"error_message":{"type":"string","nullable":true,"description":"Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised."},"error_include_result":{"type":"boolean","description":"When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false."}},"required":["expr"]},"FlowModule":{"type":"object","description":"A single step in a flow. Can be a script, subflow, loop, or branch","properties":{"id":{"type":"string","description":"Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"},"value":{"$ref":"#/components/schemas/FlowModuleValue"},"stop_after_if":{"description":"Early termination condition evaluated after this step completes","$ref":"#/components/schemas/StopAfterIf"},"stop_after_all_iters_if":{"description":"For loops only - early termination condition evaluated after all iterations complete","$ref":"#/components/schemas/StopAfterIf"},"skip_if":{"type":"object","description":"Conditionally skip this step based on previous results or flow inputs","properties":{"expr":{"type":"string","description":"JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.<step_id>'"}},"required":["expr"]},"sleep":{"description":"Delay before executing this step (in seconds or as expression)","$ref":"#/components/schemas/InputTransform"},"cache_ttl":{"type":"number","description":"Cache duration in seconds for this step's results"},"cache_ignore_s3_path":{"type":"boolean"},"timeout":{"description":"Maximum execution time in seconds (static value or expression)","$ref":"#/components/schemas/InputTransform"},"delete_after_secs":{"type":"integer","description":"If set, delete the step's args, result and logs after this many seconds following job completion"},"summary":{"type":"string","description":"Short description of what this step does"},"mock":{"type":"object","description":"Mock configuration for testing without executing the actual step","properties":{"enabled":{"type":"boolean","description":"If true, return mock value instead of executing"},"return_value":{"description":"Value to return when mocked"}}},"suspend":{"type":"object","description":"Configuration for approval/resume steps that wait for user input","properties":{"required_events":{"type":"integer","description":"Number of approvals required before continuing"},"timeout":{"type":"integer","description":"Timeout in seconds before auto-continuing or canceling"},"resume_form":{"type":"object","description":"Form schema for collecting input when resuming","properties":{"schema":{"type":"object","description":"JSON Schema for the resume form"}}},"user_auth_required":{"type":"boolean","description":"If true, only authenticated users can approve"},"user_groups_required":{"description":"Expression or list of groups that can approve","$ref":"#/components/schemas/InputTransform"},"self_approval_disabled":{"type":"boolean","description":"If true, the user who started the flow cannot approve"},"hide_cancel":{"type":"boolean","description":"If true, hide the cancel button on the approval form"},"continue_on_disapprove_timeout":{"type":"boolean","description":"If true, continue flow on timeout instead of canceling"},"skin":{"type":"string","enum":["detailed","minimal"],"description":"How the approval request is presented, on the approval page and in Slack/Teams approval messages. 'detailed' (used when unset) shows the flow details (arguments, graph, approvers); 'minimal' shows only the request: the step description, form and approve/reject actions"}}},"priority":{"type":"number","description":"Execution priority for this step (higher numbers run first)"},"continue_on_error":{"type":"boolean","description":"If true, flow continues even if this step fails"},"job_token_scopes":{"type":"array","nullable":true,"items":{"type":"string"},"description":"Scopes the token of this step's jobs is restricted to (domain:action[:resource], e.g. oidc:write), on top of the flow's own restriction: a step can only narrow it. Applies to everything the step runs (loop and branch bodies, AI agent tools)."},"retry":{"description":"Retry configuration if this step fails","$ref":"#/components/schemas/Retry"},"debouncing":{"description":"Debounce configuration for this step (EE only)","type":"object","properties":{"debounce_delay_s":{"type":"integer","description":"Delay in seconds to debounce this step's executions across flow runs"},"debounce_key":{"type":"string","description":"Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/<flow_path>-<step_id>"},"debounce_args_to_accumulate":{"type":"array","description":"Array-type arguments to accumulate across debounced executions","items":{"type":"string"}},"max_total_debouncing_time":{"type":"integer","description":"Maximum total time in seconds before forced execution"},"max_total_debounces_amount":{"type":"integer","description":"Maximum number of debounces before forced execution"}}}},"required":["value","id"]},"InputTransform":{"description":"Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs","oneOf":[{"$ref":"#/components/schemas/StaticTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type","mapping":{"static":"#/components/schemas/StaticTransform","javascript":"#/components/schemas/JavascriptTransform","ai":"#/components/schemas/AiTransform"}}},"StaticTransform":{"type":"object","description":"Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'","properties":{"value":{"description":"The static value. For resources, use format '$res:path/to/resource'"},"type":{"type":"string","enum":["static"]}},"required":["type"]},"JavascriptTransform":{"type":"object","description":"JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')","properties":{"expr":{"type":"string","description":"JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"},"type":{"type":"string","enum":["javascript"]}},"required":["expr","type"]},"AiTransform":{"type":"object","description":"Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.","properties":{"type":{"type":"string","enum":["ai"]}},"required":["type"]},"AIProviderKind":{"type":"string","description":"Supported AI provider types","enum":["openai","azure_openai","azure_foundry","anthropic","mistral","deepseek","googleai","groq","openrouter","togetherai","customai","aws_bedrock","typesafe","cloudflare"]},"ProviderConfig":{"type":"object","description":"Complete AI provider configuration with resource reference and model selection","properties":{"kind":{"$ref":"#/components/schemas/AIProviderKind"},"resource":{"type":"string","description":"Resource reference in format '$res:{resource_path}' pointing to provider credentials"},"model":{"type":"string","description":"Model identifier (e.g., 'gpt-4', 'claude-3-opus-20240229', 'gemini-pro')"},"reasoning_effort":{"type":"string","description":"Provider-native reasoning effort token (e.g. 'low', 'high', 'none') for models that support extended thinking. Optional; unset leaves the provider default."}},"required":["kind","resource","model"]},"StaticProviderTransform":{"type":"object","description":"Static provider configuration passed directly to the AI agent","properties":{"value":{"$ref":"#/components/schemas/ProviderConfig"},"type":{"type":"string","enum":["static"]}},"required":["type","value"]},"ProviderTransform":{"description":"Provider configuration - can be static (ProviderConfig), JavaScript expression, or AI-determined","oneOf":[{"$ref":"#/components/schemas/StaticProviderTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type","mapping":{"static":"#/components/schemas/StaticProviderTransform","javascript":"#/components/schemas/JavascriptTransform","ai":"#/components/schemas/AiTransform"}}},"MemoryOff":{"type":"object","description":"No conversation memory/context","properties":{"kind":{"type":"string","enum":["off"]}},"required":["kind"]},"MemoryWindow":{"type":"object","description":"Keeps the most recent messages of the memory named by the run's memory id (or the step's\\n\`memory_id\`). Without a memory id the agent runs without memory.\\n","properties":{"kind":{"type":"string","enum":["window"]},"context_length":{"type":"integer","description":"Number of most recent messages to load and store. 0 turns memory off."}},"required":["kind","context_length"]},"MemoryAuto":{"type":"object","deprecated":true,"description":"Deprecated, still read as it was written: the run's memory id, else the \`memory_id\` here.\\nThe step's own \`memory_id\` is not read while this kind is set; switch the kind to \`window\`\\nto use it. Without a \`context_length\`, or with 0, it is \`off\` and reads \`previous_messages\`.\\n","properties":{"kind":{"type":"string","enum":["auto"]},"context_length":{"type":"integer","description":"Maximum number of messages to retain in context"},"memory_id":{"type":"string","description":"Identifier for persistent memory across agent invocations"}},"required":["kind"]},"MemoryCompaction":{"type":"object","description":"Keeps the whole memory named by the run's memory id (or the step's \`memory_id\`), replacing\\nits older part with a summary as the conversation approaches the model's context window.\\nWithout a memory id the agent runs without memory, and compaction bounds the run's own loop.\\n","properties":{"kind":{"type":"string","enum":["compaction"]},"context_window":{"type":"integer","description":"Overrides the context window looked up from the model, in tokens. Only a model\\nWindmill does not know needs one; those fall back to 128000.\\n"}},"required":["kind"]},"MemoryMessage":{"type":"object","description":"A single message in conversation history","properties":{"role":{"type":"string","enum":["user","assistant","system"]},"content":{"type":"string"}},"required":["role","content"]},"MemoryManual":{"type":"object","deprecated":true,"description":"Deprecated, still read as it was written. Move the step to \`off\` with \`previous_messages\` instead.","properties":{"kind":{"type":"string","enum":["manual"]},"messages":{"type":"array","items":{"$ref":"#/components/schemas/MemoryMessage"}}},"required":["kind","messages"]},"MemoryConfig":{"description":"Managed memory, stored by Windmill and replayed with each request. The memory is named by a memory id, see \`memory_id\`. While it is off, a step can supply its history in \`previous_messages\`.","oneOf":[{"$ref":"#/components/schemas/MemoryOff"},{"$ref":"#/components/schemas/MemoryWindow"},{"$ref":"#/components/schemas/MemoryCompaction"},{"$ref":"#/components/schemas/MemoryAuto"},{"$ref":"#/components/schemas/MemoryManual"}],"discriminator":{"propertyName":"kind","mapping":{"off":"#/components/schemas/MemoryOff","window":"#/components/schemas/MemoryWindow","compaction":"#/components/schemas/MemoryCompaction","auto":"#/components/schemas/MemoryAuto","manual":"#/components/schemas/MemoryManual"}}},"StaticMemoryTransform":{"type":"object","description":"Static memory configuration passed directly to the AI agent","properties":{"value":{"$ref":"#/components/schemas/MemoryConfig"},"type":{"type":"string","enum":["static"]}},"required":["type","value"]},"MemoryTransform":{"description":"Memory configuration - can be static (MemoryConfig), JavaScript expression, or AI-determined","oneOf":[{"$ref":"#/components/schemas/StaticMemoryTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type","mapping":{"static":"#/components/schemas/StaticMemoryTransform","javascript":"#/components/schemas/JavascriptTransform","ai":"#/components/schemas/AiTransform"}}},"FlowModuleValue":{"description":"The actual implementation of a flow step. Can be a script (inline or referenced), subflow, loop, branch, or special module type","oneOf":[{"$ref":"#/components/schemas/RawScript"},{"$ref":"#/components/schemas/PathScript"},{"$ref":"#/components/schemas/PathFlow"},{"$ref":"#/components/schemas/ForloopFlow"},{"$ref":"#/components/schemas/WhileloopFlow"},{"$ref":"#/components/schemas/BranchOne"},{"$ref":"#/components/schemas/BranchAll"},{"$ref":"#/components/schemas/Identity"},{"$ref":"#/components/schemas/AiAgent"},{"$ref":"#/components/schemas/AiDecision"}],"discriminator":{"propertyName":"type","mapping":{"rawscript":"#/components/schemas/RawScript","script":"#/components/schemas/PathScript","flow":"#/components/schemas/PathFlow","forloopflow":"#/components/schemas/ForloopFlow","whileloopflow":"#/components/schemas/WhileloopFlow","branchone":"#/components/schemas/BranchOne","branchall":"#/components/schemas/BranchAll","identity":"#/components/schemas/Identity","aiagent":"#/components/schemas/AiAgent","aidecision":"#/components/schemas/AiDecision"}}},"RawScript":{"type":"object","description":"Inline script with code defined directly in the flow. Use 'bun' as default language if unspecified. The script receives arguments from input_transforms","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"content":{"type":"string","description":"The script source code. Should export a 'main' function"},"language":{"type":"string","description":"Programming language for this script","enum":["deno","bun","bunnative","python3","go","bash","powershell","postgresql","mysql","bigquery","snowflake","mssql","oracledb","graphql","nativets","php","rust","ansible","csharp","nu","java","ruby","rlang","duckdb"]},"path":{"type":"string","description":"Optional path for saving this script"},"lock":{"type":"string","description":"Lock file content for dependencies"},"type":{"type":"string","enum":["rawscript"]},"tag":{"type":"string","description":"Worker group tag for execution routing"},"concurrent_limit":{"type":"number","description":"Maximum concurrent executions of this script"},"concurrency_time_window_s":{"type":"number","description":"Time window for concurrent_limit"},"custom_concurrency_key":{"type":"string","description":"Custom key for grouping concurrent executions"},"is_trigger":{"type":"boolean","description":"If true, this script is a trigger that can start the flow"},"assets":{"type":"array","description":"External resources this script accesses (S3 objects, resources, etc.)","items":{"type":"object","required":["path","kind"],"properties":{"path":{"type":"string","description":"Path to the asset"},"kind":{"type":"string","description":"Type of asset","enum":["s3object","resource","ducklake","datatable","volume","dbt"]},"access_type":{"type":"string","nullable":true,"description":"Access level for this asset","enum":["r","w","rw"]},"alt_access_type":{"type":"string","nullable":true,"description":"Alternative access level","enum":["r","w","rw"]}}}}},"required":["type","content","language","input_transforms"]},"PathScript":{"type":"object","description":"Reference to an existing script by path. Use this when calling a previously saved script instead of writing inline code","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"path":{"type":"string","description":"Path to the script in the workspace (e.g., 'f/scripts/send_email')"},"hash":{"type":"string","description":"Optional specific version hash of the script to use"},"type":{"type":"string","enum":["script"]},"tag_override":{"type":"string","description":"Override the script's default worker group tag"},"is_trigger":{"type":"boolean","description":"If true, this script is a trigger that can start the flow"}},"required":["type","path","input_transforms"]},"PathFlow":{"type":"object","description":"Reference to an existing flow by path. Use this to call another flow as a subflow","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the subflow's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"path":{"type":"string","description":"Path to the flow in the workspace (e.g., 'f/flows/process_user')"},"type":{"type":"string","enum":["flow"]}},"required":["type","path","input_transforms"]},"ForloopFlow":{"type":"object","description":"Executes nested modules in a loop over an iterator. Inside the loop, use 'flow_input.iter.value' to access the current iteration value, and 'flow_input.iter.index' for the index. Supports parallel execution for better performance on I/O-bound operations","properties":{"modules":{"type":"array","description":"Steps to execute for each iteration. These can reference the iteration value via 'flow_input.iter.value'","items":{"$ref":"#/components/schemas/FlowModule"}},"iterator":{"description":"JavaScript expression that returns an array to iterate over. Can reference 'results.step_id' or 'flow_input'","$ref":"#/components/schemas/InputTransform"},"skip_failures":{"type":"boolean","description":"If true, iteration failures don't stop the loop. Failed iterations return null"},"type":{"type":"string","enum":["forloopflow"]},"parallel":{"type":"boolean","description":"If true, iterations run concurrently (faster for I/O-bound operations). Use with parallelism to control concurrency"},"parallelism":{"description":"Maximum number of concurrent iterations when parallel=true. Limits resource usage. Can be static number or expression","$ref":"#/components/schemas/InputTransform"},"squash":{"type":"boolean"}},"required":["modules","iterator","skip_failures","type"]},"WhileloopFlow":{"type":"object","description":"Executes nested modules repeatedly until stopped. The implicit iterator is the iteration counter, so 'flow_input.iter.value' equals 'flow_input.iter.index' (0, 1, 2, ...) and never carries state. To carry state across iterations, a step reads its own previous-iteration result via 'results.<its_own_id>' with a first-iteration fallback - the loop's stop_after_if must then be on that inner step (a plain single-step body with stop_after_if on the loop module does not resolve 'results' across iterations and never terminates); plain counters can instead be derived from 'flow_input.iter.index', which works in every configuration. stop_after_if is evaluated after each iteration - on the loop module 'result' is the last iteration's result","properties":{"modules":{"type":"array","description":"Steps to execute in each iteration","items":{"$ref":"#/components/schemas/FlowModule"}},"skip_failures":{"type":"boolean","description":"If true, iteration failures don't stop the loop. Failed iterations return null"},"type":{"type":"string","enum":["whileloopflow"]},"parallel":{"type":"boolean","description":"If true, iterations run concurrently (use with caution in while loops)"},"parallelism":{"description":"Maximum number of concurrent iterations when parallel=true","$ref":"#/components/schemas/InputTransform"},"squash":{"type":"boolean"}},"required":["modules","skip_failures","type"]},"BranchOne":{"type":"object","description":"Conditional branching where only the first matching branch executes. Branches are evaluated in order, and the first one with a true expression runs. If no branches match, the default branch executes","properties":{"branches":{"type":"array","description":"Array of branches to evaluate in order. The first branch with expr evaluating to true executes","items":{"type":"object","properties":{"summary":{"type":"string","description":"Short description of this branch condition"},"expr":{"type":"string","description":"JavaScript expression that returns boolean. Can use 'results.step_id' or 'flow_input'. First true expr wins"},"modules":{"type":"array","description":"Steps to execute if this branch's expr is true","items":{"$ref":"#/components/schemas/FlowModule"}}},"required":["modules","expr"]}},"default":{"type":"array","description":"Steps to execute if no branch expressions match","items":{"$ref":"#/components/schemas/FlowModule"}},"type":{"type":"string","enum":["branchone"]}},"required":["branches","default","type"]},"BranchAll":{"type":"object","description":"Parallel branching where all branches execute simultaneously. Unlike BranchOne, all branches run regardless of conditions. Useful for executing independent tasks concurrently","properties":{"branches":{"type":"array","description":"Array of branches that all execute (either in parallel or sequentially)","items":{"type":"object","properties":{"summary":{"type":"string","description":"Short description of this branch's purpose"},"skip_failure":{"type":"boolean","description":"If true, failure in this branch doesn't fail the entire flow"},"modules":{"type":"array","description":"Steps to execute in this branch","items":{"$ref":"#/components/schemas/FlowModule"}}},"required":["modules"]}},"type":{"type":"string","enum":["branchall"]},"parallel":{"type":"boolean","description":"If true, all branches execute concurrently. If false, they execute sequentially"}},"required":["branches","type"]},"AgentTool":{"type":"object","description":"A tool available to an AI agent. Can be a flow module or an external MCP (Model Context Protocol) tool","properties":{"id":{"type":"string","description":"Unique identifier for this tool. Cannot contain spaces - use underscores instead (e.g., 'get_user_data' not 'get user data')"},"summary":{"type":"string","description":"The name the AI agent calls this tool by, not a human label. On a flowmodule tool it must match ^[a-zA-Z0-9_]+$ - letters, numbers and underscores only (e.g. 'search_documentation', not 'Search documentation') - and always be set; on an mcp or websearch tool it is a plain label. Put the human-readable explanation in 'description'."},"description":{"type":"string","description":"Free-text description of the tool given to the AI to decide when and how to call it. Overrides the description auto-derived from the underlying script."},"job_token_scopes":{"type":"array","nullable":true,"items":{"type":"string"},"description":"Scopes the token of this tool's jobs is restricted to, on top of the agent step's own restriction: a tool can only narrow it."},"value":{"$ref":"#/components/schemas/ToolValue"}},"required":["id","value"]},"ToolValue":{"description":"The implementation of a tool. Can be a flow module (script/flow) or an MCP tool reference","oneOf":[{"$ref":"#/components/schemas/FlowModuleTool"},{"$ref":"#/components/schemas/McpToolValue"},{"$ref":"#/components/schemas/WebsearchToolValue"}],"discriminator":{"propertyName":"tool_type","mapping":{"flowmodule":"#/components/schemas/FlowModuleTool","mcp":"#/components/schemas/McpToolValue","websearch":"#/components/schemas/WebsearchToolValue"}}},"FlowModuleTool":{"description":"A tool implemented as a flow module (script, flow, etc.). The AI can call this like any other flow module","allOf":[{"type":"object","properties":{"tool_type":{"type":"string","enum":["flowmodule"]}},"required":["tool_type"]},{"$ref":"#/components/schemas/FlowModuleValue"}]},"WebsearchToolValue":{"type":"object","description":"A tool implemented as a websearch tool. The AI can call this like any other websearch tool","properties":{"tool_type":{"type":"string","enum":["websearch"]}},"required":["tool_type"]},"McpToolValue":{"type":"object","description":"Reference to an external MCP (Model Context Protocol) tool. The AI can call tools from MCP servers","properties":{"tool_type":{"type":"string","enum":["mcp"]},"resource_path":{"type":"string","description":"Path to the MCP resource/server configuration"},"include_tools":{"type":"array","description":"Whitelist of specific tools to include from this MCP server","items":{"type":"string"}},"exclude_tools":{"type":"array","description":"Blacklist of tools to exclude from this MCP server","items":{"type":"string"}}},"required":["tool_type","resource_path"]},"AiAgent":{"type":"object","description":"AI agent step that can use tools to accomplish tasks. The agent receives inputs and can call any of its configured tools to complete the task","properties":{"input_transforms":{"type":"object","description":"Input parameters for the AI agent mapped to their values","properties":{"provider":{"$ref":"#/components/schemas/ProviderTransform"},"output_type":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Output format type.\\nValid values: 'text' (default) - plain text response, 'image' - image generation\\n"},"user_message":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"The user's prompt/message to the AI agent. Supports variable interpolation with\\nflow.input syntax. Required unless memory is off and \`previous_messages\` supplies\\nthe prompt; image output always needs it.\\n"},"system_prompt":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"System instructions that guide the AI's behavior, persona, and response style. Optional."},"streaming":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Boolean. If true, stream the AI response incrementally.\\nStreaming events include: token_delta, reasoning_token_delta, tool_call, tool_call_arguments, tool_execution, tool_result\\n"},"memory":{"$ref":"#/components/schemas/MemoryTransform"},"memory_id":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"String. Names the memory this step reads and writes, overriding the memory id the run\\nwas started with (the chat conversation, an app chat session or the \`memory_id\` run\\nparameter). Leave unset to use the run's memory id. A fixed value shares one memory\\nacross every run; an expression such as \`flow_input.customer_id\` keeps one memory per\\nkey. When it evaluates to an empty value the agent runs without memory. Read only\\nwhile \`memory\` is \`window\` or \`compaction\`: it is ignored when memory is off, and an\\nolder \`auto\` or \`manual\` memory reads neither history input.\\n"},"previous_messages":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Array of MemoryMessage. History supplied by the flow, sent between the system prompt\\nand the user message. Read only while \`memory\` is off or absent: managed memory\\nignores it, and an older \`auto\` or \`manual\` memory reads neither history input.\\n"},"output_schema":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"JSON Schema object defining structured output format. Used when you need the AI to return data in a specific shape.\\nSupports standard JSON Schema properties: type, properties, required, items, enum, pattern, minLength, maxLength, minimum, maximum, etc.\\nExample: { type: 'object', properties: { name: { type: 'string' }, age: { type: 'integer' } }, required: ['name'] }\\n"},"user_attachments":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Array of file references (images or PDFs) for the AI agent.\\nFormat: Array<{ bucket: string, key: string }> - S3 object references\\nExample: [{ bucket: 'my-bucket', key: 'documents/report.pdf' }]\\n"},"enabled_tools":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Array of strings naming which of the tools configured in \`tools\` the agent may call\\nthis run. Leaving it unset carries every one of them; an empty array carries none.\\nA tool is named as the model is shown it. An entry the model is shown nothing of is\\nnamed by what identifies it instead: an MCP server by its resource path, carrying\\nevery tool it exposes (which of them stays that entry's include_tools/exclude_tools),\\nand a websearch entry by the reserved name '__wm_web_search', whatever summary it carries\\n(no tool may take that name).\\nExample: ['get_user', 'u/admin/github_mcp', '__wm_web_search']\\n"},"max_completion_tokens":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Integer. Maximum number of tokens the AI will generate in its response.\\nRange: 1 to 4,294,967,295. Typical values: 256-4096 for most use cases.\\n"},"temperature":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Float. Controls randomness/creativity of responses.\\nRange: 0.0 to 2.0 (provider-dependent)\\n- 0.0 = deterministic, focused responses\\n- 0.7 = balanced (common default)\\n- 1.0+ = more creative/random\\n"},"max_iterations":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Number. Limits how many times the agent can loop through reasoning and tool use.\\nRange: 1-1000.\\n"}}},"tools":{"type":"array","description":"Array of tools the agent can use. The agent decides which tools to call based on the task","items":{"$ref":"#/components/schemas/AgentTool"}},"type":{"type":"string","enum":["aiagent"]},"tag":{"type":"string","description":"Worker group tag for execution routing. If not set, the AI agent step runs on the flow's tag (default \`flow\`)"},"omit_output_from_conversation":{"type":"boolean","default":false,"description":"If true, this AI agent step does not persist its assistant or tool messages to the flow conversation when chat mode is enabled."},"agent":{"type":"string","description":"Path of a reusable \`ai_agent\` resource (hybrid linking). When set, the agent brain\\nconfig (provider/model/system prompt/etc.) and tool set are resolved at runtime from\\nthat resource; the module's input_transforms then only carry the flow-local inputs\\n(user_message, user_attachments, enabled_tools and the history inputs memory_id and previous_messages).\\n"},"tool_inputs":{"type":"object","description":"Host-local wiring for an agent's tool inputs, keyed by tool id then input key. Binds the\\nreferenced agent's tools to this flow's context (flow_input/results) without mutating the\\nshared resource; overlaid onto the tools' input_transforms at runtime \\u2014 including when\\n\`agent\` is unset, since a step forked for editing keeps these overrides until it is saved\\nback or unlinked.\\n","additionalProperties":{"type":"object","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}}},"parallel":{"type":"boolean","description":"If true, the agent can execute multiple tool calls in parallel"}},"required":["type","input_transforms"]},"AiDecision":{"type":"object","description":"AI decision step: one call to a decision model (TypeSafe's Jev, Cloudflare's\\nJev-compatible Clef, or OpenAI's Decisions API) that answers typed questions about a\\nstate with calibrated probabilities, instead of generating text.\\nPrefer it over an AI agent to classify, route, score or check something: it is fast,\\ncheap and its answers are structured. Its result is { output: { <question name>: answer },\\nmodel, usage }, so a later step reads e.g. results.<id>.output.intent.choice. To route on\\nthe answers, follow it with a branchone whose branch exprs read\\nresults.<id>.output.<question>.choice. Usable as an AI agent tool, where the calling agent\\nsupplies the state.\\n","properties":{"input_transforms":{"type":"object","description":"Input parameters for the decision mapped to their values","properties":{"provider":{"$ref":"#/components/schemas/ProviderTransform"},"state":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"What the questions are asked about: a string, an object or an array of strings.\\nAn object with descriptive keys holding only what the questions need works best.\\nExample: { message: flow_input.message, plan: results.a.plan }\\n"},"questions":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Object mapping each question name to { type, instructions, criteria }, where type is:\\n- 'choice': criteria maps each option to its description (up to 255); the answer\\n has choice, probabilities and confidence\\n- 'score': criteria is an ordered array of 2 to 10 level descriptions; the answer\\n has score, legend, probabilities and confidence\\n- 'noul': yes/no, criteria optionally { true, false } descriptions; the answer has\\n noul, the probability of yes (0 to 1)\\nExample: { intent: { type: 'choice', instructions: 'What does the customer want?',\\ncriteria: { refund: 'Money back', bug: 'Something is broken' } } }\\n"}},"required":["provider","state","questions"]},"type":{"type":"string","enum":["aidecision"]},"tag":{"type":"string","description":"Worker group tag for execution routing. If not set, the step runs on the flow's tag (default \`flow\`)"}},"required":["type","input_transforms"]},"Identity":{"type":"object","description":"Pass-through module that returns its input unchanged. Useful for flow structure or as a placeholder","properties":{"type":{"type":"string","enum":["identity"]},"flow":{"type":"boolean","description":"If true, marks this as a flow identity (special handling)"}},"required":["type"]},"FlowStatus":{"type":"object","properties":{"step":{"type":"integer"},"modules":{"type":"array","items":{"$ref":"#/components/schemas/FlowStatusModule"}},"user_states":{"additionalProperties":true},"preprocessor_module":{"allOf":[{"$ref":"#/components/schemas/FlowStatusModule"}]},"failure_module":{"allOf":[{"$ref":"#/components/schemas/FlowStatusModule"},{"type":"object","properties":{"parent_module":{"type":"string"}}}]},"retry":{"type":"object","properties":{"fail_count":{"type":"integer"},"failed_jobs":{"type":"array","items":{"type":"string","format":"uuid"}}}}},"required":["step","modules","failure_module"]},"FlowStatusModule":{"type":"object","properties":{"type":{"type":"string","enum":["WaitingForPriorSteps","WaitingForEvents","WaitingForExecutor","InProgress","Success","Failure"]},"id":{"type":"string"},"job":{"type":"string","format":"uuid"},"count":{"type":"integer"},"progress":{"type":"integer"},"iterator":{"type":"object","properties":{"index":{"type":"integer"},"itered":{"type":"array","items":{}},"itered_len":{"type":"integer"},"args":{}}},"flow_jobs":{"type":"array","items":{"type":"string"}},"flow_jobs_success":{"type":"array","items":{"type":"boolean"}},"flow_jobs_duration":{"type":"object","properties":{"started_at":{"type":"array","items":{"type":"string"}},"duration_ms":{"type":"array","items":{"type":"integer"}}}},"branch_chosen":{"type":"object","properties":{"type":{"type":"string","enum":["branch","default"]},"branch":{"type":"integer"}},"required":["type"]},"branchall":{"type":"object","properties":{"branch":{"type":"integer"},"len":{"type":"integer"}},"required":["branch","len"]},"approvers":{"type":"array","items":{"type":"object","properties":{"resume_id":{"type":"integer"},"approver":{"type":"string"}},"required":["resume_id","approver"]}},"failed_retries":{"type":"array","items":{"type":"string","format":"uuid"}},"skipped":{"type":"boolean"},"agent_actions":{"type":"array","items":{"type":"object","oneOf":[{"type":"object","properties":{"job_id":{"type":"string","format":"uuid"},"function_name":{"type":"string"},"type":{"type":"string","enum":["tool_call"]},"module_id":{"type":"string"}},"required":["job_id","function_name","type","module_id"]},{"type":"object","properties":{"call_id":{"type":"string","format":"uuid"},"function_name":{"type":"string"},"resource_path":{"type":"string"},"type":{"type":"string","enum":["mcp_tool_call"]},"arguments":{"type":"object"}},"required":["call_id","function_name","resource_path","type"]},{"type":"object","properties":{"type":{"type":"string","enum":["web_search"]}},"required":["type"]},{"type":"object","properties":{"type":{"type":"string","enum":["message"]}},"required":["content","type"]}]}},"agent_actions_success":{"type":"array","items":{"type":"boolean"}}},"required":["type"]}}`; +{"OpenFlow":{"type":"object","description":"Top-level flow definition containing metadata, configuration, and the flow structure","properties":{"summary":{"type":"string","description":"Short description of what this flow does"},"description":{"type":"string","description":"Detailed documentation for this flow"},"value":{"$ref":"#/components/schemas/FlowValue"},"schema":{"type":"object","description":"JSON Schema for flow inputs. Use this to define input parameters, their types, defaults, and validation. For resource inputs, set type to 'object' and format to 'resource-<type>' (e.g., 'resource-stripe')"},"on_behalf_of_email":{"type":"string","description":"Address of the account the flow runs on behalf of. Derived from on_behalf_of on read; accepted on write, where it is resolved to the account it names."},"on_behalf_of":{"type":"string","description":"The flow runs with the permissions of this identity: u/{username}, g/{group}, or a bare email when the username is itself email-shaped. The only stored half of the identity; on_behalf_of_email is derived from it. Omit it when writing and it is resolved from that address instead."}},"required":["summary","value"]},"FlowValue":{"type":"object","description":"The flow structure containing modules and optional preprocessor/failure handlers","properties":{"modules":{"type":"array","description":"Array of steps that execute in sequence. Each step can be a script, subflow, loop, or branch","items":{"$ref":"#/components/schemas/FlowModule"}},"failure_module":{"description":"Special module that executes when the flow fails. Receives error object with message, name, stack, and step_id. Must have id 'failure'. Only supports script/rawscript types","$ref":"#/components/schemas/FlowModule"},"preprocessor_module":{"description":"Special module that runs before the first step on external triggers. Must have id 'preprocessor'. Only supports script/rawscript types. Cannot reference other step results","$ref":"#/components/schemas/FlowModule"},"same_worker":{"type":"boolean","description":"If true, all steps run on the same worker for better performance"},"preserve_step_tags":{"type":"boolean","description":"If true and the flow runs on a custom worker tag, steps that declare their own non-empty tag run on it instead of inheriting the flow tag. Steps without their own tag still inherit the flow tag."},"concurrent_limit":{"type":"number","description":"Maximum number of concurrent executions of this flow"},"concurrency_key":{"type":"string","description":"Expression to group concurrent executions (e.g., by user ID)"},"concurrency_time_window_s":{"type":"number","description":"Time window in seconds for concurrent_limit"},"debounce_delay_s":{"type":"integer","description":"Delay in seconds to debounce flow executions"},"debounce_key":{"type":"string","description":"Expression to group debounced executions"},"debounce_args_to_accumulate":{"type":"array","description":"Arguments to accumulate across debounced executions","items":{"type":"string"}},"max_total_debouncing_time":{"type":"integer","description":"Maximum total time in seconds that a job can be debounced"},"max_total_debounces_amount":{"type":"integer","description":"Maximum number of times a job can be debounced"},"skip_expr":{"type":"string","description":"JavaScript expression to conditionally skip the entire flow"},"cache_ttl":{"type":"number","description":"Cache duration in seconds for flow results"},"cache_ignore_s3_path":{"type":"boolean"},"delete_after_secs":{"type":"integer","description":"If set, delete the flow job's args, result and logs after this many seconds following job completion"},"flow_env":{"type":"object","description":"Environment variables available to all steps. Values can be strings, JSON values, or special references: '$var:path' (workspace variable) or '$res:path' (resource).","additionalProperties":{}},"priority":{"type":"number","description":"Execution priority (higher numbers run first)"},"early_return":{"type":"string","description":"Id of the step whose result a sync webhook returns as soon as that step completes, while the rest of the flow keeps running. When the step does not run, or fails while the flow has a failure module, the flow's final result is returned instead."},"chat_input_enabled":{"type":"boolean","description":"Whether this flow accepts chat-style input"},"notes":{"type":"array","description":"Sticky notes attached to the flow","items":{"$ref":"#/components/schemas/FlowNote"}},"groups":{"type":"array","description":"Semantic groups of modules for organizational purposes","items":{"$ref":"#/components/schemas/FlowGroup"}}},"required":["modules"]},"Retry":{"type":"object","description":"Retry configuration for failed module executions","properties":{"constant":{"type":"object","description":"Retry with constant delay between attempts","properties":{"attempts":{"type":"integer","description":"Number of retry attempts"},"seconds":{"type":"integer","description":"Seconds to wait between retries"}}},"exponential":{"type":"object","description":"Retry with exponential backoff: the n-th retry waits multiplier \\u00d7 seconds^n","properties":{"attempts":{"type":"integer","description":"Number of retry attempts"},"multiplier":{"type":"integer","description":"Multiplier for exponential backoff"},"seconds":{"type":"integer","minimum":1,"description":"Base of the exponential (seconds); the n-th retry waits multiplier \\u00d7 seconds^n, where n counts constant retries too"},"random_factor":{"type":"integer","minimum":0,"maximum":100,"description":"Random jitter percentage (0-100) to avoid thundering herd"}}},"retry_if":{"$ref":"#/components/schemas/RetryIf"}}},"FlowNote":{"type":"object","description":"A sticky note attached to a flow for documentation and annotation","properties":{"id":{"type":"string","description":"Unique identifier for the note"},"text":{"type":"string","description":"Content of the note"},"position":{"type":"object","description":"Position of the note in the flow editor","properties":{"x":{"type":"number","description":"X coordinate"},"y":{"type":"number","description":"Y coordinate"}},"required":["x","y"]},"size":{"type":"object","description":"Size of the note in the flow editor","properties":{"width":{"type":"number","description":"Width in pixels"},"height":{"type":"number","description":"Height in pixels"}},"required":["width","height"]},"color":{"type":"string","description":"Color of the note, one of: yellow, blue, green, purple, pink, orange, red, cyan, lime, gray. Any other value renders unstyled."},"type":{"type":"string","enum":["free","group"],"description":"Type of note - 'free' for standalone notes. 'group' notes are deprecated; segment a flow with FlowValue.groups instead."},"locked":{"type":"boolean","default":false,"description":"Whether the note is locked and cannot be edited or moved"},"contained_node_ids":{"type":"array","items":{"type":"string"},"description":"For group notes, the IDs of nodes contained within this group"}},"required":["id","text","color","type"]},"FlowGroup":{"type":"object","description":"A semantic group of flow modules for organizational purposes. Does not affect execution \\u2014 modules remain in their original position in the flow. Groups provide naming and collapsibility in the editor. Members are computed dynamically from all nodes on paths between start_id and end_id.","properties":{"summary":{"type":"string","description":"Display name for this group"},"note":{"type":"string","description":"Markdown note shown below the group header"},"autocollapse":{"type":"boolean","default":false,"description":"If true, this group is collapsed by default in the flow editor. UI hint only."},"start_id":{"type":"string","description":"ID of the first flow module in this group (topological entry point)"},"end_id":{"type":"string","description":"ID of the last flow module in this group (topological exit point)"},"color":{"type":"string","description":"Color for the group in the flow editor, one of: yellow, blue, green, purple, pink, orange, red, cyan, lime, gray. Omit it to let the editor pick one."}},"required":["start_id","end_id"]},"RetryIf":{"type":"object","description":"Conditional retry based on error or result","properties":{"expr":{"type":"string","description":"JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables"}},"required":["expr"]},"StopAfterIf":{"type":"object","description":"Early termination condition for a module","properties":{"skip_if_stopped":{"type":"boolean","description":"If true, following steps are skipped when this condition triggers"},"expr":{"type":"string","description":"JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"},"error_message":{"type":"string","nullable":true,"description":"Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised."},"error_include_result":{"type":"boolean","description":"When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false."}},"required":["expr"]},"FlowModule":{"type":"object","description":"A single step in a flow. Can be a script, subflow, loop, or branch","properties":{"id":{"type":"string","description":"Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"},"value":{"$ref":"#/components/schemas/FlowModuleValue"},"stop_after_if":{"description":"Early termination condition evaluated after this step completes","$ref":"#/components/schemas/StopAfterIf"},"stop_after_all_iters_if":{"description":"For loops only - early termination condition evaluated after all iterations complete","$ref":"#/components/schemas/StopAfterIf"},"skip_if":{"type":"object","description":"Conditionally skip this step based on previous results or flow inputs","properties":{"expr":{"type":"string","description":"JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.<step_id>'"}},"required":["expr"]},"sleep":{"description":"Delay before executing this step (in seconds or as expression)","$ref":"#/components/schemas/InputTransform"},"cache_ttl":{"type":"number","description":"Cache duration in seconds for this step's results"},"cache_ignore_s3_path":{"type":"boolean"},"timeout":{"description":"Maximum execution time in seconds (static value or expression)","$ref":"#/components/schemas/InputTransform"},"delete_after_secs":{"type":"integer","description":"If set, delete the step's args, result and logs after this many seconds following job completion"},"summary":{"type":"string","description":"Short description of what this step does"},"mock":{"type":"object","description":"Mock configuration for testing without executing the actual step","properties":{"enabled":{"type":"boolean","description":"If true, return mock value instead of executing"},"return_value":{"description":"Value to return when mocked"}}},"suspend":{"type":"object","description":"Configuration for approval/resume steps that wait for user input","properties":{"required_events":{"type":"integer","description":"Number of approvals required before continuing"},"timeout":{"type":"integer","description":"Timeout in seconds before auto-continuing or canceling"},"resume_form":{"type":"object","description":"Form schema for collecting input when resuming","properties":{"schema":{"type":"object","description":"JSON Schema for the resume form"}}},"user_auth_required":{"type":"boolean","description":"If true, only authenticated users can approve"},"user_groups_required":{"description":"Expression or list of groups that can approve","$ref":"#/components/schemas/InputTransform"},"self_approval_disabled":{"type":"boolean","description":"If true, the user who started the flow cannot approve"},"hide_cancel":{"type":"boolean","description":"If true, hide the cancel button on the approval form"},"continue_on_disapprove_timeout":{"type":"boolean","description":"If true, continue flow on timeout instead of canceling"},"skin":{"type":"string","enum":["detailed","minimal"],"description":"How the approval request is presented, on the approval page and in Slack/Teams approval messages. 'detailed' (used when unset) shows the flow details (arguments, graph, approvers); 'minimal' shows only the request: the step description, form and approve/reject actions"}}},"priority":{"type":"number","description":"Execution priority for this step (higher numbers run first)"},"continue_on_error":{"type":"boolean","description":"If true, flow continues even if this step fails"},"job_token_scopes":{"type":"array","nullable":true,"items":{"type":"string"},"description":"Scopes the token of this step's jobs is restricted to (domain:action[:resource], e.g. oidc:write), on top of the flow's own restriction: a step can only narrow it. Applies to everything the step runs (loop and branch bodies, AI agent tools)."},"retry":{"description":"Retry configuration if this step fails","$ref":"#/components/schemas/Retry"},"debouncing":{"description":"Debounce configuration for this step (EE only)","type":"object","properties":{"debounce_delay_s":{"type":"integer","description":"Delay in seconds to debounce this step's executions across flow runs"},"debounce_key":{"type":"string","description":"Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/<flow_path>-<step_id>"},"debounce_args_to_accumulate":{"type":"array","description":"Array-type arguments to accumulate across debounced executions","items":{"type":"string"}},"max_total_debouncing_time":{"type":"integer","description":"Maximum total time in seconds before forced execution"},"max_total_debounces_amount":{"type":"integer","description":"Maximum number of debounces before forced execution"}}}},"required":["value","id"]},"InputTransform":{"description":"Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs","oneOf":[{"$ref":"#/components/schemas/StaticTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type","mapping":{"static":"#/components/schemas/StaticTransform","javascript":"#/components/schemas/JavascriptTransform","ai":"#/components/schemas/AiTransform"}}},"StaticTransform":{"type":"object","description":"Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'","properties":{"value":{"description":"The static value. For resources, use format '$res:path/to/resource'"},"type":{"type":"string","enum":["static"]}},"required":["type"]},"JavascriptTransform":{"type":"object","description":"JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')","properties":{"expr":{"type":"string","description":"JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"},"type":{"type":"string","enum":["javascript"]}},"required":["expr","type"]},"AiTransform":{"type":"object","description":"Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.","properties":{"type":{"type":"string","enum":["ai"]}},"required":["type"]},"AIProviderKind":{"type":"string","description":"Supported AI provider types","enum":["openai","azure_openai","azure_foundry","anthropic","mistral","deepseek","googleai","groq","openrouter","togetherai","customai","aws_bedrock","typesafe","cloudflare"]},"ProviderConfig":{"type":"object","description":"Complete AI provider configuration with resource reference and model selection","properties":{"kind":{"$ref":"#/components/schemas/AIProviderKind"},"resource":{"type":"string","description":"Resource reference in format '$res:{resource_path}' pointing to provider credentials"},"model":{"type":"string","description":"Model identifier (e.g., 'gpt-4', 'claude-3-opus-20240229', 'gemini-pro')"},"reasoning_effort":{"type":"string","description":"Provider-native reasoning effort token (e.g. 'low', 'high', 'none') for models that support extended thinking. Optional; unset leaves the provider default."}},"required":["kind","resource","model"]},"StaticProviderTransform":{"type":"object","description":"Static provider configuration passed directly to the AI agent","properties":{"value":{"$ref":"#/components/schemas/ProviderConfig"},"type":{"type":"string","enum":["static"]}},"required":["type","value"]},"ProviderTransform":{"description":"Provider configuration - can be static (ProviderConfig), JavaScript expression, or AI-determined","oneOf":[{"$ref":"#/components/schemas/StaticProviderTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type","mapping":{"static":"#/components/schemas/StaticProviderTransform","javascript":"#/components/schemas/JavascriptTransform","ai":"#/components/schemas/AiTransform"}}},"MemoryOff":{"type":"object","description":"No conversation memory/context","properties":{"kind":{"type":"string","enum":["off"]}},"required":["kind"]},"MemoryWindow":{"type":"object","description":"Keeps the most recent messages of the memory named by the run's memory id (or the step's\\n\`memory_id\`). Without a memory id the agent runs without memory.\\n","properties":{"kind":{"type":"string","enum":["window"]},"context_length":{"type":"integer","description":"Number of most recent messages to load and store. 0 turns memory off."}},"required":["kind","context_length"]},"MemoryAuto":{"type":"object","deprecated":true,"description":"Deprecated, still read as it was written: the run's memory id, else the \`memory_id\` here.\\nThe step's own \`memory_id\` is not read while this kind is set; switch the kind to \`window\`\\nto use it. Without a \`context_length\`, or with 0, it is \`off\` and reads \`previous_messages\`.\\n","properties":{"kind":{"type":"string","enum":["auto"]},"context_length":{"type":"integer","description":"Maximum number of messages to retain in context"},"memory_id":{"type":"string","description":"Identifier for persistent memory across agent invocations"}},"required":["kind"]},"MemoryCompaction":{"type":"object","description":"Keeps the whole memory named by the run's memory id (or the step's \`memory_id\`), replacing\\nits older part with a summary as the conversation approaches the model's context window.\\nWithout a memory id the agent runs without memory, and compaction bounds the run's own loop.\\n","properties":{"kind":{"type":"string","enum":["compaction"]},"context_window":{"type":"integer","description":"Overrides the context window looked up from the model, in tokens. Only a model\\nWindmill does not know needs one; those fall back to 128000.\\n"}},"required":["kind"]},"MemoryMessage":{"type":"object","description":"A single message in conversation history","properties":{"role":{"type":"string","enum":["user","assistant","system"]},"content":{"type":"string"}},"required":["role","content"]},"MemoryManual":{"type":"object","deprecated":true,"description":"Deprecated, still read as it was written. Move the step to \`off\` with \`previous_messages\` instead.","properties":{"kind":{"type":"string","enum":["manual"]},"messages":{"type":"array","items":{"$ref":"#/components/schemas/MemoryMessage"}}},"required":["kind","messages"]},"MemoryConfig":{"description":"Managed memory, stored by Windmill and replayed with each request. The memory is named by a memory id, see \`memory_id\`. While it is off, a step can supply its history in \`previous_messages\`.","oneOf":[{"$ref":"#/components/schemas/MemoryOff"},{"$ref":"#/components/schemas/MemoryWindow"},{"$ref":"#/components/schemas/MemoryCompaction"},{"$ref":"#/components/schemas/MemoryAuto"},{"$ref":"#/components/schemas/MemoryManual"}],"discriminator":{"propertyName":"kind","mapping":{"off":"#/components/schemas/MemoryOff","window":"#/components/schemas/MemoryWindow","compaction":"#/components/schemas/MemoryCompaction","auto":"#/components/schemas/MemoryAuto","manual":"#/components/schemas/MemoryManual"}}},"StaticMemoryTransform":{"type":"object","description":"Static memory configuration passed directly to the AI agent","properties":{"value":{"$ref":"#/components/schemas/MemoryConfig"},"type":{"type":"string","enum":["static"]}},"required":["type","value"]},"MemoryTransform":{"description":"Memory configuration - can be static (MemoryConfig), JavaScript expression, or AI-determined","oneOf":[{"$ref":"#/components/schemas/StaticMemoryTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type","mapping":{"static":"#/components/schemas/StaticMemoryTransform","javascript":"#/components/schemas/JavascriptTransform","ai":"#/components/schemas/AiTransform"}}},"FlowModuleValue":{"description":"The actual implementation of a flow step. Can be a script (inline or referenced), subflow, loop, branch, or special module type","oneOf":[{"$ref":"#/components/schemas/RawScript"},{"$ref":"#/components/schemas/PathScript"},{"$ref":"#/components/schemas/PathFlow"},{"$ref":"#/components/schemas/ForloopFlow"},{"$ref":"#/components/schemas/WhileloopFlow"},{"$ref":"#/components/schemas/BranchOne"},{"$ref":"#/components/schemas/BranchAll"},{"$ref":"#/components/schemas/Identity"},{"$ref":"#/components/schemas/AiAgent"},{"$ref":"#/components/schemas/AiDecision"}],"discriminator":{"propertyName":"type","mapping":{"rawscript":"#/components/schemas/RawScript","script":"#/components/schemas/PathScript","flow":"#/components/schemas/PathFlow","forloopflow":"#/components/schemas/ForloopFlow","whileloopflow":"#/components/schemas/WhileloopFlow","branchone":"#/components/schemas/BranchOne","branchall":"#/components/schemas/BranchAll","identity":"#/components/schemas/Identity","aiagent":"#/components/schemas/AiAgent","aidecision":"#/components/schemas/AiDecision"}}},"RawScript":{"type":"object","description":"Inline script with code defined directly in the flow. Use 'bun' as default language if unspecified. The script receives arguments from input_transforms","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"content":{"type":"string","description":"The script source code. Should export a 'main' function"},"language":{"type":"string","description":"Programming language for this script","enum":["deno","bun","bunnative","python3","go","bash","powershell","postgresql","mysql","bigquery","snowflake","mssql","oracledb","graphql","nativets","php","rust","ansible","csharp","nu","java","ruby","rlang","duckdb"]},"path":{"type":"string","description":"Optional path for saving this script"},"lock":{"type":"string","description":"Lock file content for dependencies"},"type":{"type":"string","enum":["rawscript"]},"tag":{"type":"string","description":"Worker group tag for execution routing"},"concurrent_limit":{"type":"number","description":"Maximum concurrent executions of this script"},"concurrency_time_window_s":{"type":"number","description":"Time window for concurrent_limit"},"custom_concurrency_key":{"type":"string","description":"Custom key for grouping concurrent executions"},"is_trigger":{"type":"boolean","description":"If true, this script is a trigger that can start the flow"},"assets":{"type":"array","description":"External resources this script accesses (S3 objects, resources, etc.)","items":{"type":"object","required":["path","kind"],"properties":{"path":{"type":"string","description":"Path to the asset"},"kind":{"type":"string","description":"Type of asset","enum":["s3object","resource","ducklake","datatable","volume","dbt"]},"access_type":{"type":"string","nullable":true,"description":"Access level for this asset","enum":["r","w","rw"]},"alt_access_type":{"type":"string","nullable":true,"description":"Alternative access level","enum":["r","w","rw"]}}}}},"required":["type","content","language","input_transforms"]},"PathScript":{"type":"object","description":"Reference to an existing script by path. Use this when calling a previously saved script instead of writing inline code","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"path":{"type":"string","description":"Path to the script in the workspace (e.g., 'f/scripts/send_email')"},"hash":{"type":"string","description":"Optional specific version hash of the script to use"},"type":{"type":"string","enum":["script"]},"tag_override":{"type":"string","description":"Override the script's default worker group tag"},"is_trigger":{"type":"boolean","description":"If true, this script is a trigger that can start the flow"}},"required":["type","path","input_transforms"]},"PathFlow":{"type":"object","description":"Reference to an existing flow by path. Use this to call another flow as a subflow","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the subflow's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"path":{"type":"string","description":"Path to the flow in the workspace (e.g., 'f/flows/process_user')"},"type":{"type":"string","enum":["flow"]}},"required":["type","path","input_transforms"]},"ForloopFlow":{"type":"object","description":"Executes nested modules in a loop over an iterator. Inside the loop, use 'flow_input.iter.value' to access the current iteration value, and 'flow_input.iter.index' for the index. Supports parallel execution for better performance on I/O-bound operations","properties":{"modules":{"type":"array","description":"Steps to execute for each iteration. These can reference the iteration value via 'flow_input.iter.value'","items":{"$ref":"#/components/schemas/FlowModule"}},"iterator":{"description":"JavaScript expression that returns an array to iterate over. Can reference 'results.step_id' or 'flow_input'","$ref":"#/components/schemas/InputTransform"},"skip_failures":{"type":"boolean","description":"If true, iteration failures don't stop the loop. Failed iterations return null"},"type":{"type":"string","enum":["forloopflow"]},"parallel":{"type":"boolean","description":"If true, iterations run concurrently (faster for I/O-bound operations). Use with parallelism to control concurrency"},"parallelism":{"description":"Maximum number of concurrent iterations when parallel=true. Limits resource usage. Can be static number or expression","$ref":"#/components/schemas/InputTransform"},"squash":{"type":"boolean"}},"required":["modules","iterator","skip_failures","type"]},"WhileloopFlow":{"type":"object","description":"Executes nested modules repeatedly until stopped. The implicit iterator is the iteration counter, so 'flow_input.iter.value' equals 'flow_input.iter.index' (0, 1, 2, ...) and never carries state. To carry state across iterations, a step reads its own previous-iteration result via 'results.<its_own_id>' with a first-iteration fallback - the loop's stop_after_if must then be on that inner step (a plain single-step body with stop_after_if on the loop module does not resolve 'results' across iterations and never terminates); plain counters can instead be derived from 'flow_input.iter.index', which works in every configuration. stop_after_if is evaluated after each iteration - on the loop module 'result' is the last iteration's result","properties":{"modules":{"type":"array","description":"Steps to execute in each iteration","items":{"$ref":"#/components/schemas/FlowModule"}},"skip_failures":{"type":"boolean","description":"If true, iteration failures don't stop the loop. Failed iterations return null"},"type":{"type":"string","enum":["whileloopflow"]},"parallel":{"type":"boolean","description":"If true, iterations run concurrently (use with caution in while loops)"},"parallelism":{"description":"Maximum number of concurrent iterations when parallel=true","$ref":"#/components/schemas/InputTransform"},"squash":{"type":"boolean"}},"required":["modules","skip_failures","type"]},"BranchOne":{"type":"object","description":"Conditional branching where only the first matching branch executes. Branches are evaluated in order, and the first one with a true expression runs. If no branches match, the default branch executes","properties":{"branches":{"type":"array","description":"Array of branches to evaluate in order. The first branch with expr evaluating to true executes","items":{"type":"object","properties":{"summary":{"type":"string","description":"Short description of this branch condition"},"expr":{"type":"string","description":"JavaScript expression that returns boolean. Can use 'results.step_id' or 'flow_input'. First true expr wins"},"modules":{"type":"array","description":"Steps to execute if this branch's expr is true","items":{"$ref":"#/components/schemas/FlowModule"}}},"required":["modules","expr"]}},"default":{"type":"array","description":"Steps to execute if no branch expressions match","items":{"$ref":"#/components/schemas/FlowModule"}},"type":{"type":"string","enum":["branchone"]}},"required":["branches","default","type"]},"BranchAll":{"type":"object","description":"Parallel branching where all branches execute simultaneously. Unlike BranchOne, all branches run regardless of conditions. Useful for executing independent tasks concurrently","properties":{"branches":{"type":"array","description":"Array of branches that all execute (either in parallel or sequentially)","items":{"type":"object","properties":{"summary":{"type":"string","description":"Short description of this branch's purpose"},"skip_failure":{"type":"boolean","description":"If true, failure in this branch doesn't fail the entire flow"},"modules":{"type":"array","description":"Steps to execute in this branch","items":{"$ref":"#/components/schemas/FlowModule"}}},"required":["modules"]}},"type":{"type":"string","enum":["branchall"]},"parallel":{"type":"boolean","description":"If true, all branches execute concurrently. If false, they execute sequentially"}},"required":["branches","type"]},"AgentTool":{"type":"object","description":"A tool available to an AI agent. Can be a flow module or an external MCP (Model Context Protocol) tool","properties":{"id":{"type":"string","description":"Unique identifier for this tool. Cannot contain spaces - use underscores instead (e.g., 'get_user_data' not 'get user data')"},"summary":{"type":"string","description":"The name the AI agent calls this tool by, not a human label. On a flowmodule tool it must match ^[a-zA-Z0-9_]+$ - letters, numbers and underscores only (e.g. 'search_documentation', not 'Search documentation') - and always be set; on an mcp or websearch tool it is a plain label. Put the human-readable explanation in 'description'."},"description":{"type":"string","description":"Free-text description of the tool given to the AI to decide when and how to call it. Overrides the description auto-derived from the underlying script."},"job_token_scopes":{"type":"array","nullable":true,"items":{"type":"string"},"description":"Scopes the token of this tool's jobs is restricted to, on top of the agent step's own restriction: a tool can only narrow it."},"value":{"$ref":"#/components/schemas/ToolValue"}},"required":["id","value"]},"ToolValue":{"description":"The implementation of a tool. Can be a flow module (script/flow) or an MCP tool reference","oneOf":[{"$ref":"#/components/schemas/FlowModuleTool"},{"$ref":"#/components/schemas/McpToolValue"},{"$ref":"#/components/schemas/WebsearchToolValue"}],"discriminator":{"propertyName":"tool_type","mapping":{"flowmodule":"#/components/schemas/FlowModuleTool","mcp":"#/components/schemas/McpToolValue","websearch":"#/components/schemas/WebsearchToolValue"}}},"FlowModuleTool":{"description":"A tool implemented as a flow module (script, flow, etc.). The AI can call this like any other flow module","allOf":[{"type":"object","properties":{"tool_type":{"type":"string","enum":["flowmodule"]}},"required":["tool_type"]},{"$ref":"#/components/schemas/FlowModuleValue"}]},"WebsearchToolValue":{"type":"object","description":"A tool implemented as a websearch tool. The AI can call this like any other websearch tool","properties":{"tool_type":{"type":"string","enum":["websearch"]}},"required":["tool_type"]},"McpToolValue":{"type":"object","description":"Reference to an external MCP (Model Context Protocol) tool. The AI can call tools from MCP servers","properties":{"tool_type":{"type":"string","enum":["mcp"]},"resource_path":{"type":"string","description":"Path to the MCP resource/server configuration"},"include_tools":{"type":"array","description":"Whitelist of specific tools to include from this MCP server","items":{"type":"string"}},"exclude_tools":{"type":"array","description":"Blacklist of tools to exclude from this MCP server","items":{"type":"string"}}},"required":["tool_type","resource_path"]},"AiAgent":{"type":"object","description":"AI agent step that can use tools to accomplish tasks. The agent receives inputs and can call any of its configured tools to complete the task","properties":{"input_transforms":{"type":"object","description":"Input parameters for the AI agent mapped to their values","properties":{"provider":{"$ref":"#/components/schemas/ProviderTransform"},"output_type":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Output format type.\\nValid values: 'text' (default) - plain text response, 'image' - image generation\\n"},"user_message":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"The user's prompt/message to the AI agent. Supports variable interpolation with\\nflow.input syntax. Required unless memory is off and \`previous_messages\` supplies\\nthe prompt; image output always needs it.\\n"},"system_prompt":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"System instructions that guide the AI's behavior, persona, and response style. Optional."},"streaming":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Boolean. If true, stream the AI response incrementally.\\nStreaming events include: token_delta, reasoning_token_delta, tool_call, tool_call_arguments, tool_execution, tool_result\\n"},"memory":{"$ref":"#/components/schemas/MemoryTransform"},"memory_id":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"String. Names the memory this step reads and writes, overriding the memory id the run\\nwas started with (the chat conversation, an app chat session or the \`memory_id\` run\\nparameter). Leave unset to use the run's memory id. A fixed value shares one memory\\nacross every run; an expression such as \`flow_input.customer_id\` keeps one memory per\\nkey. When it evaluates to an empty value the agent runs without memory. Read only\\nwhile \`memory\` is \`window\` or \`compaction\`: it is ignored when memory is off, and an\\nolder \`auto\` or \`manual\` memory reads neither history input.\\n"},"previous_messages":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Array of MemoryMessage. History supplied by the flow, sent between the system prompt\\nand the user message. Read only while \`memory\` is off or absent: managed memory\\nignores it, and an older \`auto\` or \`manual\` memory reads neither history input.\\n"},"output_schema":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"JSON Schema object defining structured output format. Used when you need the AI to return data in a specific shape.\\nSupports standard JSON Schema properties: type, properties, required, items, enum, pattern, minLength, maxLength, minimum, maximum, etc.\\nExample: { type: 'object', properties: { name: { type: 'string' }, age: { type: 'integer' } }, required: ['name'] }\\n"},"user_attachments":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Array of file references (images or PDFs) for the AI agent.\\nFormat: Array<{ bucket: string, key: string }> - S3 object references\\nExample: [{ bucket: 'my-bucket', key: 'documents/report.pdf' }]\\n"},"enabled_tools":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Array of strings naming which of the tools configured in \`tools\` the agent may call\\nthis run. Leaving it unset carries every one of them; an empty array carries none.\\nA tool is named as the model is shown it. An entry the model is shown nothing of is\\nnamed by what identifies it instead: an MCP server by its resource path, carrying\\nevery tool it exposes (which of them stays that entry's include_tools/exclude_tools),\\nand a websearch entry by the reserved name '__wm_web_search', whatever summary it carries\\n(no tool may take that name).\\nExample: ['get_user', 'u/admin/github_mcp', '__wm_web_search']\\n"},"max_completion_tokens":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Integer. Maximum number of tokens the AI will generate in its response.\\nRange: 1 to 4,294,967,295. Typical values: 256-4096 for most use cases.\\n"},"temperature":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Float. Controls randomness/creativity of responses.\\nRange: 0.0 to 2.0 (provider-dependent)\\n- 0.0 = deterministic, focused responses\\n- 0.7 = balanced (common default)\\n- 1.0+ = more creative/random\\n"},"max_iterations":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Number. Limits how many times the agent can loop through reasoning and tool use.\\nRange: 1-1000.\\n"},"model":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"String. Only on a step linked to a saved agent (see \`agent\`): replaces the model\\nsaved on the agent for this step's runs, on the agent's own provider resource. An\\nempty value keeps the saved model. Set it to an expression such as\\n\`flow_input.model\` to choose the model per run.\\n"},"reasoning_effort":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"String. Only on a step linked to a saved agent (see \`agent\`): replaces the reasoning\\neffort saved on the agent for this step's runs, as a provider-native token (e.g.\\n'low', 'high', 'none'). An empty value sends no effort, so the model runs at its\\ndefault. Leave the input out to keep the saved effort, which holds only while the\\nstep runs the saved model. A step that is not linked sets both inside \`provider\`.\\n"}}},"tools":{"type":"array","description":"Array of tools the agent can use. The agent decides which tools to call based on the task","items":{"$ref":"#/components/schemas/AgentTool"}},"type":{"type":"string","enum":["aiagent"]},"tag":{"type":"string","description":"Worker group tag for execution routing. If not set, the AI agent step runs on the flow's tag (default \`flow\`)"},"omit_output_from_conversation":{"type":"boolean","default":false,"description":"If true, this AI agent step does not persist its assistant or tool messages to the flow conversation when chat mode is enabled."},"agent":{"type":"string","description":"Path of a reusable \`ai_agent\` resource (hybrid linking). When set, the agent brain\\nconfig (provider/model/system prompt/etc.) and tool set are resolved at runtime from\\nthat resource; the module's input_transforms then only carry the flow-local inputs\\n(user_message, user_attachments, enabled_tools and the history inputs memory_id and previous_messages)\\nand, optionally, the \`model\` and \`reasoning_effort\` overrides of what the agent saved.\\n"},"tool_inputs":{"type":"object","description":"Host-local wiring for an agent's tool inputs, keyed by tool id then input key. Binds the\\nreferenced agent's tools to this flow's context (flow_input/results) without mutating the\\nshared resource; overlaid onto the tools' input_transforms at runtime \\u2014 including when\\n\`agent\` is unset, since a step forked for editing keeps these overrides until it is saved\\nback or unlinked.\\n","additionalProperties":{"type":"object","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}}},"parallel":{"type":"boolean","description":"If true, the agent can execute multiple tool calls in parallel"}},"required":["type","input_transforms"]},"AiDecision":{"type":"object","description":"AI decision step: one call to a decision model (TypeSafe's Jev, Cloudflare's\\nJev-compatible Clef, or OpenAI's Decisions API) that answers typed questions about a\\nstate with calibrated probabilities, instead of generating text.\\nPrefer it over an AI agent to classify, route, score or check something: it is fast,\\ncheap and its answers are structured. Its result is { output: { <question name>: answer },\\nmodel, usage }, so a later step reads e.g. results.<id>.output.intent.choice. To route on\\nthe answers, follow it with a branchone whose branch exprs read\\nresults.<id>.output.<question>.choice. Usable as an AI agent tool, where the calling agent\\nsupplies the state.\\n","properties":{"input_transforms":{"type":"object","description":"Input parameters for the decision mapped to their values","properties":{"provider":{"$ref":"#/components/schemas/ProviderTransform"},"state":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"What the questions are asked about: a string, an object or an array of strings.\\nAn object with descriptive keys holding only what the questions need works best.\\nExample: { message: flow_input.message, plan: results.a.plan }\\n"},"questions":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Object mapping each question name to { type, instructions, criteria }, where type is:\\n- 'choice': criteria maps each option to its description (up to 255); the answer\\n has choice, probabilities and confidence\\n- 'score': criteria is an ordered array of 2 to 10 level descriptions; the answer\\n has score, legend, probabilities and confidence\\n- 'noul': yes/no, criteria optionally { true, false } descriptions; the answer has\\n noul, the probability of yes (0 to 1)\\nExample: { intent: { type: 'choice', instructions: 'What does the customer want?',\\ncriteria: { refund: 'Money back', bug: 'Something is broken' } } }\\n"}},"required":["provider","state","questions"]},"type":{"type":"string","enum":["aidecision"]},"tag":{"type":"string","description":"Worker group tag for execution routing. If not set, the step runs on the flow's tag (default \`flow\`)"}},"required":["type","input_transforms"]},"Identity":{"type":"object","description":"Pass-through module that returns its input unchanged. Useful for flow structure or as a placeholder","properties":{"type":{"type":"string","enum":["identity"]},"flow":{"type":"boolean","description":"If true, marks this as a flow identity (special handling)"}},"required":["type"]},"FlowStatus":{"type":"object","properties":{"step":{"type":"integer"},"modules":{"type":"array","items":{"$ref":"#/components/schemas/FlowStatusModule"}},"user_states":{"additionalProperties":true},"preprocessor_module":{"allOf":[{"$ref":"#/components/schemas/FlowStatusModule"}]},"failure_module":{"allOf":[{"$ref":"#/components/schemas/FlowStatusModule"},{"type":"object","properties":{"parent_module":{"type":"string"}}}]},"retry":{"type":"object","properties":{"fail_count":{"type":"integer"},"failed_jobs":{"type":"array","items":{"type":"string","format":"uuid"}}}}},"required":["step","modules","failure_module"]},"FlowStatusModule":{"type":"object","properties":{"type":{"type":"string","enum":["WaitingForPriorSteps","WaitingForEvents","WaitingForExecutor","InProgress","Success","Failure"]},"id":{"type":"string"},"job":{"type":"string","format":"uuid"},"count":{"type":"integer"},"progress":{"type":"integer"},"iterator":{"type":"object","properties":{"index":{"type":"integer"},"itered":{"type":"array","items":{}},"itered_len":{"type":"integer"},"args":{}}},"flow_jobs":{"type":"array","items":{"type":"string"}},"flow_jobs_success":{"type":"array","items":{"type":"boolean"}},"flow_jobs_duration":{"type":"object","properties":{"started_at":{"type":"array","items":{"type":"string"}},"duration_ms":{"type":"array","items":{"type":"integer"}}}},"branch_chosen":{"type":"object","properties":{"type":{"type":"string","enum":["branch","default"]},"branch":{"type":"integer"}},"required":["type"]},"branchall":{"type":"object","properties":{"branch":{"type":"integer"},"len":{"type":"integer"}},"required":["branch","len"]},"approvers":{"type":"array","items":{"type":"object","properties":{"resume_id":{"type":"integer"},"approver":{"type":"string"}},"required":["resume_id","approver"]}},"failed_retries":{"type":"array","items":{"type":"string","format":"uuid"}},"skipped":{"type":"boolean"},"agent_actions":{"type":"array","items":{"type":"object","oneOf":[{"type":"object","properties":{"job_id":{"type":"string","format":"uuid"},"function_name":{"type":"string"},"type":{"type":"string","enum":["tool_call"]},"module_id":{"type":"string"}},"required":["job_id","function_name","type","module_id"]},{"type":"object","properties":{"call_id":{"type":"string","format":"uuid"},"function_name":{"type":"string"},"resource_path":{"type":"string"},"type":{"type":"string","enum":["mcp_tool_call"]},"arguments":{"type":"object"}},"required":["call_id","function_name","resource_path","type"]},{"type":"object","properties":{"type":{"type":"string","enum":["web_search"]}},"required":["type"]},{"type":"object","properties":{"type":{"type":"string","enum":["message"]}},"required":["content","type"]}]}},"agent_actions_success":{"type":"array","items":{"type":"boolean"}}},"required":["type"]}}`; export const CLI_COMMANDS = `# Windmill CLI Commands @@ -3519,7 +3763,7 @@ app related commands - \`app dev [app_folder:string]\` - Start a development server for building apps with live reload and hot module replacement - \`--port <port:number>\` - Port to run the dev server on (will find next available port if occupied) - \`--host <host:string>\` - Host to bind the dev server to - - \`--entry <entry:string>\` - Entry point file (default: index.ts for Svelte/Vue, index.tsx otherwise) + - \`--entry <entry:string>\` - Entry point file (default: index.ts for Svelte, index.tsx otherwise) - \`--no-open\` - Don't automatically open the browser - \`--recording\` - Frame the app in a shell with a Record button, to capture a replayable session recording of the app under development - \`app lint [app_folder:string]\` - Lint a raw app folder to validate structure and buildability @@ -3530,7 +3774,7 @@ app related commands - \`app new\` - create a new raw app from a template - \`--summary <summary:string>\` - App summary (short description). Skips the prompt when provided. Triggers non-interactive mode. - \`--path <path:string>\` - App path (e.g., f/folder/my_app or u/username/my_app). Skips the prompt when provided. Triggers non-interactive mode. - - \`--framework <framework:string>\` - Framework template: react19 | react18 | svelte5 | vue. Skips the prompt when provided. Triggers non-interactive mode. + - \`--framework <framework:string>\` - Framework template: react19 | react18 | svelte5. Skips the prompt when provided. Triggers non-interactive mode. - \`--datatable <datatable:string>\` - Datatable to wire up. Without this flag in non-interactive mode, no datatable is configured. - \`--schema <schema:string>\` - Schema to use with --datatable. If it doesn't exist yet, a sql_to_apply/ migration (CREATE SCHEMA IF NOT EXISTS) is written for it. - \`--overwrite\` - Overwrite the target directory if it already exists, without prompting. @@ -3573,8 +3817,10 @@ datatable related commands - \`datatable migrate\` - manage datatable migrations - \`datatable migrate new <name:string>\` - scaffold a new migration (.up.sql / .down.sql files) - \`-d --datatable <datatable:string>\` - Target datatable (default: main) + - \`-s --schemas <schemas:string>\` - Comma-separated schemas the migration changes, written as its \`-- schemas\` line. Without it the migration applies to the whole database and every later migration waits for it - \`datatable migrate up\` - apply all pending migrations to the main datatable (or one via --datatable) - \`-d --datatable <datatable:string>\` - Target datatable (default: main) + - \`--schema <schema:string>\` - Apply only the pending migrations that declare this schema; refused while an earlier overlapping migration is pending - \`datatable migrate down\` - roll back the most recent migration on the main datatable (or one via --datatable) - \`-d --datatable <datatable:string>\` - Target datatable (default: main) - \`datatable migrate status\` - show applied and pending migrations on the main datatable (or one via --datatable) @@ -3670,6 +3916,7 @@ flow related commands - \`--remote\` - Use deployed workspace scripts for PathScript steps instead of local files. - \`--step <step_id:string>\` - Run only the named step instead of the whole flow. Honors --data as the step's args and --remote / local-PathScript resolution the same way the full-flow preview does. - \`--tag <tag:string>\` - Override the worker tag the preview is dispatched to (e.g. to route it to dev workers instead of the flow's default tag). + - \`--on-behalf-of <identity:string>\` - Run the preview as this user or group (an email, u/<username> or g/<group>) instead of yourself, e.g. to reproduce a run_on_behalf_of identity. Requires being an admin or a member of wm_deployers. - \`flow new <flow_path:string>\` - create a new empty flow - \`--summary <summary:string>\` - flow summary - \`--description <description:string>\` - flow description @@ -4068,6 +4315,7 @@ script related commands - \`-d --data <data:file>\` - Inputs specified as a JSON string or a file using @<filename> or stdin using @-. A resource argument is the bare string $res:<path> as its whole value, and a variable argument is the bare string $var:<path> — not an object wrapper keyed on $res/$var, and not a plain path. - \`-s --silent\` - Do not output anything other than the final output. Useful for scripting. - \`--tag <tag:string>\` - Override the worker tag the preview is dispatched to (e.g. to route it to dev workers instead of the script's default tag). + - \`--on-behalf-of <identity:string>\` - Run the preview as this user or group (an email, u/<username> or g/<group>) instead of yourself, e.g. to reproduce a run_on_behalf_of identity. Requires being an admin or a member of wm_deployers. - \`script new <path:file> <language:string>\` - create a new script - \`--summary <summary:string>\` - script summary - \`--description <description:string>\` - script description @@ -4105,6 +4353,7 @@ sync local with a remote workspaces or the opposite (push or pull) - \`--include-users\` - Include syncing users - \`--include-groups\` - Include syncing groups - \`--include-settings\` - Include syncing workspace settings + - \`--include-datatable-permissions\` - With --include-settings, also sync who may connect to each data table as which role - \`--include-key\` - Include workspace encryption key - \`--keep-deleted\` - Do not delete local files for items that no longer exist on the remote workspace. Only adds and updates. - \`--skip-branch-validation\` - Skip git branch validation and prompts @@ -4136,6 +4385,7 @@ sync local with a remote workspaces or the opposite (push or pull) - \`--include-users\` - Include syncing users - \`--include-groups\` - Include syncing groups - \`--include-settings\` - Include syncing workspace settings + - \`--include-datatable-permissions\` - With --include-settings, also sync who may connect to each data table as which role - \`--include-key\` - Include workspace encryption key - \`--skip-reencrypt-on-key-change\` - When the pushed encryption key differs from the remote, do NOT re-encrypt existing remote secrets. Only safe if they are already encrypted with the new key (e.g. workspace/instance migration). Default is to re-encrypt. - \`--keep-deleted\` - Do not delete remote items that no longer exist locally. Only adds and updates. @@ -4329,6 +4579,13 @@ Arguments (omit both to be prompted interactively): - \`--team-id <team_id:string>\` - Slack team id - \`--team-name <team_name:string>\` - Slack team name - \`workspace disconnect-slack\` - Clear slack_team_id / slack_name on the active workspace (marks the workspace as disconnected). Does NOT remove the bot token variable/resource/folder/group — delete those from the local sync folder and run 'wmill sync push' to tear them down. Does NOT remove the workspace-level OAuth override — set slack_oauth_client_id/_secret to '' in settings.yaml and push. +- \`workspace get-settings\` - Print the active workspace's settings in the layout of the settings.yaml that 'wmill sync' writes. Secrets show as __SENSITIVE_AND_UNCHANGED__ unless --encrypted. Admin only. + - \`--encrypted\` - Write secrets encrypted with the workspace key, as 'wmill sync pull' does + - \`--json\` - Output as JSON +- \`workspace apply-settings <file:string>\` - Apply a settings document (YAML or JSON, in the layout of settings.yaml) to the active workspace. Only the settings the file states are changed, unless --replace; a setting set to null is cleared. A secret left as __SENSITIVE_AND_UNCHANGED__ keeps its value. Shows the changes and asks before applying. Admin only. + - \`--dry-run\` - Only show the changes + - \`--replace\` - Also clear the settings the file omits, as 'wmill sync push' does + - \`-y --yes\` - Apply without asking @@ -4706,7 +4963,7 @@ export async function main(url: string) { ## Pure computation: \`//no_network\` -A native script that only transforms its inputs can declare \`//no_network\` in its leading comment block (right after \`//native\`). The runtime then refuses every connection the script attempts: \`fetch\` to any host, the Windmill API (so \`windmill-client\` calls fail too), raw sockets and unix sockets, and \`WM_TOKEN\` is not set. It only takes effect on native scripts: without \`//native\` it is ignored. Use it only when the script needs no external data beyond its arguments: +A native script that only transforms its inputs can declare \`//no_network\` in its leading comment block (right after \`//native\`). The runtime then refuses every connection the script attempts: \`fetch\` to any host, the Windmill API (so \`windmill-client\` calls fail too), raw sockets and unix sockets, and \`WM_TOKEN\` is not set. Without \`//native\` it means something else: the script must run in an nsjail sandbox (\`//sandbox\`, or instance-wide sandboxing), which then loses its network, and it fails to run otherwise. Use it only when the script needs no external data beyond its arguments: \`\`\`typescript //native @@ -5738,6 +5995,27 @@ Name the parameters by adding comments before the statement: SELECT * FROM users WHERE name = ? AND age > ?; \`\`\` +## Array parameters + +Declare a list with a \`[]\` suffix on the element type (\`(varchar[])\`, +\`(int[])\`), or \`(array)\` for an untyped one. Snowflake cannot bind an array +directly, so Windmill binds the list as JSON text: wrap the placeholder with +\`PARSE_JSON(?)\`, and cast to \`ARRAY\` where a function expects one. + +\`\`\`sql +-- ? groups (varchar[]) +SELECT o.* FROM orders o +WHERE ARRAY_CONTAINS(o.owner_group::VARIANT, PARSE_JSON(?)::ARRAY); +\`\`\` + +Or join on the elements with \`FLATTEN\`: + +\`\`\`sql +-- ? groups (varchar[]) +SELECT o.* FROM orders o +JOIN TABLE(FLATTEN(input => PARSE_JSON(?))) g ON g.value::STRING = o.owner_group; +\`\`\` + ## Receiving an S3Object as a script parameter Declare the arg with type \`(s3object)\`. Windmill renders an S3 file picker for diff --git a/system_prompts/auto-generated/script.md b/system_prompts/auto-generated/script.md index cb5ae40490..509e34d502 100644 --- a/system_prompts/auto-generated/script.md +++ b/system_prompts/auto-generated/script.md @@ -3,6 +3,8 @@ ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_<name>`, which keeps it apart from a hub type synced later: the parameter takes `RT.C<Name>` in TypeScript, a `c_<name>` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments - Where the language has a Windmill client (`wmill`), use it to interact with the platform @@ -377,7 +379,7 @@ export async function main(url: string) { ## Pure computation: `//no_network` -A native script that only transforms its inputs can declare `//no_network` in its leading comment block (right after `//native`). The runtime then refuses every connection the script attempts: `fetch` to any host, the Windmill API (so `windmill-client` calls fail too), raw sockets and unix sockets, and `WM_TOKEN` is not set. It only takes effect on native scripts: without `//native` it is ignored. Use it only when the script needs no external data beyond its arguments: +A native script that only transforms its inputs can declare `//no_network` in its leading comment block (right after `//native`). The runtime then refuses every connection the script attempts: `fetch` to any host, the Windmill API (so `windmill-client` calls fail too), raw sockets and unix sockets, and `WM_TOKEN` is not set. Without `//native` it means something else: the script must run in an nsjail sandbox (`//sandbox`, or instance-wide sandboxing), which then loses its network, and it fails to run otherwise. Use it only when the script needs no external data beyond its arguments: ```typescript //native @@ -1409,6 +1411,27 @@ Name the parameters by adding comments before the statement: SELECT * FROM users WHERE name = ? AND age > ?; ``` +## Array parameters + +Declare a list with a `[]` suffix on the element type (`(varchar[])`, +`(int[])`), or `(array)` for an untyped one. Snowflake cannot bind an array +directly, so Windmill binds the list as JSON text: wrap the placeholder with +`PARSE_JSON(?)`, and cast to `ARRAY` where a function expects one. + +```sql +-- ? groups (varchar[]) +SELECT o.* FROM orders o +WHERE ARRAY_CONTAINS(o.owner_group::VARIANT, PARSE_JSON(?)::ARRAY); +``` + +Or join on the elements with `FLATTEN`: + +```sql +-- ? groups (varchar[]) +SELECT o.* FROM orders o +JOIN TABLE(FLATTEN(input => PARSE_JSON(?))) g ON g.value::STRING = o.owner_group; +``` + ## Receiving an S3Object as a script parameter Declare the arg with type `(s3object)`. Windmill renders an S3 file picker for @@ -1639,6 +1662,14 @@ async setProgress(percent: number, jobId?: any): Promise<void> */ async getProgress(jobId?: any): Promise<number | null> +/** + * Whether the worker running this job has received its shutdown signal. + * A draining worker waits for its current job to finish before exiting, so a + * long-running script can poll this and return early to let the worker be replaced. + * @param jobId? Job to check, defaults to the current job + */ +async workerIsDraining(jobId?: string): Promise<boolean> + /** * Set a flow user state * @param key key of the state @@ -1898,6 +1929,9 @@ async sleep(seconds: number): Promise<void> * `fn`'s result is encoded as JSON and decoded back before it is returned, so * the round that runs the body sees the same types every replay sees: a `Date` * comes back as a string, a `Map` as `{}`. {@link Jsonified} is that shape. + * + * Called from inside a task body, `fn` runs in place and nothing is + * checkpointed: a task is a single job and is never replayed. */ async step<T>(name: string, fn: () => T | Promise<T>,): Promise<Jsonified<Awaited<T>>> @@ -2311,6 +2345,18 @@ def set_progress(value: int, job_id: Optional[str] = None) # Progress value (0-100) or None if not set def get_progress(job_id: Optional[str] = None) -> Any +# Whether the worker running the job has received its shutdown signal. +# +# A draining worker waits for its current job to finish before exiting. A long-running +# script can poll this and return early so the worker can be replaced. +# +# Args: +# job_id: Job ID (defaults to current WM_JOB_ID) +# +# Returns: +# True if the worker running the job is draining +def worker_is_draining(job_id: Optional[str] = None) -> bool + # Set the user state of a flow at a given key def set_flow_user_state(key: str, value: Any) -> None @@ -2324,15 +2370,31 @@ def get_flow_user_state(key: str) -> Any def version() # Convenient helpers that takes an S3 resource as input and returns the settings necessary to -# initiate an S3 connection from DuckDB +# initiate an S3 connection from DuckDB. +# +# Without a resource path, the connection goes to the workspace storage through Windmill's +# S3 proxy when that storage is S3: address it as ``s3://<bucket>/<key>`` with the +# storage's own bucket, returned as ``s3_bucket``. Pass the resource path to connect with +# the storage's own credentials instead. def get_duckdb_connection_settings(s3_resource_path: str = '') -> DuckDbConnectionSettings | None # Convenient helpers that takes an S3 resource as input and returns the settings necessary to -# initiate an S3 connection from Polars +# initiate an S3 connection from Polars. +# +# Without a resource path, the connection goes to the workspace storage through Windmill's +# S3 proxy when that storage is S3: address it as ``s3://<bucket>/<key>`` with the +# storage's own bucket, returned as ``s3_bucket``. Pass the resource path to connect with +# the storage's own credentials instead. def get_polars_connection_settings(s3_resource_path: str = '') -> PolarsConnectionSettings # Convenient helpers that takes an S3 resource as input and returns the settings necessary to -# initiate an S3 connection using boto3 +# initiate an S3 connection using boto3. +# +# Without a resource path, the connection goes to the workspace storage through Windmill's +# S3 proxy when that storage is S3: pass the storage's own bucket as ``Bucket``. The proxy +# serves object reads, writes, deletes, listing and multipart uploads of that bucket only; +# presigned URLs, other buckets and bucket-level APIs need the storage's own credentials, +# which passing the resource path returns. def get_boto3_connection_settings(s3_resource_path: str = '') -> Boto3ConnectionSettings # Load a file from the workspace s3 bucket and returns its content as bytes. @@ -2728,7 +2790,9 @@ def parse_sql_client_name(name: str) -> tuple[str, Optional[str]] # # - **v2 (inside @workflow)**: dispatches as a checkpoint step. # - **v1 (WM_JOB_ID set, no @workflow)**: dispatches via HTTP API. -# - **Standalone**: executes the function body directly. +# - **Standalone, or called from inside another v2 task**: executes the +# function body directly. A task runs as a single job, so the tasks it +# calls run in that same job, without their own options. # # A task runs as its own job, so its result is always encoded as JSON and # decoded back before the caller sees it: a ``datetime`` comes back as a @@ -2814,12 +2878,15 @@ def workflow(func) # ``fn``'s result is encoded as JSON and decoded back before it is returned, # so the round that runs the body sees the same types every replay sees: # a ``datetime`` comes back as a string, a tuple as a list. +# +# Called from inside a task body, ``fn`` runs in place and nothing is +# checkpointed: a task is a single job and is never replayed. async def step(name: str, fn) # Server-side sleep — suspend the workflow for the given duration without holding a worker. # # Inside a @workflow, the parent job suspends and auto-resumes after ``seconds``. -# Outside a workflow, falls back to ``asyncio.sleep``. +# Outside a workflow, or inside a task body, falls back to ``asyncio.sleep``. async def sleep(seconds: int) # Suspend the workflow and wait for an external approval. diff --git a/system_prompts/auto-generated/sdks/python.md b/system_prompts/auto-generated/sdks/python.md index 4241d49efa..1a772ae6ee 100644 --- a/system_prompts/auto-generated/sdks/python.md +++ b/system_prompts/auto-generated/sdks/python.md @@ -240,6 +240,18 @@ def set_progress(value: int, job_id: Optional[str] = None) # Progress value (0-100) or None if not set def get_progress(job_id: Optional[str] = None) -> Any +# Whether the worker running the job has received its shutdown signal. +# +# A draining worker waits for its current job to finish before exiting. A long-running +# script can poll this and return early so the worker can be replaced. +# +# Args: +# job_id: Job ID (defaults to current WM_JOB_ID) +# +# Returns: +# True if the worker running the job is draining +def worker_is_draining(job_id: Optional[str] = None) -> bool + # Set the user state of a flow at a given key def set_flow_user_state(key: str, value: Any) -> None @@ -253,15 +265,31 @@ def get_flow_user_state(key: str) -> Any def version() # Convenient helpers that takes an S3 resource as input and returns the settings necessary to -# initiate an S3 connection from DuckDB +# initiate an S3 connection from DuckDB. +# +# Without a resource path, the connection goes to the workspace storage through Windmill's +# S3 proxy when that storage is S3: address it as ``s3://<bucket>/<key>`` with the +# storage's own bucket, returned as ``s3_bucket``. Pass the resource path to connect with +# the storage's own credentials instead. def get_duckdb_connection_settings(s3_resource_path: str = '') -> DuckDbConnectionSettings | None # Convenient helpers that takes an S3 resource as input and returns the settings necessary to -# initiate an S3 connection from Polars +# initiate an S3 connection from Polars. +# +# Without a resource path, the connection goes to the workspace storage through Windmill's +# S3 proxy when that storage is S3: address it as ``s3://<bucket>/<key>`` with the +# storage's own bucket, returned as ``s3_bucket``. Pass the resource path to connect with +# the storage's own credentials instead. def get_polars_connection_settings(s3_resource_path: str = '') -> PolarsConnectionSettings # Convenient helpers that takes an S3 resource as input and returns the settings necessary to -# initiate an S3 connection using boto3 +# initiate an S3 connection using boto3. +# +# Without a resource path, the connection goes to the workspace storage through Windmill's +# S3 proxy when that storage is S3: pass the storage's own bucket as ``Bucket``. The proxy +# serves object reads, writes, deletes, listing and multipart uploads of that bucket only; +# presigned URLs, other buckets and bucket-level APIs need the storage's own credentials, +# which passing the resource path returns. def get_boto3_connection_settings(s3_resource_path: str = '') -> Boto3ConnectionSettings # Load a file from the workspace s3 bucket and returns its content as bytes. @@ -657,7 +685,9 @@ def parse_sql_client_name(name: str) -> tuple[str, Optional[str]] # # - **v2 (inside @workflow)**: dispatches as a checkpoint step. # - **v1 (WM_JOB_ID set, no @workflow)**: dispatches via HTTP API. -# - **Standalone**: executes the function body directly. +# - **Standalone, or called from inside another v2 task**: executes the +# function body directly. A task runs as a single job, so the tasks it +# calls run in that same job, without their own options. # # A task runs as its own job, so its result is always encoded as JSON and # decoded back before the caller sees it: a ``datetime`` comes back as a @@ -743,12 +773,15 @@ def workflow(func) # ``fn``'s result is encoded as JSON and decoded back before it is returned, # so the round that runs the body sees the same types every replay sees: # a ``datetime`` comes back as a string, a tuple as a list. +# +# Called from inside a task body, ``fn`` runs in place and nothing is +# checkpointed: a task is a single job and is never replayed. async def step(name: str, fn) # Server-side sleep — suspend the workflow for the given duration without holding a worker. # # Inside a @workflow, the parent job suspends and auto-resumes after ``seconds``. -# Outside a workflow, falls back to ``asyncio.sleep``. +# Outside a workflow, or inside a task body, falls back to ``asyncio.sleep``. async def sleep(seconds: int) # Suspend the workflow and wait for an external approval. diff --git a/system_prompts/auto-generated/sdks/typescript.md b/system_prompts/auto-generated/sdks/typescript.md index 47b0be888d..da9e79ec94 100644 --- a/system_prompts/auto-generated/sdks/typescript.md +++ b/system_prompts/auto-generated/sdks/typescript.md @@ -196,6 +196,14 @@ async setProgress(percent: number, jobId?: any): Promise<void> */ async getProgress(jobId?: any): Promise<number | null> +/** + * Whether the worker running this job has received its shutdown signal. + * A draining worker waits for its current job to finish before exiting, so a + * long-running script can poll this and return early to let the worker be replaced. + * @param jobId? Job to check, defaults to the current job + */ +async workerIsDraining(jobId?: string): Promise<boolean> + /** * Set a flow user state * @param key key of the state @@ -455,6 +463,9 @@ async sleep(seconds: number): Promise<void> * `fn`'s result is encoded as JSON and decoded back before it is returned, so * the round that runs the body sees the same types every replay sees: a `Date` * comes back as a string, a `Map` as `{}`. {@link Jsonified} is that shape. + * + * Called from inside a task body, `fn` runs in place and nothing is + * checkpointed: a task is a single job and is never replayed. */ async step<T>(name: string, fn: () => T | Promise<T>,): Promise<Jsonified<Awaited<T>>> diff --git a/system_prompts/auto-generated/sdks/wac-python.md b/system_prompts/auto-generated/sdks/wac-python.md index a8e98a9d4f..6dd307dd24 100644 --- a/system_prompts/auto-generated/sdks/wac-python.md +++ b/system_prompts/auto-generated/sdks/wac-python.md @@ -36,7 +36,9 @@ def get_resume_urls(approver: str = None, flow_level: bool = None) -> dict # # - **v2 (inside @workflow)**: dispatches as a checkpoint step. # - **v1 (WM_JOB_ID set, no @workflow)**: dispatches via HTTP API. -# - **Standalone**: executes the function body directly. +# - **Standalone, or called from inside another v2 task**: executes the +# function body directly. A task runs as a single job, so the tasks it +# calls run in that same job, without their own options. # # A task runs as its own job, so its result is always encoded as JSON and # decoded back before the caller sees it: a ``datetime`` comes back as a @@ -122,12 +124,15 @@ def workflow(func) # ``fn``'s result is encoded as JSON and decoded back before it is returned, # so the round that runs the body sees the same types every replay sees: # a ``datetime`` comes back as a string, a tuple as a list. +# +# Called from inside a task body, ``fn`` runs in place and nothing is +# checkpointed: a task is a single job and is never replayed. async def step(name: str, fn) # Server-side sleep — suspend the workflow for the given duration without holding a worker. # # Inside a @workflow, the parent job suspends and auto-resumes after ``seconds``. -# Outside a workflow, falls back to ``asyncio.sleep``. +# Outside a workflow, or inside a task body, falls back to ``asyncio.sleep``. async def sleep(seconds: int) # Suspend the workflow and wait for an external approval. diff --git a/system_prompts/auto-generated/sdks/wac-typescript.md b/system_prompts/auto-generated/sdks/wac-typescript.md index 608d75d18c..dd04a64de0 100644 --- a/system_prompts/auto-generated/sdks/wac-typescript.md +++ b/system_prompts/auto-generated/sdks/wac-typescript.md @@ -67,8 +67,9 @@ export async function getResumeUrls(approver?: string, flowLevel?: boolean): Pro * const call_api = task(fetchOrders, { retry: { attempts: 3, delay: 30, multiplier: 2 } }); * * Inside a `workflow()`, calling a task dispatches it as a step. - * Outside a workflow, the function body executes directly and - * {@link TaskOptions} — retry included — does not apply. + * Outside a workflow, or called from inside another task, the function body + * executes directly and {@link TaskOptions} — retry included — does not apply: + * a task runs as a single job, so the tasks it calls run in that same job. * * A task runs as its own job, so its result is always encoded as JSON and * decoded back before the caller sees it: a `Date` comes back as a string, a @@ -112,6 +113,9 @@ export function workflow<T>(fn: (...args: any[]) => Promise<T>) * `fn`'s result is encoded as JSON and decoded back before it is returned, so * the round that runs the body sees the same types every replay sees: a `Date` * comes back as a string, a `Map` as `{}`. {@link Jsonified} is that shape. + * + * Called from inside a task body, `fn` runs in place and nothing is + * checkpointed: a task is a single job and is never replayed. */ export async function step<T>(name: string, fn: () => T | Promise<T>,): Promise<Jsonified<Awaited<T>>> diff --git a/system_prompts/auto-generated/skills/cli-commands/SKILL.md b/system_prompts/auto-generated/skills/cli-commands/SKILL.md index 3f41b5cfba..30fb9b93e3 100644 --- a/system_prompts/auto-generated/skills/cli-commands/SKILL.md +++ b/system_prompts/auto-generated/skills/cli-commands/SKILL.md @@ -35,7 +35,7 @@ app related commands - `app dev [app_folder:string]` - Start a development server for building apps with live reload and hot module replacement - `--port <port:number>` - Port to run the dev server on (will find next available port if occupied) - `--host <host:string>` - Host to bind the dev server to - - `--entry <entry:string>` - Entry point file (default: index.ts for Svelte/Vue, index.tsx otherwise) + - `--entry <entry:string>` - Entry point file (default: index.ts for Svelte, index.tsx otherwise) - `--no-open` - Don't automatically open the browser - `--recording` - Frame the app in a shell with a Record button, to capture a replayable session recording of the app under development - `app lint [app_folder:string]` - Lint a raw app folder to validate structure and buildability @@ -46,7 +46,7 @@ app related commands - `app new` - create a new raw app from a template - `--summary <summary:string>` - App summary (short description). Skips the prompt when provided. Triggers non-interactive mode. - `--path <path:string>` - App path (e.g., f/folder/my_app or u/username/my_app). Skips the prompt when provided. Triggers non-interactive mode. - - `--framework <framework:string>` - Framework template: react19 | react18 | svelte5 | vue. Skips the prompt when provided. Triggers non-interactive mode. + - `--framework <framework:string>` - Framework template: react19 | react18 | svelte5. Skips the prompt when provided. Triggers non-interactive mode. - `--datatable <datatable:string>` - Datatable to wire up. Without this flag in non-interactive mode, no datatable is configured. - `--schema <schema:string>` - Schema to use with --datatable. If it doesn't exist yet, a sql_to_apply/ migration (CREATE SCHEMA IF NOT EXISTS) is written for it. - `--overwrite` - Overwrite the target directory if it already exists, without prompting. @@ -89,8 +89,10 @@ datatable related commands - `datatable migrate` - manage datatable migrations - `datatable migrate new <name:string>` - scaffold a new migration (.up.sql / .down.sql files) - `-d --datatable <datatable:string>` - Target datatable (default: main) + - `-s --schemas <schemas:string>` - Comma-separated schemas the migration changes, written as its `-- schemas` line. Without it the migration applies to the whole database and every later migration waits for it - `datatable migrate up` - apply all pending migrations to the main datatable (or one via --datatable) - `-d --datatable <datatable:string>` - Target datatable (default: main) + - `--schema <schema:string>` - Apply only the pending migrations that declare this schema; refused while an earlier overlapping migration is pending - `datatable migrate down` - roll back the most recent migration on the main datatable (or one via --datatable) - `-d --datatable <datatable:string>` - Target datatable (default: main) - `datatable migrate status` - show applied and pending migrations on the main datatable (or one via --datatable) @@ -186,6 +188,7 @@ flow related commands - `--remote` - Use deployed workspace scripts for PathScript steps instead of local files. - `--step <step_id:string>` - Run only the named step instead of the whole flow. Honors --data as the step's args and --remote / local-PathScript resolution the same way the full-flow preview does. - `--tag <tag:string>` - Override the worker tag the preview is dispatched to (e.g. to route it to dev workers instead of the flow's default tag). + - `--on-behalf-of <identity:string>` - Run the preview as this user or group (an email, u/<username> or g/<group>) instead of yourself, e.g. to reproduce a run_on_behalf_of identity. Requires being an admin or a member of wm_deployers. - `flow new <flow_path:string>` - create a new empty flow - `--summary <summary:string>` - flow summary - `--description <description:string>` - flow description @@ -584,6 +587,7 @@ script related commands - `-d --data <data:file>` - Inputs specified as a JSON string or a file using @<filename> or stdin using @-. A resource argument is the bare string $res:<path> as its whole value, and a variable argument is the bare string $var:<path> — not an object wrapper keyed on $res/$var, and not a plain path. - `-s --silent` - Do not output anything other than the final output. Useful for scripting. - `--tag <tag:string>` - Override the worker tag the preview is dispatched to (e.g. to route it to dev workers instead of the script's default tag). + - `--on-behalf-of <identity:string>` - Run the preview as this user or group (an email, u/<username> or g/<group>) instead of yourself, e.g. to reproduce a run_on_behalf_of identity. Requires being an admin or a member of wm_deployers. - `script new <path:file> <language:string>` - create a new script - `--summary <summary:string>` - script summary - `--description <description:string>` - script description @@ -621,6 +625,7 @@ sync local with a remote workspaces or the opposite (push or pull) - `--include-users` - Include syncing users - `--include-groups` - Include syncing groups - `--include-settings` - Include syncing workspace settings + - `--include-datatable-permissions` - With --include-settings, also sync who may connect to each data table as which role - `--include-key` - Include workspace encryption key - `--keep-deleted` - Do not delete local files for items that no longer exist on the remote workspace. Only adds and updates. - `--skip-branch-validation` - Skip git branch validation and prompts @@ -652,6 +657,7 @@ sync local with a remote workspaces or the opposite (push or pull) - `--include-users` - Include syncing users - `--include-groups` - Include syncing groups - `--include-settings` - Include syncing workspace settings + - `--include-datatable-permissions` - With --include-settings, also sync who may connect to each data table as which role - `--include-key` - Include workspace encryption key - `--skip-reencrypt-on-key-change` - When the pushed encryption key differs from the remote, do NOT re-encrypt existing remote secrets. Only safe if they are already encrypted with the new key (e.g. workspace/instance migration). Default is to re-encrypt. - `--keep-deleted` - Do not delete remote items that no longer exist locally. Only adds and updates. @@ -845,6 +851,13 @@ Arguments (omit both to be prompted interactively): - `--team-id <team_id:string>` - Slack team id - `--team-name <team_name:string>` - Slack team name - `workspace disconnect-slack` - Clear slack_team_id / slack_name on the active workspace (marks the workspace as disconnected). Does NOT remove the bot token variable/resource/folder/group — delete those from the local sync folder and run 'wmill sync push' to tear them down. Does NOT remove the workspace-level OAuth override — set slack_oauth_client_id/_secret to '' in settings.yaml and push. +- `workspace get-settings` - Print the active workspace's settings in the layout of the settings.yaml that 'wmill sync' writes. Secrets show as __SENSITIVE_AND_UNCHANGED__ unless --encrypted. Admin only. + - `--encrypted` - Write secrets encrypted with the workspace key, as 'wmill sync pull' does + - `--json` - Output as JSON +- `workspace apply-settings <file:string>` - Apply a settings document (YAML or JSON, in the layout of settings.yaml) to the active workspace. Only the settings the file states are changed, unless --replace; a setting set to null is cleared. A secret left as __SENSITIVE_AND_UNCHANGED__ keeps its value. Shows the changes and asks before applying. Admin only. + - `--dry-run` - Only show the changes + - `--replace` - Also clear the settings the file omits, as 'wmill sync push' does + - `-y --yes` - Apply without asking diff --git a/system_prompts/auto-generated/skills/datatables/SKILL.md b/system_prompts/auto-generated/skills/datatables/SKILL.md new file mode 100644 index 0000000000..ac0bdf257c --- /dev/null +++ b/system_prompts/auto-generated/skills/datatables/SKILL.md @@ -0,0 +1,47 @@ +--- +name: datatables +description: MUST use when changing a data table's schema, writing or running its migrations, or working with its roles and permissions. +--- + +# Data tables: schema changes, migrations and permissions + +A data table is a PostgreSQL database managed by Windmill and shared by the whole workspace: scripts, flows and apps reach it by name, `main` being the default. It is configured in the workspace settings (Data Tables), never created by SQL. + +## Changing the schema + +A data table with migrations enabled keeps its schema as an ordered list of versioned SQL migrations, each an `up` and an optional `down`. That list is what git sync and a workspace merge carry, and what rebuilds the schema in another workspace. So first find out whether migrations are enabled on the data table: + +- **Enabled**: make every schema change (CREATE, ALTER, DROP, anything but row data) as a new migration. A change made with plain SQL exists in that one database only, and the history no longer describes it. +- **Not enabled**: schema changes are plain SQL. Enabling migrations is a workspace admin's decision, made in the Data Tables settings, not a step to take on the way to something else. + +Writing a migration: + +- Wrap the statements in `BEGIN; ... END;` so it applies atomically. Leave the frame out only for a statement that cannot run in a transaction, such as `CREATE INDEX CONCURRENTLY`: such a migration can fail half applied. +- Give it a `down` that undoes the `up` whenever the change is reversible. Without one it cannot be rolled back. +- Declare the schemas it changes on a leading line of its `up`, `-- schemas sales, billing`, and qualify every name with its schema (`sales.orders`). A migration waits only on earlier migrations whose schemas overlap its own. One that declares none applies to the whole database and every later migration waits for it, so leave the line out only for a change that really spans the database, such as an extension. +- Migrations apply oldest first. One that is applied is not edited: correct it with a new migration. +- Row data is not schema. Insert, update and delete rows with plain SQL, migrations or not. + +`wmill datatable migrate new <name>` scaffolds `migrations/datatable/<datatable>/<timestamp>_<name>.up.sql` and `.down.sql`, `wmill datatable migrate up` pushes the local files and applies what is pending, `wmill datatable migrate down` rolls back the most recent one and `wmill datatable migrate status` lists them. All take `-d <datatable>` and default to `main`. `migrate new --schemas sales,billing` writes the `-- schemas` line, and `migrate up --schema sales` applies only the pending migrations declaring that schema. + +## A migration is not a draft + +A migration is saved to the workspace and changes the database as soon as it is applied, for everything that reads those tables. To try a schema out without touching tables already in use: + +- put the new tables in a schema of their own, created by the same migration (`CREATE SCHEMA IF NOT EXISTS`), and point what you are building at it. A raw app names its schema in its `data` config, which is why a new app gets a new schema by default; +- or work in a workspace fork whose data table was cloned when the fork was created ("Clone schema only" or "Clone schema and data"): migrations applied there change that copy alone, and reach the parent workspace when the fork is merged. A fork that kept the original data table points at the parent's database, so a migration applied in it changes the parent's tables at once. + +Altering or dropping a table other scripts or apps use is neither of those: say what depends on it before doing it. + +## Roles and permissions + +Data table roles are a self-hosted Enterprise Edition feature, for data tables on managed Postgres (the instance database or the external managed instance). Without them, and always on a data table backed by a Postgres resource, everyone who can use the data table reaches all of it: there is no per-user, per-schema or per-row access to promise. + +A data table under roles is reached as a Postgres role, and Postgres enforces what that role was granted: + +- roles are assigned, per data table, to users, groups or folders. `admin` is the connection the data table had before roles: it owns the existing objects and ignores grants; +- a connection either names a role (`wmill.datatable('main', { role: 'analyst' })`, `role='analyst'` in Python, `datatable://main?role=analyst`) and holds that role alone, or names none and is resolved from the data table's default role; +- `permission denied` means the role in use lacks a grant. Say which role and which object: the grant is a data table admin's to give, in the roles drawer of the Database Manager. Do not switch to `admin` to get past it; +- a migration runs as the role its SQL declares on its first line, `-- role <name>`, the same one in its `down`. One that declares none runs as `admin`, which only those who may use `admin` can do. + +Read the Permissions section of https://www.windmill.dev/docs/core_concepts/persistent_storage/data_tables before designing who reaches what: it covers tenants, grants, the default role and the roles a connection that names none ends up holding, rows that differ per viewer through row-level security, and how forks and raw apps behave under roles. diff --git a/system_prompts/auto-generated/skills/raw-app/SKILL.md b/system_prompts/auto-generated/skills/raw-app/SKILL.md index 2f7cd52d5f..df5e7ece6a 100644 --- a/system_prompts/auto-generated/skills/raw-app/SKILL.md +++ b/system_prompts/auto-generated/skills/raw-app/SKILL.md @@ -17,7 +17,7 @@ You need three values to run the command: 1. **summary** — a short description of the app 2. **path** — the windmill path, e.g. `f/folder/my_app` or `u/username/my_app` -3. **framework** — one of `react19` (recommended), `react18`, `svelte5`, `vue` +3. **framework** — one of `react19` (recommended), `react18`, `svelte5` **summary and path**: if the user's request did not supply them, ask. Do not guess values and do not invent paths. @@ -89,7 +89,7 @@ my_app__raw_app/ ├── DATATABLES.md # Database schemas (run 'wmill app generate-agents' to refresh) ├── raw_app.yaml # App configuration (summary, path, data settings) ├── index.tsx # Frontend entry point -├── App.tsx # Main React/Svelte/Vue component +├── App.tsx # Main React/Svelte component ├── index.css # Styles ├── package.json # Frontend dependencies ├── wmill.ts # Auto-generated backend type definitions (DO NOT EDIT) @@ -152,6 +152,8 @@ fields: value: "default_user" ``` +`viewer_data_access: true` makes an inline runnable read data tables and object storage as the person using the app instead of as the app's identity (see "Reading data as the viewer"). + ### Referencing existing scripts To use an existing Windmill script instead of inline code: @@ -188,7 +190,7 @@ data: - `<datatable>/<table>` — Specific table in public schema - `<datatable>/<schema>:<table>` — Table in specific schema -**Roles:** when a datatable is under roles, its queries run as a role, which only reaches what it was granted. `roles` records the role the app uses each datatable through; the app's code must pass the same role: `wmill.datatable('main', { role: 'analyst' })` in TypeScript, `wmill.datatable('main', role='analyst')` in Python. A datatable without an entry is used as its default role. +**Roles:** when a datatable is under roles, its queries run as a role, which only reaches what it was granted. `roles` records the role the app uses each datatable through; the app's code must pass the same role: `wmill.datatable('main', { role: 'analyst' })` in TypeScript, `wmill.datatable('main', role='analyst')` in Python. A datatable without an entry is used as its default role, if it has one, plus the roles of the app's identity, or of whoever is using the app for a runnable with `viewer_data_access: true`, unless that default is `admin`. ## SQL Migrations (sql_to_apply/) @@ -247,7 +249,7 @@ For the rest, tell the user which command fits their intent and let them run it # Windmill Raw Apps -Raw apps let you build custom frontends with React, Svelte, or Vue that connect to Windmill backend runnables and datatables. +Raw apps let you build custom frontends with React or Svelte that connect to Windmill backend runnables and datatables. ## App shape @@ -263,7 +265,7 @@ A new app gets the setup Windmill's own new-app dialog gives one: a framework, t ### Framework -Use the framework the user named. When they named none, follow what there is to follow: the app being edited, or the apps the request points at. With nothing to follow, use **React 19**, the recommended default, **without asking**. React 18, Svelte 5 and Vue are for when they are asked for. +Use the framework the user named. When they named none, follow what there is to follow: the app being edited, or the apps the request points at. With nothing to follow, use **React 19**, the recommended default, **without asking**. React 18 and Svelte 5 are for when they are asked for. These three are the only frameworks the raw app bundler builds. When the user asks to build or convert an app in another framework, write no code in it: say it is not available and offer these three instead. ### Data setup @@ -293,7 +295,7 @@ Then build what was chosen: the data table and schema become the app's `data.dat ### Entrypoint -The entrypoint is `index.tsx` for React and `index.ts` for Svelte and Vue. It is both the bundling entrypoint (the bundler is esbuild) and the **mount** entrypoint: the preview executes the bundle against an empty `<div id="root">` and auto-renders nothing, so the entrypoint must mount a top-level `App` itself. Keep the UI in `App.tsx` / `App.svelte` / `App.vue` and keep the entrypoint as the mount shim. +The entrypoint is `index.tsx` for React and `index.ts` for Svelte. It is both the bundling entrypoint (the bundler is esbuild) and the **mount** entrypoint: the preview executes the bundle against an empty `<div id="root">` and auto-renders nothing, so the entrypoint must mount a top-level `App` itself. Keep the UI in `App.tsx` / `App.svelte` and keep the entrypoint as the mount shim. React (`index.tsx`): @@ -305,10 +307,12 @@ import App from './App' createRoot(document.getElementById('root')!).render(<App />) ``` -Svelte (`index.ts`): `mount(App, { target: document.getElementById('root')! })`. Vue (`index.ts`): `createApp(App).mount('#root')`. +Svelte (`index.ts`): `mount(App, { target: document.getElementById('root')! })`. **Never replace the entrypoint with a bare component** (`export default function App() { ... }` and no mount call). A component that is defined but never mounted renders a blank screen with **no error thrown** — it never executes, so nothing reaches the console or the error overlay. If an app renders blank, check that the entrypoint still mounts `App` into `#root`. +**Set the browser tab title with `document.title = '...'`** (or a `<title>` the framework renders into `<head>`). The app has no `index.html` of its own, so a `<title>` written there is never served; the deployed app's page shows whatever `document.title` holds, and follows it when it changes. + **Always begin every React file (`.tsx`/`.jsx`) that uses JSX with `import React from 'react'`.** esbuild uses the classic JSX transform, so `React` must be in scope wherever JSX appears — a missing import compiles fine but throws `React is not defined` at runtime, leaving a blank screen. ### Generated bindings (`wmill.d.ts` / `wmill.ts`) @@ -378,16 +382,16 @@ Apply it to customer data, internal notes and anything else a viewer of the demo ### Chat UIs over a flow in chat mode -A flow deployed with chat mode on is a chat backend (streaming answer, tool calls, memory, conversation history). Do not drive it through a runnable: add `windmill-chat` to `package.json` and use it directly, it detects the app's Windmill and credential. +A flow deployed with chat mode on is a chat backend (streaming answer, tool calls, memory, conversation history). Do not drive it through a runnable: add `@windmill-labs/chat-sdk` to `package.json` and use it directly, it detects the app's Windmill and credential. ```tsx -import { useWindmillChat } from 'windmill-chat/react' +import { useWindmillChat } from '@windmill-labs/chat-sdk/react' const chat = useWindmillChat({ flowPath: 'f/support/assistant' }) // chat.messages ({ role, content, pending, success, tool? }), chat.status, chat.sendMessage(text), chat.stop() ``` -`windmill-chat/ai-sdk` gives a `ChatTransport` for the Vercel AI SDK's `useChat`, `windmill-chat/assistant-ui` a runtime for assistant-ui. The flow must be deployed, not a draft. A sandboxed app needs `jobs:run` in its frontend SDK scopes, plus `flow_conversations:write` for the conversation sidebar; without them the chat keeps history in the browser. +`@windmill-labs/chat-sdk/ai-sdk` gives a `ChatTransport` for the Vercel AI SDK's `useChat`, `@windmill-labs/chat-sdk/assistant-ui` a runtime for assistant-ui. The flow must be deployed, not a draft. A sandboxed app needs `jobs:run` in its frontend SDK scopes, plus `flow_conversations:write` for the conversation sidebar; without them the chat keeps history in the browser. ## Backend runnables @@ -428,6 +432,10 @@ def main(user_id: str): return user ``` +#### Sharing code between runnables + +An inline runnable can import another inline runnable of the same app by its id, as a relative import: `import { getDb } from './shared'` (TypeScript, Bun) or `from .shared import get_db` (Python). This works across TypeScript (Bun) runnables and across Python runnables, not between the two. The imported runnable's own dependencies are picked up, and it can import further runnables in turn. A runnable that only holds helpers needs no `main`; the frontend just never calls it. A TypeScript runnable whose id is `main` cannot be imported, because that name is taken by the entrypoint file of every TypeScript job: give shared code any other id. + #### The `wmill` client is already authenticated An inline runnable runs as an ordinary Windmill job. `import * as wmill from 'windmill-client'` (TypeScript) and `import wmill` (Python) are already pointed at this instance and this workspace — there is nothing to configure. @@ -471,6 +479,27 @@ A draft app is reachable by nobody; deploying is what exposes it, and its backen Either one lets those people run the app's backend runnables, so never open an app up unless the user asks. `public: true` in `raw_app.yaml` deploys the app for anonymous users, and `guests: true` for guests. Remove the line and the next push closes the app again. +An app's custom URL is not in `raw_app.yaml`: each workspace has its own file next to the app folder, `<app path>.<workspace>.custom_path.yaml` (for example `f/sales/dashboard.prod.custom_path.yaml` holding `custom_path: dashboard`), where `<workspace>` is the workspace's name in `wmill.yaml`, or its id. A push applies only the target workspace's file and leaves the deployed custom URL alone when there is none, so deleting the file does not remove the URL: `custom_path: ''` does. Setting or clearing one takes a workspace admin. + +## Sandbox isolation and frontend API access + +New apps are sandboxed: the frontend is isolated from the viewer's own Windmill session and reaches Windmill only through its backend runnables, plus whatever frontend API scopes the app declares, which each viewer approves before the app runs. With isolation turned off, the frontend runs with the viewer's full session. The scopes are `jobs:run`, `jobs:read`, `resources:read`, `variables:read`, `flow_conversations:read` and `flow_conversations:write`; grant only the ones the frontend calls. The viewer's identity needs no scope: it is in `window.ctx`, and whoami works with any of them. + +Inside the sandbox, IndexedDB is unavailable, third-party sign-in and OAuth redirects fail, and requests to other services carry `Origin: null`, which an API that checks the origin rejects. Work around these first: call the service from a backend runnable, keep state in a data table or `localStorage`, or grant the frontend API scope the code needs. Suggest turning isolation off only when none of that works, and say plainly that it is a security risk: the app's code, and any XSS bug in it, then runs with the full Windmill permissions of everyone who opens the app. +In `raw_app.yaml`: + +```yaml +sandbox: true +frontend_api: [jobs:run] +``` + +A file with a `sandbox` key states both settings: `sandbox: false` turns isolation off, and a missing `frontend_api` means no scopes. A file without the key leaves the deployed app's isolation and scopes as they are, so removing `sandbox: true` does not unsandbox it. `frontend_api` needs `sandbox: true`; the push fails otherwise. + +## Reading data as the viewer + +A backend runnable reads data as the app's identity (the publisher in publisher mode), the same for every viewer. An inline runnable can instead read data as the person using the app: its data table connections that name no role hold that viewer's roles, and object storage permission rules (which paths may be listed, read, written) are checked against the viewer. Resources, variables and everything else stay the app's, and an anonymous viewer is refused. Turn it on only when what the runnable reads should differ per viewer: row-level security on a data table, or per-user paths in object storage. Both are Enterprise Edition features. +Set it with `viewer_data_access: true` in the runnable's `backend/<id>.yaml`. + ## Data Tables Data tables are PostgreSQL databases managed by Windmill. Backend runnables query them via the `wmill` client; the frontend never queries them directly. **When the app needs to store or persist data** (user data, settings, application state, records, logs), use a data table. @@ -482,6 +511,7 @@ Data tables are PostgreSQL databases managed by Windmill. Backend runnables quer 3. **No DDL inside runnables**: runnables only read and write rows (SELECT, INSERT, UPDATE, DELETE) on existing tables. Never CREATE, ALTER or DROP a table from a runnable. 4. **Qualify table names**: an unqualified name means the `public` schema, so write every other table as `schema.table`, in table creation and queries alike. The app's `data` config sets the default datatable and schema its tables go in; use them consistently across runnables. 5. **Pass the role**: when the app's `data.roles` gives a data table a role, every `wmill.datatable` call on it passes that role (`wmill.datatable('main', { role: 'analyst' })` in TypeScript, `wmill.datatable('main', role='analyst')` in Python). The role only reaches what it was granted, so a query outside it fails with `permission denied`. +6. **Per-viewer rows**: a data table with no entry in `data.roles` is called with no role. Unless its default role is `admin`, the connection then holds the default role, if it may use it, plus every role it is a tenant of, and is refused when that is none. Whose roles those are follows the runnable's identity (see "Reading data as the viewer"). Row-level security policies written as `pg_has_role(current_user, '<role>', 'member')` then return the right rows with nothing added to the code. A role pins the connection to that one role either way, so a data table whose rows should differ per viewer gets no `data.roles` entry. Data table roles are an Enterprise Edition feature, self-hosted only. `wmill datatable list` lists the workspace's data tables. Create or change tables with a migration in `sql_to_apply/` (see "SQL Migrations" above), then add them to `data.tables` in `raw_app.yaml`. @@ -535,4 +565,4 @@ def main(user_id: str): 7. **Mark sensitive UI with `data-wm-no-record`** — it is what keeps that data out of a recorded demo; passwords are handled for you. 8. **Reach for `backendAsync` + `waitJob`** for long work — never a hand-written job-polling runnable. 9. **Deploy what a path runnable points at** — a path runnable aimed at a draft fails at runtime; tell the user what needs deploying. -10. **Use `windmill-chat` for a chat over a chat-mode flow** — never a runnable that runs the flow and polls its stream. +10. **Use `@windmill-labs/chat-sdk` for a chat over a chat-mode flow** — never a runnable that runs the flow and polls its stream. diff --git a/system_prompts/auto-generated/skills/resources/SKILL.md b/system_prompts/auto-generated/skills/resources/SKILL.md index bd690b1dec..45d3c64619 100644 --- a/system_prompts/auto-generated/skills/resources/SKILL.md +++ b/system_prompts/auto-generated/skills/resources/SKILL.md @@ -34,6 +34,12 @@ Example: `f/databases/postgres_prod.resource.json` - `value` - Object containing the resource configuration - `resource_type` - Name of the resource type (e.g., "postgresql", "slack") +## Agents + +An agent, as the Agents page lists it, is a resource of type `ai_agent`. Its value holds the +agent's provider, system prompt, tools and memory settings, and a flow step uses a saved agent by +linking its path. + ## Variable References Reference variables in resource values: @@ -214,13 +220,23 @@ The prefix must be on the string itself. } ``` +## When No Resource Type Fits + +The Windmill Hub publishes resource types for most services, and an instance gets them by syncing with the hub. When none fits the service: + +- If the instance is reported as not having synced the hub's types, mention that a superadmin can sync them: the hub most likely has one for the service. That holds for a type a hub script takes too: it is missing here until the sync, so say so before asking for a resource of it. Create one of your own only if the user still wants it, since after a sync the workspace would hold both. +- Otherwise, or when the user prefers it to syncing, propose a custom resource type named `c_<name>` holding the service's connection fields (base URL, account or region identifiers, credentials), as in "Custom Resource Types" below, and ask the user before creating it: every resource of that type and every script taking one depends on its fields. +- A plain variable instead of a resource is fine when the user asks for it; without that, default to the resource, its secret in a variable it references. + ## Custom Resource Types +A custom type's name starts with `c_`: the hub's types reach every instance under their plain names, so the prefix keeps a custom type from clashing with one synced later. Scripts and flows refer to the full name: `format: resource-c_custom_api`, `RT.CCustomApi` in TypeScript, a `c_custom_api` TypedDict in Python. + Create custom resource types with JSON Schema: ```json { - "name": "custom_api", + "name": "c_custom_api", "schema": { "type": "object", "properties": { @@ -234,7 +250,7 @@ Create custom resource types with JSON Schema: } ``` -Save as: `custom_api.resource-type.json` +Save as: `c_custom_api.resource-type.json` ## OAuth Resources diff --git a/system_prompts/auto-generated/skills/workspace-settings/SKILL.md b/system_prompts/auto-generated/skills/workspace-settings/SKILL.md new file mode 100644 index 0000000000..6216b92db6 --- /dev/null +++ b/system_prompts/auto-generated/skills/workspace-settings/SKILL.md @@ -0,0 +1,84 @@ +--- +name: workspace-settings +description: MUST use when reading or changing workspace settings, or the settings.yaml file `wmill sync` keeps. +--- + +# Workspace settings + +Everything an admin sets on the Workspace settings page is one document: a mapping of top-level +keys, the same layout as the `settings.yaml` file `wmill sync` keeps. Only a workspace admin can +read or change it. + +## Applying a document + +- A partial document changes only the keys it states; every key it omits is left as it is. +- Each key is replaced whole, so read its current value and send it back edited: a nested object + given with one field replaces the stored object with that one field. +- A key set to `null` clears that setting; an on/off switch cleared this way reads as `false`. +- Each setting is written through the same path the settings page uses, with the same validation + and audit log. The writes are not one transaction: when one fails the apply stops, and the + error says what was already written. +- A dry run reports the changes, as `before` / `after` per key, without writing anything. +- `name` is never applied: rename a workspace on the settings page. `color` is applied only when + set to a value, so `null` does not clear it. +- A key the server does not know is ignored and named in the warnings: check them, since a typo + otherwise reads as "nothing to change". +- A setting this edition does not offer (Enterprise only) is refused, by the dry run too. + +## Secrets + +`slack_oauth_client_secret` is the one secret. A read shows `__SENSITIVE_AND_UNCHANGED__` in place +of a set secret; sending that placeholder back keeps the stored value. A value starting with +`$encrypted:` is decrypted with the workspace key, and one encrypted with another workspace's key +is left unchanged with a warning; any other value is taken as plaintext. Never +write a secret you were not given: keep the placeholder. + +## Keys + +| Key | Value | +|---|---| +| `auto_invite` | `{ enabled, mode: invite \| add, operator, instance_groups?, instance_groups_roles? }`. The instance groups are managed only when `instance_groups` is stated; clearing a group removes the members it added. | +| `error_handler` / `success_handler` | `{ path, extra_args?, muted_on_cancel?, muted_on_user_path? }`, `path` being `script/<path>` or `flow/<path>`. | +| `error_handler_fallback_to_instance_alerts` | Report failures to the instance critical alert channels when no error handler is set. | +| `webhook` | URL POSTed a JSON event on every change to the workspace's items. | +| `ai_config` | Providers, default and completion models, custom prompts, `copilot_disabled`. | +| `large_file_storage` | Workspace object storage: `{ type, s3_resource_path \| azure_blob_resource_path \| gcs_resource_path, public_resource?, secondary_storage?, advanced_permissions? }`. | +| `git_sync` | `{ repositories: [...] }`, each with `git_repo_resource_path`, `script_path` and `settings` (include/exclude paths and types). Server-owned fields (webhook secrets, sync state, credentials) are never read nor written. | +| `datatable` | `{ datatables: { <name>: { database: { resource_type, resource_path? } } } }`. Role permissions are `datatable_permissions`. | +| `datatable_permissions` | `{ <data table>: { default_role, roles: { <role>: [tenants] } } }`: who may connect to each data table as which role. Tenants are `u/<user>`, `g/<group>`, `f/<folder>` or `*`; `admin` is always a role, and `default_role: null` means no default. A data table the value omits is no longer under roles. Only a data table on a cluster Windmill manages can be. | +| `protection_rules` | `{ <rule name>: { rules: [...], bypass_groups: [...], bypass_users: [...] } }`, rules among `DisableDirectDeployment`, `DisableWorkspaceForking`, `RestrictDeployToDeployers`, `RestrictAnonymousAppDeployment`, `RestrictPublicRunSharing`, `RestrictGuestAppDeployment`, `RequireIsolatedForks`. A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. | +| `ducklake` | `{ ducklakes: { <name>: { catalog, storage, ... } } }`. | +| `dbt_warehouses` | dbt warehouse connections. | +| `default_app` | Path of the app shown as the workspace home. | +| `default_scripts` | `{ order?, hidden?, default_script_content? }` for the script language picker. | +| `deploy_ui` | `{ include_path?, include_type? }`: what the deploy-to-workspace UI offers. | +| `operator_settings` | What operators see and do: page visibility flags (`runs`, `schedules`, `resources`, `variables`, `assets`, `audit_logs`, `groups`, `folders`, `workers`, `triggers`) and write rights (`manage_schedules`, `manage_triggers`, `builder_flows`, `builder_apps`). A write right the value omits keeps its stored value. | +| `mute_critical_alerts` | Mute the workspace's critical alerts. | +| `slack_team_id`, `slack_name` | Read only: set by connecting Slack on the settings page. | +| `slack_command_script` / `teams_command_script` | Script or flow handling the Slack / Teams command. | +| `slack_oauth_client_id` / `slack_oauth_client_secret` | The workspace's own Slack OAuth app. Clearing either removes both. | +| `public_app_execution_limit_per_minute` | Rate limit for public apps, `null` for none. | +| `guest_access_enabled`, `guest_jwt_public_key`, `guest_jwt_jwks_url` | Guest access to public apps and the key that signs guest JWTs. | +| `add_admins_and_developers_to_forks` | Add the workspace's admins and developers to each fork. | +| `color` | Workspace color, `#rrggbb`. | + +## From the command line + +`wmill workspace get-settings` prints the document (`--encrypted` for secrets encrypted with the +workspace key, `--json` for JSON). `wmill workspace apply-settings <file>` applies a partial +document from a YAML or JSON file: it shows the changes and asks before writing (`--dry-run` to +only show them, `-y` to skip the question, `--replace` to clear what the file omits). + +## In a synced repository + +With `includeSettings: true` in `wmill.yaml`, `wmill sync pull` writes the document to +`settings.yaml`, secrets encrypted with the workspace key (plaintext only with `plainSecrets`), and +`wmill sync push` applies it. Unlike a partial apply, a push treats the file as the whole +document: a setting the file omits is cleared, except `operator_settings`, `color`, the auto-invite +instance groups, and the keys `ducklake`, `dbt_warehouses`, `deploy_ui`, `teams_command_script`, +`public_app_execution_limit_per_minute`, `guest_access_enabled`, `guest_jwt_public_key`, +`guest_jwt_jwks_url`, `error_handler_fallback_to_instance_alerts` and +`add_admins_and_developers_to_forks`, which are managed only when the file states them. +`datatable_permissions` is pushed only with `includeDatatablePermissions: true` (or +`--include-datatable-permissions`). A push ignores `protection_rules`: `protection-rules.yaml` and +`wmill protection-rules push` sync them. diff --git a/system_prompts/auto-generated/skills/write-flow/SKILL.md b/system_prompts/auto-generated/skills/write-flow/SKILL.md index 4b0889c3d8..906f416184 100644 --- a/system_prompts/auto-generated/skills/write-flow/SKILL.md +++ b/system_prompts/auto-generated/skills/write-flow/SKILL.md @@ -236,6 +236,10 @@ needs becomes unreachable. references. A spread, a call or a computed key leaves the composer unable to tell which input feeds which field, so it offers no control at all — a bare `flow_input.x` for the whole object is read instead as that one input carrying every field +- A step linked to a saved agent (`agent` set) has no `provider` of its own. It exposes the same + two controls through its `model` and `reasoning_effort` inputs, which replace what the agent + saved: `"model": { "type": "javascript", "expr": "flow_input.model" }`. An empty model keeps the + saved one, an empty effort sends none, and the provider resource always stays the agent's - `memory` is what lets the agent see earlier turns; without it every message starts from nothing - `streaming` on makes the answer and its thinking appear token by token instead of all at once - `user_attachments` points at a flow input typed as an array of s3 objects @@ -671,6 +675,14 @@ In the flow schema, set the property type to `"object"` with format `"resource-{ } ``` +### When No Resource Type Fits + +A connection still comes in as one resource input, not as separate string inputs (a URL, a token) or a variable read inside a step: type the input `resource-c_<name>` with a custom resource type holding the service's connection fields, its secret in a variable the resource references. The `c_` prefix of custom types keeps one apart from a hub type synced later under the same name. + +- If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. +- Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it. +- A plain variable is fine when the user asks for it. + ### As Step Input (Static Reference) Reference a specific resource using `$res:` prefix: @@ -686,4 +698,4 @@ Reference a specific resource using `$res:` prefix: ## OpenFlow Schema -{"OpenFlow":{"type":"object","description":"Top-level flow definition containing metadata, configuration, and the flow structure","properties":{"summary":{"type":"string","description":"Short description of what this flow does"},"description":{"type":"string","description":"Detailed documentation for this flow"},"value":{"$ref":"#/components/schemas/FlowValue"},"schema":{"type":"object","description":"JSON Schema for flow inputs. Use this to define input parameters, their types, defaults, and validation. For resource inputs, set type to 'object' and format to 'resource-<type>' (e.g., 'resource-stripe')"},"on_behalf_of_email":{"type":"string","description":"Address of the account the flow runs on behalf of. Derived from on_behalf_of on read; accepted on write, where it is resolved to the account it names."},"on_behalf_of":{"type":"string","description":"The flow runs with the permissions of this identity: u/{username}, g/{group}, or a bare email when the username is itself email-shaped. The only stored half of the identity; on_behalf_of_email is derived from it. Omit it when writing and it is resolved from that address instead."}},"required":["summary","value"]},"FlowValue":{"type":"object","description":"The flow structure containing modules and optional preprocessor/failure handlers","properties":{"modules":{"type":"array","description":"Array of steps that execute in sequence. Each step can be a script, subflow, loop, or branch","items":{"$ref":"#/components/schemas/FlowModule"}},"failure_module":{"description":"Special module that executes when the flow fails. Receives error object with message, name, stack, and step_id. Must have id 'failure'. Only supports script/rawscript types","$ref":"#/components/schemas/FlowModule"},"preprocessor_module":{"description":"Special module that runs before the first step on external triggers. Must have id 'preprocessor'. Only supports script/rawscript types. Cannot reference other step results","$ref":"#/components/schemas/FlowModule"},"same_worker":{"type":"boolean","description":"If true, all steps run on the same worker for better performance"},"preserve_step_tags":{"type":"boolean","description":"If true and the flow runs on a custom worker tag, steps that declare their own non-empty tag run on it instead of inheriting the flow tag. Steps without their own tag still inherit the flow tag."},"concurrent_limit":{"type":"number","description":"Maximum number of concurrent executions of this flow"},"concurrency_key":{"type":"string","description":"Expression to group concurrent executions (e.g., by user ID)"},"concurrency_time_window_s":{"type":"number","description":"Time window in seconds for concurrent_limit"},"debounce_delay_s":{"type":"integer","description":"Delay in seconds to debounce flow executions"},"debounce_key":{"type":"string","description":"Expression to group debounced executions"},"debounce_args_to_accumulate":{"type":"array","description":"Arguments to accumulate across debounced executions","items":{"type":"string"}},"max_total_debouncing_time":{"type":"integer","description":"Maximum total time in seconds that a job can be debounced"},"max_total_debounces_amount":{"type":"integer","description":"Maximum number of times a job can be debounced"},"skip_expr":{"type":"string","description":"JavaScript expression to conditionally skip the entire flow"},"cache_ttl":{"type":"number","description":"Cache duration in seconds for flow results"},"cache_ignore_s3_path":{"type":"boolean"},"delete_after_secs":{"type":"integer","description":"If set, delete the flow job's args, result and logs after this many seconds following job completion"},"flow_env":{"type":"object","description":"Environment variables available to all steps. Values can be strings, JSON values, or special references: '$var:path' (workspace variable) or '$res:path' (resource).","additionalProperties":{}},"priority":{"type":"number","description":"Execution priority (higher numbers run first)"},"early_return":{"type":"string","description":"JavaScript expression to return early from the flow"},"chat_input_enabled":{"type":"boolean","description":"Whether this flow accepts chat-style input"},"notes":{"type":"array","description":"Sticky notes attached to the flow","items":{"$ref":"#/components/schemas/FlowNote"}},"groups":{"type":"array","description":"Semantic groups of modules for organizational purposes","items":{"$ref":"#/components/schemas/FlowGroup"}}},"required":["modules"]},"Retry":{"type":"object","description":"Retry configuration for failed module executions","properties":{"constant":{"type":"object","description":"Retry with constant delay between attempts","properties":{"attempts":{"type":"integer","description":"Number of retry attempts"},"seconds":{"type":"integer","description":"Seconds to wait between retries"}}},"exponential":{"type":"object","description":"Retry with exponential backoff: the n-th retry waits multiplier \u00d7 seconds^n","properties":{"attempts":{"type":"integer","description":"Number of retry attempts"},"multiplier":{"type":"integer","description":"Multiplier for exponential backoff"},"seconds":{"type":"integer","minimum":1,"description":"Base of the exponential (seconds); the n-th retry waits multiplier \u00d7 seconds^n, where n counts constant retries too"},"random_factor":{"type":"integer","minimum":0,"maximum":100,"description":"Random jitter percentage (0-100) to avoid thundering herd"}}},"retry_if":{"$ref":"#/components/schemas/RetryIf"}}},"FlowNote":{"type":"object","description":"A sticky note attached to a flow for documentation and annotation","properties":{"id":{"type":"string","description":"Unique identifier for the note"},"text":{"type":"string","description":"Content of the note"},"position":{"type":"object","description":"Position of the note in the flow editor","properties":{"x":{"type":"number","description":"X coordinate"},"y":{"type":"number","description":"Y coordinate"}},"required":["x","y"]},"size":{"type":"object","description":"Size of the note in the flow editor","properties":{"width":{"type":"number","description":"Width in pixels"},"height":{"type":"number","description":"Height in pixels"}},"required":["width","height"]},"color":{"type":"string","description":"Color of the note, one of: yellow, blue, green, purple, pink, orange, red, cyan, lime, gray. Any other value renders unstyled."},"type":{"type":"string","enum":["free","group"],"description":"Type of note - 'free' for standalone notes. 'group' notes are deprecated; segment a flow with FlowValue.groups instead."},"locked":{"type":"boolean","default":false,"description":"Whether the note is locked and cannot be edited or moved"},"contained_node_ids":{"type":"array","items":{"type":"string"},"description":"For group notes, the IDs of nodes contained within this group"}},"required":["id","text","color","type"]},"FlowGroup":{"type":"object","description":"A semantic group of flow modules for organizational purposes. Does not affect execution \u2014 modules remain in their original position in the flow. Groups provide naming and collapsibility in the editor. Members are computed dynamically from all nodes on paths between start_id and end_id.","properties":{"summary":{"type":"string","description":"Display name for this group"},"note":{"type":"string","description":"Markdown note shown below the group header"},"autocollapse":{"type":"boolean","default":false,"description":"If true, this group is collapsed by default in the flow editor. UI hint only."},"start_id":{"type":"string","description":"ID of the first flow module in this group (topological entry point)"},"end_id":{"type":"string","description":"ID of the last flow module in this group (topological exit point)"},"color":{"type":"string","description":"Color for the group in the flow editor, one of: yellow, blue, green, purple, pink, orange, red, cyan, lime, gray. Omit it to let the editor pick one."}},"required":["start_id","end_id"]},"RetryIf":{"type":"object","description":"Conditional retry based on error or result","properties":{"expr":{"type":"string","description":"JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables"}},"required":["expr"]},"StopAfterIf":{"type":"object","description":"Early termination condition for a module","properties":{"skip_if_stopped":{"type":"boolean","description":"If true, following steps are skipped when this condition triggers"},"expr":{"type":"string","description":"JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"},"error_message":{"type":"string","nullable":true,"description":"Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised."},"error_include_result":{"type":"boolean","description":"When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false."}},"required":["expr"]},"FlowModule":{"type":"object","description":"A single step in a flow. Can be a script, subflow, loop, or branch","properties":{"id":{"type":"string","description":"Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"},"value":{"$ref":"#/components/schemas/FlowModuleValue"},"stop_after_if":{"description":"Early termination condition evaluated after this step completes","$ref":"#/components/schemas/StopAfterIf"},"stop_after_all_iters_if":{"description":"For loops only - early termination condition evaluated after all iterations complete","$ref":"#/components/schemas/StopAfterIf"},"skip_if":{"type":"object","description":"Conditionally skip this step based on previous results or flow inputs","properties":{"expr":{"type":"string","description":"JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.<step_id>'"}},"required":["expr"]},"sleep":{"description":"Delay before executing this step (in seconds or as expression)","$ref":"#/components/schemas/InputTransform"},"cache_ttl":{"type":"number","description":"Cache duration in seconds for this step's results"},"cache_ignore_s3_path":{"type":"boolean"},"timeout":{"description":"Maximum execution time in seconds (static value or expression)","$ref":"#/components/schemas/InputTransform"},"delete_after_secs":{"type":"integer","description":"If set, delete the step's args, result and logs after this many seconds following job completion"},"summary":{"type":"string","description":"Short description of what this step does"},"mock":{"type":"object","description":"Mock configuration for testing without executing the actual step","properties":{"enabled":{"type":"boolean","description":"If true, return mock value instead of executing"},"return_value":{"description":"Value to return when mocked"}}},"suspend":{"type":"object","description":"Configuration for approval/resume steps that wait for user input","properties":{"required_events":{"type":"integer","description":"Number of approvals required before continuing"},"timeout":{"type":"integer","description":"Timeout in seconds before auto-continuing or canceling"},"resume_form":{"type":"object","description":"Form schema for collecting input when resuming","properties":{"schema":{"type":"object","description":"JSON Schema for the resume form"}}},"user_auth_required":{"type":"boolean","description":"If true, only authenticated users can approve"},"user_groups_required":{"description":"Expression or list of groups that can approve","$ref":"#/components/schemas/InputTransform"},"self_approval_disabled":{"type":"boolean","description":"If true, the user who started the flow cannot approve"},"hide_cancel":{"type":"boolean","description":"If true, hide the cancel button on the approval form"},"continue_on_disapprove_timeout":{"type":"boolean","description":"If true, continue flow on timeout instead of canceling"},"skin":{"type":"string","enum":["detailed","minimal"],"description":"How the approval request is presented, on the approval page and in Slack/Teams approval messages. 'detailed' (used when unset) shows the flow details (arguments, graph, approvers); 'minimal' shows only the request: the step description, form and approve/reject actions"}}},"priority":{"type":"number","description":"Execution priority for this step (higher numbers run first)"},"continue_on_error":{"type":"boolean","description":"If true, flow continues even if this step fails"},"job_token_scopes":{"type":"array","nullable":true,"items":{"type":"string"},"description":"Scopes the token of this step's jobs is restricted to (domain:action[:resource], e.g. oidc:write), on top of the flow's own restriction: a step can only narrow it. Applies to everything the step runs (loop and branch bodies, AI agent tools)."},"retry":{"description":"Retry configuration if this step fails","$ref":"#/components/schemas/Retry"},"debouncing":{"description":"Debounce configuration for this step (EE only)","type":"object","properties":{"debounce_delay_s":{"type":"integer","description":"Delay in seconds to debounce this step's executions across flow runs"},"debounce_key":{"type":"string","description":"Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/<flow_path>-<step_id>"},"debounce_args_to_accumulate":{"type":"array","description":"Array-type arguments to accumulate across debounced executions","items":{"type":"string"}},"max_total_debouncing_time":{"type":"integer","description":"Maximum total time in seconds before forced execution"},"max_total_debounces_amount":{"type":"integer","description":"Maximum number of debounces before forced execution"}}}},"required":["value","id"]},"InputTransform":{"description":"Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs","oneOf":[{"$ref":"#/components/schemas/StaticTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type","mapping":{"static":"#/components/schemas/StaticTransform","javascript":"#/components/schemas/JavascriptTransform","ai":"#/components/schemas/AiTransform"}}},"StaticTransform":{"type":"object","description":"Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'","properties":{"value":{"description":"The static value. For resources, use format '$res:path/to/resource'"},"type":{"type":"string","enum":["static"]}},"required":["type"]},"JavascriptTransform":{"type":"object","description":"JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')","properties":{"expr":{"type":"string","description":"JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"},"type":{"type":"string","enum":["javascript"]}},"required":["expr","type"]},"AiTransform":{"type":"object","description":"Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.","properties":{"type":{"type":"string","enum":["ai"]}},"required":["type"]},"AIProviderKind":{"type":"string","description":"Supported AI provider types","enum":["openai","azure_openai","azure_foundry","anthropic","mistral","deepseek","googleai","groq","openrouter","togetherai","customai","aws_bedrock","typesafe","cloudflare"]},"ProviderConfig":{"type":"object","description":"Complete AI provider configuration with resource reference and model selection","properties":{"kind":{"$ref":"#/components/schemas/AIProviderKind"},"resource":{"type":"string","description":"Resource reference in format '$res:{resource_path}' pointing to provider credentials"},"model":{"type":"string","description":"Model identifier (e.g., 'gpt-4', 'claude-3-opus-20240229', 'gemini-pro')"},"reasoning_effort":{"type":"string","description":"Provider-native reasoning effort token (e.g. 'low', 'high', 'none') for models that support extended thinking. Optional; unset leaves the provider default."}},"required":["kind","resource","model"]},"StaticProviderTransform":{"type":"object","description":"Static provider configuration passed directly to the AI agent","properties":{"value":{"$ref":"#/components/schemas/ProviderConfig"},"type":{"type":"string","enum":["static"]}},"required":["type","value"]},"ProviderTransform":{"description":"Provider configuration - can be static (ProviderConfig), JavaScript expression, or AI-determined","oneOf":[{"$ref":"#/components/schemas/StaticProviderTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type","mapping":{"static":"#/components/schemas/StaticProviderTransform","javascript":"#/components/schemas/JavascriptTransform","ai":"#/components/schemas/AiTransform"}}},"MemoryOff":{"type":"object","description":"No conversation memory/context","properties":{"kind":{"type":"string","enum":["off"]}},"required":["kind"]},"MemoryWindow":{"type":"object","description":"Keeps the most recent messages of the memory named by the run's memory id (or the step's\n`memory_id`). Without a memory id the agent runs without memory.\n","properties":{"kind":{"type":"string","enum":["window"]},"context_length":{"type":"integer","description":"Number of most recent messages to load and store. 0 turns memory off."}},"required":["kind","context_length"]},"MemoryAuto":{"type":"object","deprecated":true,"description":"Deprecated, still read as it was written: the run's memory id, else the `memory_id` here.\nThe step's own `memory_id` is not read while this kind is set; switch the kind to `window`\nto use it. Without a `context_length`, or with 0, it is `off` and reads `previous_messages`.\n","properties":{"kind":{"type":"string","enum":["auto"]},"context_length":{"type":"integer","description":"Maximum number of messages to retain in context"},"memory_id":{"type":"string","description":"Identifier for persistent memory across agent invocations"}},"required":["kind"]},"MemoryCompaction":{"type":"object","description":"Keeps the whole memory named by the run's memory id (or the step's `memory_id`), replacing\nits older part with a summary as the conversation approaches the model's context window.\nWithout a memory id the agent runs without memory, and compaction bounds the run's own loop.\n","properties":{"kind":{"type":"string","enum":["compaction"]},"context_window":{"type":"integer","description":"Overrides the context window looked up from the model, in tokens. Only a model\nWindmill does not know needs one; those fall back to 128000.\n"}},"required":["kind"]},"MemoryMessage":{"type":"object","description":"A single message in conversation history","properties":{"role":{"type":"string","enum":["user","assistant","system"]},"content":{"type":"string"}},"required":["role","content"]},"MemoryManual":{"type":"object","deprecated":true,"description":"Deprecated, still read as it was written. Move the step to `off` with `previous_messages` instead.","properties":{"kind":{"type":"string","enum":["manual"]},"messages":{"type":"array","items":{"$ref":"#/components/schemas/MemoryMessage"}}},"required":["kind","messages"]},"MemoryConfig":{"description":"Managed memory, stored by Windmill and replayed with each request. The memory is named by a memory id, see `memory_id`. While it is off, a step can supply its history in `previous_messages`.","oneOf":[{"$ref":"#/components/schemas/MemoryOff"},{"$ref":"#/components/schemas/MemoryWindow"},{"$ref":"#/components/schemas/MemoryCompaction"},{"$ref":"#/components/schemas/MemoryAuto"},{"$ref":"#/components/schemas/MemoryManual"}],"discriminator":{"propertyName":"kind","mapping":{"off":"#/components/schemas/MemoryOff","window":"#/components/schemas/MemoryWindow","compaction":"#/components/schemas/MemoryCompaction","auto":"#/components/schemas/MemoryAuto","manual":"#/components/schemas/MemoryManual"}}},"StaticMemoryTransform":{"type":"object","description":"Static memory configuration passed directly to the AI agent","properties":{"value":{"$ref":"#/components/schemas/MemoryConfig"},"type":{"type":"string","enum":["static"]}},"required":["type","value"]},"MemoryTransform":{"description":"Memory configuration - can be static (MemoryConfig), JavaScript expression, or AI-determined","oneOf":[{"$ref":"#/components/schemas/StaticMemoryTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type","mapping":{"static":"#/components/schemas/StaticMemoryTransform","javascript":"#/components/schemas/JavascriptTransform","ai":"#/components/schemas/AiTransform"}}},"FlowModuleValue":{"description":"The actual implementation of a flow step. Can be a script (inline or referenced), subflow, loop, branch, or special module type","oneOf":[{"$ref":"#/components/schemas/RawScript"},{"$ref":"#/components/schemas/PathScript"},{"$ref":"#/components/schemas/PathFlow"},{"$ref":"#/components/schemas/ForloopFlow"},{"$ref":"#/components/schemas/WhileloopFlow"},{"$ref":"#/components/schemas/BranchOne"},{"$ref":"#/components/schemas/BranchAll"},{"$ref":"#/components/schemas/Identity"},{"$ref":"#/components/schemas/AiAgent"},{"$ref":"#/components/schemas/AiDecision"}],"discriminator":{"propertyName":"type","mapping":{"rawscript":"#/components/schemas/RawScript","script":"#/components/schemas/PathScript","flow":"#/components/schemas/PathFlow","forloopflow":"#/components/schemas/ForloopFlow","whileloopflow":"#/components/schemas/WhileloopFlow","branchone":"#/components/schemas/BranchOne","branchall":"#/components/schemas/BranchAll","identity":"#/components/schemas/Identity","aiagent":"#/components/schemas/AiAgent","aidecision":"#/components/schemas/AiDecision"}}},"RawScript":{"type":"object","description":"Inline script with code defined directly in the flow. Use 'bun' as default language if unspecified. The script receives arguments from input_transforms","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"content":{"type":"string","description":"The script source code. Should export a 'main' function"},"language":{"type":"string","description":"Programming language for this script","enum":["deno","bun","bunnative","python3","go","bash","powershell","postgresql","mysql","bigquery","snowflake","mssql","oracledb","graphql","nativets","php","rust","ansible","csharp","nu","java","ruby","rlang","duckdb"]},"path":{"type":"string","description":"Optional path for saving this script"},"lock":{"type":"string","description":"Lock file content for dependencies"},"type":{"type":"string","enum":["rawscript"]},"tag":{"type":"string","description":"Worker group tag for execution routing"},"concurrent_limit":{"type":"number","description":"Maximum concurrent executions of this script"},"concurrency_time_window_s":{"type":"number","description":"Time window for concurrent_limit"},"custom_concurrency_key":{"type":"string","description":"Custom key for grouping concurrent executions"},"is_trigger":{"type":"boolean","description":"If true, this script is a trigger that can start the flow"},"assets":{"type":"array","description":"External resources this script accesses (S3 objects, resources, etc.)","items":{"type":"object","required":["path","kind"],"properties":{"path":{"type":"string","description":"Path to the asset"},"kind":{"type":"string","description":"Type of asset","enum":["s3object","resource","ducklake","datatable","volume","dbt"]},"access_type":{"type":"string","nullable":true,"description":"Access level for this asset","enum":["r","w","rw"]},"alt_access_type":{"type":"string","nullable":true,"description":"Alternative access level","enum":["r","w","rw"]}}}}},"required":["type","content","language","input_transforms"]},"PathScript":{"type":"object","description":"Reference to an existing script by path. Use this when calling a previously saved script instead of writing inline code","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"path":{"type":"string","description":"Path to the script in the workspace (e.g., 'f/scripts/send_email')"},"hash":{"type":"string","description":"Optional specific version hash of the script to use"},"type":{"type":"string","enum":["script"]},"tag_override":{"type":"string","description":"Override the script's default worker group tag"},"is_trigger":{"type":"boolean","description":"If true, this script is a trigger that can start the flow"}},"required":["type","path","input_transforms"]},"PathFlow":{"type":"object","description":"Reference to an existing flow by path. Use this to call another flow as a subflow","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the subflow's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"path":{"type":"string","description":"Path to the flow in the workspace (e.g., 'f/flows/process_user')"},"type":{"type":"string","enum":["flow"]}},"required":["type","path","input_transforms"]},"ForloopFlow":{"type":"object","description":"Executes nested modules in a loop over an iterator. Inside the loop, use 'flow_input.iter.value' to access the current iteration value, and 'flow_input.iter.index' for the index. Supports parallel execution for better performance on I/O-bound operations","properties":{"modules":{"type":"array","description":"Steps to execute for each iteration. These can reference the iteration value via 'flow_input.iter.value'","items":{"$ref":"#/components/schemas/FlowModule"}},"iterator":{"description":"JavaScript expression that returns an array to iterate over. Can reference 'results.step_id' or 'flow_input'","$ref":"#/components/schemas/InputTransform"},"skip_failures":{"type":"boolean","description":"If true, iteration failures don't stop the loop. Failed iterations return null"},"type":{"type":"string","enum":["forloopflow"]},"parallel":{"type":"boolean","description":"If true, iterations run concurrently (faster for I/O-bound operations). Use with parallelism to control concurrency"},"parallelism":{"description":"Maximum number of concurrent iterations when parallel=true. Limits resource usage. Can be static number or expression","$ref":"#/components/schemas/InputTransform"},"squash":{"type":"boolean"}},"required":["modules","iterator","skip_failures","type"]},"WhileloopFlow":{"type":"object","description":"Executes nested modules repeatedly until stopped. The implicit iterator is the iteration counter, so 'flow_input.iter.value' equals 'flow_input.iter.index' (0, 1, 2, ...) and never carries state. To carry state across iterations, a step reads its own previous-iteration result via 'results.<its_own_id>' with a first-iteration fallback - the loop's stop_after_if must then be on that inner step (a plain single-step body with stop_after_if on the loop module does not resolve 'results' across iterations and never terminates); plain counters can instead be derived from 'flow_input.iter.index', which works in every configuration. stop_after_if is evaluated after each iteration - on the loop module 'result' is the last iteration's result","properties":{"modules":{"type":"array","description":"Steps to execute in each iteration","items":{"$ref":"#/components/schemas/FlowModule"}},"skip_failures":{"type":"boolean","description":"If true, iteration failures don't stop the loop. Failed iterations return null"},"type":{"type":"string","enum":["whileloopflow"]},"parallel":{"type":"boolean","description":"If true, iterations run concurrently (use with caution in while loops)"},"parallelism":{"description":"Maximum number of concurrent iterations when parallel=true","$ref":"#/components/schemas/InputTransform"},"squash":{"type":"boolean"}},"required":["modules","skip_failures","type"]},"BranchOne":{"type":"object","description":"Conditional branching where only the first matching branch executes. Branches are evaluated in order, and the first one with a true expression runs. If no branches match, the default branch executes","properties":{"branches":{"type":"array","description":"Array of branches to evaluate in order. The first branch with expr evaluating to true executes","items":{"type":"object","properties":{"summary":{"type":"string","description":"Short description of this branch condition"},"expr":{"type":"string","description":"JavaScript expression that returns boolean. Can use 'results.step_id' or 'flow_input'. First true expr wins"},"modules":{"type":"array","description":"Steps to execute if this branch's expr is true","items":{"$ref":"#/components/schemas/FlowModule"}}},"required":["modules","expr"]}},"default":{"type":"array","description":"Steps to execute if no branch expressions match","items":{"$ref":"#/components/schemas/FlowModule"}},"type":{"type":"string","enum":["branchone"]}},"required":["branches","default","type"]},"BranchAll":{"type":"object","description":"Parallel branching where all branches execute simultaneously. Unlike BranchOne, all branches run regardless of conditions. Useful for executing independent tasks concurrently","properties":{"branches":{"type":"array","description":"Array of branches that all execute (either in parallel or sequentially)","items":{"type":"object","properties":{"summary":{"type":"string","description":"Short description of this branch's purpose"},"skip_failure":{"type":"boolean","description":"If true, failure in this branch doesn't fail the entire flow"},"modules":{"type":"array","description":"Steps to execute in this branch","items":{"$ref":"#/components/schemas/FlowModule"}}},"required":["modules"]}},"type":{"type":"string","enum":["branchall"]},"parallel":{"type":"boolean","description":"If true, all branches execute concurrently. If false, they execute sequentially"}},"required":["branches","type"]},"AgentTool":{"type":"object","description":"A tool available to an AI agent. Can be a flow module or an external MCP (Model Context Protocol) tool","properties":{"id":{"type":"string","description":"Unique identifier for this tool. Cannot contain spaces - use underscores instead (e.g., 'get_user_data' not 'get user data')"},"summary":{"type":"string","description":"The name the AI agent calls this tool by, not a human label. On a flowmodule tool it must match ^[a-zA-Z0-9_]+$ - letters, numbers and underscores only (e.g. 'search_documentation', not 'Search documentation') - and always be set; on an mcp or websearch tool it is a plain label. Put the human-readable explanation in 'description'."},"description":{"type":"string","description":"Free-text description of the tool given to the AI to decide when and how to call it. Overrides the description auto-derived from the underlying script."},"job_token_scopes":{"type":"array","nullable":true,"items":{"type":"string"},"description":"Scopes the token of this tool's jobs is restricted to, on top of the agent step's own restriction: a tool can only narrow it."},"value":{"$ref":"#/components/schemas/ToolValue"}},"required":["id","value"]},"ToolValue":{"description":"The implementation of a tool. Can be a flow module (script/flow) or an MCP tool reference","oneOf":[{"$ref":"#/components/schemas/FlowModuleTool"},{"$ref":"#/components/schemas/McpToolValue"},{"$ref":"#/components/schemas/WebsearchToolValue"}],"discriminator":{"propertyName":"tool_type","mapping":{"flowmodule":"#/components/schemas/FlowModuleTool","mcp":"#/components/schemas/McpToolValue","websearch":"#/components/schemas/WebsearchToolValue"}}},"FlowModuleTool":{"description":"A tool implemented as a flow module (script, flow, etc.). The AI can call this like any other flow module","allOf":[{"type":"object","properties":{"tool_type":{"type":"string","enum":["flowmodule"]}},"required":["tool_type"]},{"$ref":"#/components/schemas/FlowModuleValue"}]},"WebsearchToolValue":{"type":"object","description":"A tool implemented as a websearch tool. The AI can call this like any other websearch tool","properties":{"tool_type":{"type":"string","enum":["websearch"]}},"required":["tool_type"]},"McpToolValue":{"type":"object","description":"Reference to an external MCP (Model Context Protocol) tool. The AI can call tools from MCP servers","properties":{"tool_type":{"type":"string","enum":["mcp"]},"resource_path":{"type":"string","description":"Path to the MCP resource/server configuration"},"include_tools":{"type":"array","description":"Whitelist of specific tools to include from this MCP server","items":{"type":"string"}},"exclude_tools":{"type":"array","description":"Blacklist of tools to exclude from this MCP server","items":{"type":"string"}}},"required":["tool_type","resource_path"]},"AiAgent":{"type":"object","description":"AI agent step that can use tools to accomplish tasks. The agent receives inputs and can call any of its configured tools to complete the task","properties":{"input_transforms":{"type":"object","description":"Input parameters for the AI agent mapped to their values","properties":{"provider":{"$ref":"#/components/schemas/ProviderTransform"},"output_type":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Output format type.\nValid values: 'text' (default) - plain text response, 'image' - image generation\n"},"user_message":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"The user's prompt/message to the AI agent. Supports variable interpolation with\nflow.input syntax. Required unless memory is off and `previous_messages` supplies\nthe prompt; image output always needs it.\n"},"system_prompt":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"System instructions that guide the AI's behavior, persona, and response style. Optional."},"streaming":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Boolean. If true, stream the AI response incrementally.\nStreaming events include: token_delta, reasoning_token_delta, tool_call, tool_call_arguments, tool_execution, tool_result\n"},"memory":{"$ref":"#/components/schemas/MemoryTransform"},"memory_id":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"String. Names the memory this step reads and writes, overriding the memory id the run\nwas started with (the chat conversation, an app chat session or the `memory_id` run\nparameter). Leave unset to use the run's memory id. A fixed value shares one memory\nacross every run; an expression such as `flow_input.customer_id` keeps one memory per\nkey. When it evaluates to an empty value the agent runs without memory. Read only\nwhile `memory` is `window` or `compaction`: it is ignored when memory is off, and an\nolder `auto` or `manual` memory reads neither history input.\n"},"previous_messages":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Array of MemoryMessage. History supplied by the flow, sent between the system prompt\nand the user message. Read only while `memory` is off or absent: managed memory\nignores it, and an older `auto` or `manual` memory reads neither history input.\n"},"output_schema":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"JSON Schema object defining structured output format. Used when you need the AI to return data in a specific shape.\nSupports standard JSON Schema properties: type, properties, required, items, enum, pattern, minLength, maxLength, minimum, maximum, etc.\nExample: { type: 'object', properties: { name: { type: 'string' }, age: { type: 'integer' } }, required: ['name'] }\n"},"user_attachments":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Array of file references (images or PDFs) for the AI agent.\nFormat: Array<{ bucket: string, key: string }> - S3 object references\nExample: [{ bucket: 'my-bucket', key: 'documents/report.pdf' }]\n"},"enabled_tools":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Array of strings naming which of the tools configured in `tools` the agent may call\nthis run. Leaving it unset carries every one of them; an empty array carries none.\nA tool is named as the model is shown it. An entry the model is shown nothing of is\nnamed by what identifies it instead: an MCP server by its resource path, carrying\nevery tool it exposes (which of them stays that entry's include_tools/exclude_tools),\nand a websearch entry by the reserved name '__wm_web_search', whatever summary it carries\n(no tool may take that name).\nExample: ['get_user', 'u/admin/github_mcp', '__wm_web_search']\n"},"max_completion_tokens":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Integer. Maximum number of tokens the AI will generate in its response.\nRange: 1 to 4,294,967,295. Typical values: 256-4096 for most use cases.\n"},"temperature":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Float. Controls randomness/creativity of responses.\nRange: 0.0 to 2.0 (provider-dependent)\n- 0.0 = deterministic, focused responses\n- 0.7 = balanced (common default)\n- 1.0+ = more creative/random\n"},"max_iterations":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Number. Limits how many times the agent can loop through reasoning and tool use.\nRange: 1-1000.\n"}}},"tools":{"type":"array","description":"Array of tools the agent can use. The agent decides which tools to call based on the task","items":{"$ref":"#/components/schemas/AgentTool"}},"type":{"type":"string","enum":["aiagent"]},"tag":{"type":"string","description":"Worker group tag for execution routing. If not set, the AI agent step runs on the flow's tag (default `flow`)"},"omit_output_from_conversation":{"type":"boolean","default":false,"description":"If true, this AI agent step does not persist its assistant or tool messages to the flow conversation when chat mode is enabled."},"agent":{"type":"string","description":"Path of a reusable `ai_agent` resource (hybrid linking). When set, the agent brain\nconfig (provider/model/system prompt/etc.) and tool set are resolved at runtime from\nthat resource; the module's input_transforms then only carry the flow-local inputs\n(user_message, user_attachments, enabled_tools and the history inputs memory_id and previous_messages).\n"},"tool_inputs":{"type":"object","description":"Host-local wiring for an agent's tool inputs, keyed by tool id then input key. Binds the\nreferenced agent's tools to this flow's context (flow_input/results) without mutating the\nshared resource; overlaid onto the tools' input_transforms at runtime \u2014 including when\n`agent` is unset, since a step forked for editing keeps these overrides until it is saved\nback or unlinked.\n","additionalProperties":{"type":"object","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}}},"parallel":{"type":"boolean","description":"If true, the agent can execute multiple tool calls in parallel"}},"required":["type","input_transforms"]},"AiDecision":{"type":"object","description":"AI decision step: one call to a decision model (TypeSafe's Jev, Cloudflare's\nJev-compatible Clef, or OpenAI's Decisions API) that answers typed questions about a\nstate with calibrated probabilities, instead of generating text.\nPrefer it over an AI agent to classify, route, score or check something: it is fast,\ncheap and its answers are structured. Its result is { output: { <question name>: answer },\nmodel, usage }, so a later step reads e.g. results.<id>.output.intent.choice. To route on\nthe answers, follow it with a branchone whose branch exprs read\nresults.<id>.output.<question>.choice. Usable as an AI agent tool, where the calling agent\nsupplies the state.\n","properties":{"input_transforms":{"type":"object","description":"Input parameters for the decision mapped to their values","properties":{"provider":{"$ref":"#/components/schemas/ProviderTransform"},"state":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"What the questions are asked about: a string, an object or an array of strings.\nAn object with descriptive keys holding only what the questions need works best.\nExample: { message: flow_input.message, plan: results.a.plan }\n"},"questions":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Object mapping each question name to { type, instructions, criteria }, where type is:\n- 'choice': criteria maps each option to its description (up to 255); the answer\n has choice, probabilities and confidence\n- 'score': criteria is an ordered array of 2 to 10 level descriptions; the answer\n has score, legend, probabilities and confidence\n- 'noul': yes/no, criteria optionally { true, false } descriptions; the answer has\n noul, the probability of yes (0 to 1)\nExample: { intent: { type: 'choice', instructions: 'What does the customer want?',\ncriteria: { refund: 'Money back', bug: 'Something is broken' } } }\n"}},"required":["provider","state","questions"]},"type":{"type":"string","enum":["aidecision"]},"tag":{"type":"string","description":"Worker group tag for execution routing. If not set, the step runs on the flow's tag (default `flow`)"}},"required":["type","input_transforms"]},"Identity":{"type":"object","description":"Pass-through module that returns its input unchanged. Useful for flow structure or as a placeholder","properties":{"type":{"type":"string","enum":["identity"]},"flow":{"type":"boolean","description":"If true, marks this as a flow identity (special handling)"}},"required":["type"]},"FlowStatus":{"type":"object","properties":{"step":{"type":"integer"},"modules":{"type":"array","items":{"$ref":"#/components/schemas/FlowStatusModule"}},"user_states":{"additionalProperties":true},"preprocessor_module":{"allOf":[{"$ref":"#/components/schemas/FlowStatusModule"}]},"failure_module":{"allOf":[{"$ref":"#/components/schemas/FlowStatusModule"},{"type":"object","properties":{"parent_module":{"type":"string"}}}]},"retry":{"type":"object","properties":{"fail_count":{"type":"integer"},"failed_jobs":{"type":"array","items":{"type":"string","format":"uuid"}}}}},"required":["step","modules","failure_module"]},"FlowStatusModule":{"type":"object","properties":{"type":{"type":"string","enum":["WaitingForPriorSteps","WaitingForEvents","WaitingForExecutor","InProgress","Success","Failure"]},"id":{"type":"string"},"job":{"type":"string","format":"uuid"},"count":{"type":"integer"},"progress":{"type":"integer"},"iterator":{"type":"object","properties":{"index":{"type":"integer"},"itered":{"type":"array","items":{}},"itered_len":{"type":"integer"},"args":{}}},"flow_jobs":{"type":"array","items":{"type":"string"}},"flow_jobs_success":{"type":"array","items":{"type":"boolean"}},"flow_jobs_duration":{"type":"object","properties":{"started_at":{"type":"array","items":{"type":"string"}},"duration_ms":{"type":"array","items":{"type":"integer"}}}},"branch_chosen":{"type":"object","properties":{"type":{"type":"string","enum":["branch","default"]},"branch":{"type":"integer"}},"required":["type"]},"branchall":{"type":"object","properties":{"branch":{"type":"integer"},"len":{"type":"integer"}},"required":["branch","len"]},"approvers":{"type":"array","items":{"type":"object","properties":{"resume_id":{"type":"integer"},"approver":{"type":"string"}},"required":["resume_id","approver"]}},"failed_retries":{"type":"array","items":{"type":"string","format":"uuid"}},"skipped":{"type":"boolean"},"agent_actions":{"type":"array","items":{"type":"object","oneOf":[{"type":"object","properties":{"job_id":{"type":"string","format":"uuid"},"function_name":{"type":"string"},"type":{"type":"string","enum":["tool_call"]},"module_id":{"type":"string"}},"required":["job_id","function_name","type","module_id"]},{"type":"object","properties":{"call_id":{"type":"string","format":"uuid"},"function_name":{"type":"string"},"resource_path":{"type":"string"},"type":{"type":"string","enum":["mcp_tool_call"]},"arguments":{"type":"object"}},"required":["call_id","function_name","resource_path","type"]},{"type":"object","properties":{"type":{"type":"string","enum":["web_search"]}},"required":["type"]},{"type":"object","properties":{"type":{"type":"string","enum":["message"]}},"required":["content","type"]}]}},"agent_actions_success":{"type":"array","items":{"type":"boolean"}}},"required":["type"]}} +{"OpenFlow":{"type":"object","description":"Top-level flow definition containing metadata, configuration, and the flow structure","properties":{"summary":{"type":"string","description":"Short description of what this flow does"},"description":{"type":"string","description":"Detailed documentation for this flow"},"value":{"$ref":"#/components/schemas/FlowValue"},"schema":{"type":"object","description":"JSON Schema for flow inputs. Use this to define input parameters, their types, defaults, and validation. For resource inputs, set type to 'object' and format to 'resource-<type>' (e.g., 'resource-stripe')"},"on_behalf_of_email":{"type":"string","description":"Address of the account the flow runs on behalf of. Derived from on_behalf_of on read; accepted on write, where it is resolved to the account it names."},"on_behalf_of":{"type":"string","description":"The flow runs with the permissions of this identity: u/{username}, g/{group}, or a bare email when the username is itself email-shaped. The only stored half of the identity; on_behalf_of_email is derived from it. Omit it when writing and it is resolved from that address instead."}},"required":["summary","value"]},"FlowValue":{"type":"object","description":"The flow structure containing modules and optional preprocessor/failure handlers","properties":{"modules":{"type":"array","description":"Array of steps that execute in sequence. Each step can be a script, subflow, loop, or branch","items":{"$ref":"#/components/schemas/FlowModule"}},"failure_module":{"description":"Special module that executes when the flow fails. Receives error object with message, name, stack, and step_id. Must have id 'failure'. Only supports script/rawscript types","$ref":"#/components/schemas/FlowModule"},"preprocessor_module":{"description":"Special module that runs before the first step on external triggers. Must have id 'preprocessor'. Only supports script/rawscript types. Cannot reference other step results","$ref":"#/components/schemas/FlowModule"},"same_worker":{"type":"boolean","description":"If true, all steps run on the same worker for better performance"},"preserve_step_tags":{"type":"boolean","description":"If true and the flow runs on a custom worker tag, steps that declare their own non-empty tag run on it instead of inheriting the flow tag. Steps without their own tag still inherit the flow tag."},"concurrent_limit":{"type":"number","description":"Maximum number of concurrent executions of this flow"},"concurrency_key":{"type":"string","description":"Expression to group concurrent executions (e.g., by user ID)"},"concurrency_time_window_s":{"type":"number","description":"Time window in seconds for concurrent_limit"},"debounce_delay_s":{"type":"integer","description":"Delay in seconds to debounce flow executions"},"debounce_key":{"type":"string","description":"Expression to group debounced executions"},"debounce_args_to_accumulate":{"type":"array","description":"Arguments to accumulate across debounced executions","items":{"type":"string"}},"max_total_debouncing_time":{"type":"integer","description":"Maximum total time in seconds that a job can be debounced"},"max_total_debounces_amount":{"type":"integer","description":"Maximum number of times a job can be debounced"},"skip_expr":{"type":"string","description":"JavaScript expression to conditionally skip the entire flow"},"cache_ttl":{"type":"number","description":"Cache duration in seconds for flow results"},"cache_ignore_s3_path":{"type":"boolean"},"delete_after_secs":{"type":"integer","description":"If set, delete the flow job's args, result and logs after this many seconds following job completion"},"flow_env":{"type":"object","description":"Environment variables available to all steps. Values can be strings, JSON values, or special references: '$var:path' (workspace variable) or '$res:path' (resource).","additionalProperties":{}},"priority":{"type":"number","description":"Execution priority (higher numbers run first)"},"early_return":{"type":"string","description":"Id of the step whose result a sync webhook returns as soon as that step completes, while the rest of the flow keeps running. When the step does not run, or fails while the flow has a failure module, the flow's final result is returned instead."},"chat_input_enabled":{"type":"boolean","description":"Whether this flow accepts chat-style input"},"notes":{"type":"array","description":"Sticky notes attached to the flow","items":{"$ref":"#/components/schemas/FlowNote"}},"groups":{"type":"array","description":"Semantic groups of modules for organizational purposes","items":{"$ref":"#/components/schemas/FlowGroup"}}},"required":["modules"]},"Retry":{"type":"object","description":"Retry configuration for failed module executions","properties":{"constant":{"type":"object","description":"Retry with constant delay between attempts","properties":{"attempts":{"type":"integer","description":"Number of retry attempts"},"seconds":{"type":"integer","description":"Seconds to wait between retries"}}},"exponential":{"type":"object","description":"Retry with exponential backoff: the n-th retry waits multiplier \u00d7 seconds^n","properties":{"attempts":{"type":"integer","description":"Number of retry attempts"},"multiplier":{"type":"integer","description":"Multiplier for exponential backoff"},"seconds":{"type":"integer","minimum":1,"description":"Base of the exponential (seconds); the n-th retry waits multiplier \u00d7 seconds^n, where n counts constant retries too"},"random_factor":{"type":"integer","minimum":0,"maximum":100,"description":"Random jitter percentage (0-100) to avoid thundering herd"}}},"retry_if":{"$ref":"#/components/schemas/RetryIf"}}},"FlowNote":{"type":"object","description":"A sticky note attached to a flow for documentation and annotation","properties":{"id":{"type":"string","description":"Unique identifier for the note"},"text":{"type":"string","description":"Content of the note"},"position":{"type":"object","description":"Position of the note in the flow editor","properties":{"x":{"type":"number","description":"X coordinate"},"y":{"type":"number","description":"Y coordinate"}},"required":["x","y"]},"size":{"type":"object","description":"Size of the note in the flow editor","properties":{"width":{"type":"number","description":"Width in pixels"},"height":{"type":"number","description":"Height in pixels"}},"required":["width","height"]},"color":{"type":"string","description":"Color of the note, one of: yellow, blue, green, purple, pink, orange, red, cyan, lime, gray. Any other value renders unstyled."},"type":{"type":"string","enum":["free","group"],"description":"Type of note - 'free' for standalone notes. 'group' notes are deprecated; segment a flow with FlowValue.groups instead."},"locked":{"type":"boolean","default":false,"description":"Whether the note is locked and cannot be edited or moved"},"contained_node_ids":{"type":"array","items":{"type":"string"},"description":"For group notes, the IDs of nodes contained within this group"}},"required":["id","text","color","type"]},"FlowGroup":{"type":"object","description":"A semantic group of flow modules for organizational purposes. Does not affect execution \u2014 modules remain in their original position in the flow. Groups provide naming and collapsibility in the editor. Members are computed dynamically from all nodes on paths between start_id and end_id.","properties":{"summary":{"type":"string","description":"Display name for this group"},"note":{"type":"string","description":"Markdown note shown below the group header"},"autocollapse":{"type":"boolean","default":false,"description":"If true, this group is collapsed by default in the flow editor. UI hint only."},"start_id":{"type":"string","description":"ID of the first flow module in this group (topological entry point)"},"end_id":{"type":"string","description":"ID of the last flow module in this group (topological exit point)"},"color":{"type":"string","description":"Color for the group in the flow editor, one of: yellow, blue, green, purple, pink, orange, red, cyan, lime, gray. Omit it to let the editor pick one."}},"required":["start_id","end_id"]},"RetryIf":{"type":"object","description":"Conditional retry based on error or result","properties":{"expr":{"type":"string","description":"JavaScript expression that returns true to retry. Has access to 'result' and 'error' variables"}},"required":["expr"]},"StopAfterIf":{"type":"object","description":"Early termination condition for a module","properties":{"skip_if_stopped":{"type":"boolean","description":"If true, following steps are skipped when this condition triggers"},"expr":{"type":"string","description":"JavaScript expression evaluated after the module runs. Can use 'result' (step's result) or 'flow_input'. Return true to stop"},"error_message":{"type":"string","nullable":true,"description":"Custom error message when stopping with an error. Mutually exclusive with skip_if_stopped. If set to a non-empty string, the flow stops with this error. If empty string, a default error message is used. If null or omitted, no error is raised."},"error_include_result":{"type":"boolean","description":"When stopping with an error (error_message set), embed the stopping step's own result inside the raised error object (as error.result) instead of discarding it. The top-level result stays { error }. Defaults to false."}},"required":["expr"]},"FlowModule":{"type":"object","description":"A single step in a flow. Can be a script, subflow, loop, or branch","properties":{"id":{"type":"string","description":"Unique identifier for this step. Used to reference results via 'results.step_id'. Must be a valid identifier (alphanumeric, underscore, hyphen)"},"value":{"$ref":"#/components/schemas/FlowModuleValue"},"stop_after_if":{"description":"Early termination condition evaluated after this step completes","$ref":"#/components/schemas/StopAfterIf"},"stop_after_all_iters_if":{"description":"For loops only - early termination condition evaluated after all iterations complete","$ref":"#/components/schemas/StopAfterIf"},"skip_if":{"type":"object","description":"Conditionally skip this step based on previous results or flow inputs","properties":{"expr":{"type":"string","description":"JavaScript expression that returns true to skip. Can use 'flow_input' or 'results.<step_id>'"}},"required":["expr"]},"sleep":{"description":"Delay before executing this step (in seconds or as expression)","$ref":"#/components/schemas/InputTransform"},"cache_ttl":{"type":"number","description":"Cache duration in seconds for this step's results"},"cache_ignore_s3_path":{"type":"boolean"},"timeout":{"description":"Maximum execution time in seconds (static value or expression)","$ref":"#/components/schemas/InputTransform"},"delete_after_secs":{"type":"integer","description":"If set, delete the step's args, result and logs after this many seconds following job completion"},"summary":{"type":"string","description":"Short description of what this step does"},"mock":{"type":"object","description":"Mock configuration for testing without executing the actual step","properties":{"enabled":{"type":"boolean","description":"If true, return mock value instead of executing"},"return_value":{"description":"Value to return when mocked"}}},"suspend":{"type":"object","description":"Configuration for approval/resume steps that wait for user input","properties":{"required_events":{"type":"integer","description":"Number of approvals required before continuing"},"timeout":{"type":"integer","description":"Timeout in seconds before auto-continuing or canceling"},"resume_form":{"type":"object","description":"Form schema for collecting input when resuming","properties":{"schema":{"type":"object","description":"JSON Schema for the resume form"}}},"user_auth_required":{"type":"boolean","description":"If true, only authenticated users can approve"},"user_groups_required":{"description":"Expression or list of groups that can approve","$ref":"#/components/schemas/InputTransform"},"self_approval_disabled":{"type":"boolean","description":"If true, the user who started the flow cannot approve"},"hide_cancel":{"type":"boolean","description":"If true, hide the cancel button on the approval form"},"continue_on_disapprove_timeout":{"type":"boolean","description":"If true, continue flow on timeout instead of canceling"},"skin":{"type":"string","enum":["detailed","minimal"],"description":"How the approval request is presented, on the approval page and in Slack/Teams approval messages. 'detailed' (used when unset) shows the flow details (arguments, graph, approvers); 'minimal' shows only the request: the step description, form and approve/reject actions"}}},"priority":{"type":"number","description":"Execution priority for this step (higher numbers run first)"},"continue_on_error":{"type":"boolean","description":"If true, flow continues even if this step fails"},"job_token_scopes":{"type":"array","nullable":true,"items":{"type":"string"},"description":"Scopes the token of this step's jobs is restricted to (domain:action[:resource], e.g. oidc:write), on top of the flow's own restriction: a step can only narrow it. Applies to everything the step runs (loop and branch bodies, AI agent tools)."},"retry":{"description":"Retry configuration if this step fails","$ref":"#/components/schemas/Retry"},"debouncing":{"description":"Debounce configuration for this step (EE only)","type":"object","properties":{"debounce_delay_s":{"type":"integer","description":"Delay in seconds to debounce this step's executions across flow runs"},"debounce_key":{"type":"string","description":"Expression to group debounced executions. Supports $workspace and $args[name]. Default: $workspace/flow/<flow_path>-<step_id>"},"debounce_args_to_accumulate":{"type":"array","description":"Array-type arguments to accumulate across debounced executions","items":{"type":"string"}},"max_total_debouncing_time":{"type":"integer","description":"Maximum total time in seconds before forced execution"},"max_total_debounces_amount":{"type":"integer","description":"Maximum number of debounces before forced execution"}}}},"required":["value","id"]},"InputTransform":{"description":"Maps input parameters for a step. Can be a static value or a JavaScript expression that references previous results or flow inputs","oneOf":[{"$ref":"#/components/schemas/StaticTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type","mapping":{"static":"#/components/schemas/StaticTransform","javascript":"#/components/schemas/JavascriptTransform","ai":"#/components/schemas/AiTransform"}}},"StaticTransform":{"type":"object","description":"Static value passed directly to the step. Use for hardcoded values or resource references like '$res:path/to/resource'","properties":{"value":{"description":"The static value. For resources, use format '$res:path/to/resource'"},"type":{"type":"string","enum":["static"]}},"required":["type"]},"JavascriptTransform":{"type":"object","description":"JavaScript expression evaluated at runtime. Can reference previous step results via 'results.step_id' or flow inputs via 'flow_input.property'. Inside for loops, use 'flow_input.iter.value' for the current iteration value (in while loops it equals 'flow_input.iter.index')","properties":{"expr":{"type":"string","description":"JavaScript expression returning the value. Available variables - results (object with all previous step results), flow_input (flow inputs), flow_input.iter (in loops)"},"type":{"type":"string","enum":["javascript"]}},"required":["expr","type"]},"AiTransform":{"type":"object","description":"Value resolved by the AI runtime for this input. The AI engine decides how to satisfy the parameter.","properties":{"type":{"type":"string","enum":["ai"]}},"required":["type"]},"AIProviderKind":{"type":"string","description":"Supported AI provider types","enum":["openai","azure_openai","azure_foundry","anthropic","mistral","deepseek","googleai","groq","openrouter","togetherai","customai","aws_bedrock","typesafe","cloudflare"]},"ProviderConfig":{"type":"object","description":"Complete AI provider configuration with resource reference and model selection","properties":{"kind":{"$ref":"#/components/schemas/AIProviderKind"},"resource":{"type":"string","description":"Resource reference in format '$res:{resource_path}' pointing to provider credentials"},"model":{"type":"string","description":"Model identifier (e.g., 'gpt-4', 'claude-3-opus-20240229', 'gemini-pro')"},"reasoning_effort":{"type":"string","description":"Provider-native reasoning effort token (e.g. 'low', 'high', 'none') for models that support extended thinking. Optional; unset leaves the provider default."}},"required":["kind","resource","model"]},"StaticProviderTransform":{"type":"object","description":"Static provider configuration passed directly to the AI agent","properties":{"value":{"$ref":"#/components/schemas/ProviderConfig"},"type":{"type":"string","enum":["static"]}},"required":["type","value"]},"ProviderTransform":{"description":"Provider configuration - can be static (ProviderConfig), JavaScript expression, or AI-determined","oneOf":[{"$ref":"#/components/schemas/StaticProviderTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type","mapping":{"static":"#/components/schemas/StaticProviderTransform","javascript":"#/components/schemas/JavascriptTransform","ai":"#/components/schemas/AiTransform"}}},"MemoryOff":{"type":"object","description":"No conversation memory/context","properties":{"kind":{"type":"string","enum":["off"]}},"required":["kind"]},"MemoryWindow":{"type":"object","description":"Keeps the most recent messages of the memory named by the run's memory id (or the step's\n`memory_id`). Without a memory id the agent runs without memory.\n","properties":{"kind":{"type":"string","enum":["window"]},"context_length":{"type":"integer","description":"Number of most recent messages to load and store. 0 turns memory off."}},"required":["kind","context_length"]},"MemoryAuto":{"type":"object","deprecated":true,"description":"Deprecated, still read as it was written: the run's memory id, else the `memory_id` here.\nThe step's own `memory_id` is not read while this kind is set; switch the kind to `window`\nto use it. Without a `context_length`, or with 0, it is `off` and reads `previous_messages`.\n","properties":{"kind":{"type":"string","enum":["auto"]},"context_length":{"type":"integer","description":"Maximum number of messages to retain in context"},"memory_id":{"type":"string","description":"Identifier for persistent memory across agent invocations"}},"required":["kind"]},"MemoryCompaction":{"type":"object","description":"Keeps the whole memory named by the run's memory id (or the step's `memory_id`), replacing\nits older part with a summary as the conversation approaches the model's context window.\nWithout a memory id the agent runs without memory, and compaction bounds the run's own loop.\n","properties":{"kind":{"type":"string","enum":["compaction"]},"context_window":{"type":"integer","description":"Overrides the context window looked up from the model, in tokens. Only a model\nWindmill does not know needs one; those fall back to 128000.\n"}},"required":["kind"]},"MemoryMessage":{"type":"object","description":"A single message in conversation history","properties":{"role":{"type":"string","enum":["user","assistant","system"]},"content":{"type":"string"}},"required":["role","content"]},"MemoryManual":{"type":"object","deprecated":true,"description":"Deprecated, still read as it was written. Move the step to `off` with `previous_messages` instead.","properties":{"kind":{"type":"string","enum":["manual"]},"messages":{"type":"array","items":{"$ref":"#/components/schemas/MemoryMessage"}}},"required":["kind","messages"]},"MemoryConfig":{"description":"Managed memory, stored by Windmill and replayed with each request. The memory is named by a memory id, see `memory_id`. While it is off, a step can supply its history in `previous_messages`.","oneOf":[{"$ref":"#/components/schemas/MemoryOff"},{"$ref":"#/components/schemas/MemoryWindow"},{"$ref":"#/components/schemas/MemoryCompaction"},{"$ref":"#/components/schemas/MemoryAuto"},{"$ref":"#/components/schemas/MemoryManual"}],"discriminator":{"propertyName":"kind","mapping":{"off":"#/components/schemas/MemoryOff","window":"#/components/schemas/MemoryWindow","compaction":"#/components/schemas/MemoryCompaction","auto":"#/components/schemas/MemoryAuto","manual":"#/components/schemas/MemoryManual"}}},"StaticMemoryTransform":{"type":"object","description":"Static memory configuration passed directly to the AI agent","properties":{"value":{"$ref":"#/components/schemas/MemoryConfig"},"type":{"type":"string","enum":["static"]}},"required":["type","value"]},"MemoryTransform":{"description":"Memory configuration - can be static (MemoryConfig), JavaScript expression, or AI-determined","oneOf":[{"$ref":"#/components/schemas/StaticMemoryTransform"},{"$ref":"#/components/schemas/JavascriptTransform"},{"$ref":"#/components/schemas/AiTransform"}],"discriminator":{"propertyName":"type","mapping":{"static":"#/components/schemas/StaticMemoryTransform","javascript":"#/components/schemas/JavascriptTransform","ai":"#/components/schemas/AiTransform"}}},"FlowModuleValue":{"description":"The actual implementation of a flow step. Can be a script (inline or referenced), subflow, loop, branch, or special module type","oneOf":[{"$ref":"#/components/schemas/RawScript"},{"$ref":"#/components/schemas/PathScript"},{"$ref":"#/components/schemas/PathFlow"},{"$ref":"#/components/schemas/ForloopFlow"},{"$ref":"#/components/schemas/WhileloopFlow"},{"$ref":"#/components/schemas/BranchOne"},{"$ref":"#/components/schemas/BranchAll"},{"$ref":"#/components/schemas/Identity"},{"$ref":"#/components/schemas/AiAgent"},{"$ref":"#/components/schemas/AiDecision"}],"discriminator":{"propertyName":"type","mapping":{"rawscript":"#/components/schemas/RawScript","script":"#/components/schemas/PathScript","flow":"#/components/schemas/PathFlow","forloopflow":"#/components/schemas/ForloopFlow","whileloopflow":"#/components/schemas/WhileloopFlow","branchone":"#/components/schemas/BranchOne","branchall":"#/components/schemas/BranchAll","identity":"#/components/schemas/Identity","aiagent":"#/components/schemas/AiAgent","aidecision":"#/components/schemas/AiDecision"}}},"RawScript":{"type":"object","description":"Inline script with code defined directly in the flow. Use 'bun' as default language if unspecified. The script receives arguments from input_transforms","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"content":{"type":"string","description":"The script source code. Should export a 'main' function"},"language":{"type":"string","description":"Programming language for this script","enum":["deno","bun","bunnative","python3","go","bash","powershell","postgresql","mysql","bigquery","snowflake","mssql","oracledb","graphql","nativets","php","rust","ansible","csharp","nu","java","ruby","rlang","duckdb"]},"path":{"type":"string","description":"Optional path for saving this script"},"lock":{"type":"string","description":"Lock file content for dependencies"},"type":{"type":"string","enum":["rawscript"]},"tag":{"type":"string","description":"Worker group tag for execution routing"},"concurrent_limit":{"type":"number","description":"Maximum concurrent executions of this script"},"concurrency_time_window_s":{"type":"number","description":"Time window for concurrent_limit"},"custom_concurrency_key":{"type":"string","description":"Custom key for grouping concurrent executions"},"is_trigger":{"type":"boolean","description":"If true, this script is a trigger that can start the flow"},"assets":{"type":"array","description":"External resources this script accesses (S3 objects, resources, etc.)","items":{"type":"object","required":["path","kind"],"properties":{"path":{"type":"string","description":"Path to the asset"},"kind":{"type":"string","description":"Type of asset","enum":["s3object","resource","ducklake","datatable","volume","dbt"]},"access_type":{"type":"string","nullable":true,"description":"Access level for this asset","enum":["r","w","rw"]},"alt_access_type":{"type":"string","nullable":true,"description":"Alternative access level","enum":["r","w","rw"]}}}}},"required":["type","content","language","input_transforms"]},"PathScript":{"type":"object","description":"Reference to an existing script by path. Use this when calling a previously saved script instead of writing inline code","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the script's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"path":{"type":"string","description":"Path to the script in the workspace (e.g., 'f/scripts/send_email')"},"hash":{"type":"string","description":"Optional specific version hash of the script to use"},"type":{"type":"string","enum":["script"]},"tag_override":{"type":"string","description":"Override the script's default worker group tag"},"is_trigger":{"type":"boolean","description":"If true, this script is a trigger that can start the flow"}},"required":["type","path","input_transforms"]},"PathFlow":{"type":"object","description":"Reference to an existing flow by path. Use this to call another flow as a subflow","properties":{"input_transforms":{"type":"object","description":"Map of parameter names to their values (static or JavaScript expressions). These become the subflow's input arguments","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}},"path":{"type":"string","description":"Path to the flow in the workspace (e.g., 'f/flows/process_user')"},"type":{"type":"string","enum":["flow"]}},"required":["type","path","input_transforms"]},"ForloopFlow":{"type":"object","description":"Executes nested modules in a loop over an iterator. Inside the loop, use 'flow_input.iter.value' to access the current iteration value, and 'flow_input.iter.index' for the index. Supports parallel execution for better performance on I/O-bound operations","properties":{"modules":{"type":"array","description":"Steps to execute for each iteration. These can reference the iteration value via 'flow_input.iter.value'","items":{"$ref":"#/components/schemas/FlowModule"}},"iterator":{"description":"JavaScript expression that returns an array to iterate over. Can reference 'results.step_id' or 'flow_input'","$ref":"#/components/schemas/InputTransform"},"skip_failures":{"type":"boolean","description":"If true, iteration failures don't stop the loop. Failed iterations return null"},"type":{"type":"string","enum":["forloopflow"]},"parallel":{"type":"boolean","description":"If true, iterations run concurrently (faster for I/O-bound operations). Use with parallelism to control concurrency"},"parallelism":{"description":"Maximum number of concurrent iterations when parallel=true. Limits resource usage. Can be static number or expression","$ref":"#/components/schemas/InputTransform"},"squash":{"type":"boolean"}},"required":["modules","iterator","skip_failures","type"]},"WhileloopFlow":{"type":"object","description":"Executes nested modules repeatedly until stopped. The implicit iterator is the iteration counter, so 'flow_input.iter.value' equals 'flow_input.iter.index' (0, 1, 2, ...) and never carries state. To carry state across iterations, a step reads its own previous-iteration result via 'results.<its_own_id>' with a first-iteration fallback - the loop's stop_after_if must then be on that inner step (a plain single-step body with stop_after_if on the loop module does not resolve 'results' across iterations and never terminates); plain counters can instead be derived from 'flow_input.iter.index', which works in every configuration. stop_after_if is evaluated after each iteration - on the loop module 'result' is the last iteration's result","properties":{"modules":{"type":"array","description":"Steps to execute in each iteration","items":{"$ref":"#/components/schemas/FlowModule"}},"skip_failures":{"type":"boolean","description":"If true, iteration failures don't stop the loop. Failed iterations return null"},"type":{"type":"string","enum":["whileloopflow"]},"parallel":{"type":"boolean","description":"If true, iterations run concurrently (use with caution in while loops)"},"parallelism":{"description":"Maximum number of concurrent iterations when parallel=true","$ref":"#/components/schemas/InputTransform"},"squash":{"type":"boolean"}},"required":["modules","skip_failures","type"]},"BranchOne":{"type":"object","description":"Conditional branching where only the first matching branch executes. Branches are evaluated in order, and the first one with a true expression runs. If no branches match, the default branch executes","properties":{"branches":{"type":"array","description":"Array of branches to evaluate in order. The first branch with expr evaluating to true executes","items":{"type":"object","properties":{"summary":{"type":"string","description":"Short description of this branch condition"},"expr":{"type":"string","description":"JavaScript expression that returns boolean. Can use 'results.step_id' or 'flow_input'. First true expr wins"},"modules":{"type":"array","description":"Steps to execute if this branch's expr is true","items":{"$ref":"#/components/schemas/FlowModule"}}},"required":["modules","expr"]}},"default":{"type":"array","description":"Steps to execute if no branch expressions match","items":{"$ref":"#/components/schemas/FlowModule"}},"type":{"type":"string","enum":["branchone"]}},"required":["branches","default","type"]},"BranchAll":{"type":"object","description":"Parallel branching where all branches execute simultaneously. Unlike BranchOne, all branches run regardless of conditions. Useful for executing independent tasks concurrently","properties":{"branches":{"type":"array","description":"Array of branches that all execute (either in parallel or sequentially)","items":{"type":"object","properties":{"summary":{"type":"string","description":"Short description of this branch's purpose"},"skip_failure":{"type":"boolean","description":"If true, failure in this branch doesn't fail the entire flow"},"modules":{"type":"array","description":"Steps to execute in this branch","items":{"$ref":"#/components/schemas/FlowModule"}}},"required":["modules"]}},"type":{"type":"string","enum":["branchall"]},"parallel":{"type":"boolean","description":"If true, all branches execute concurrently. If false, they execute sequentially"}},"required":["branches","type"]},"AgentTool":{"type":"object","description":"A tool available to an AI agent. Can be a flow module or an external MCP (Model Context Protocol) tool","properties":{"id":{"type":"string","description":"Unique identifier for this tool. Cannot contain spaces - use underscores instead (e.g., 'get_user_data' not 'get user data')"},"summary":{"type":"string","description":"The name the AI agent calls this tool by, not a human label. On a flowmodule tool it must match ^[a-zA-Z0-9_]+$ - letters, numbers and underscores only (e.g. 'search_documentation', not 'Search documentation') - and always be set; on an mcp or websearch tool it is a plain label. Put the human-readable explanation in 'description'."},"description":{"type":"string","description":"Free-text description of the tool given to the AI to decide when and how to call it. Overrides the description auto-derived from the underlying script."},"job_token_scopes":{"type":"array","nullable":true,"items":{"type":"string"},"description":"Scopes the token of this tool's jobs is restricted to, on top of the agent step's own restriction: a tool can only narrow it."},"value":{"$ref":"#/components/schemas/ToolValue"}},"required":["id","value"]},"ToolValue":{"description":"The implementation of a tool. Can be a flow module (script/flow) or an MCP tool reference","oneOf":[{"$ref":"#/components/schemas/FlowModuleTool"},{"$ref":"#/components/schemas/McpToolValue"},{"$ref":"#/components/schemas/WebsearchToolValue"}],"discriminator":{"propertyName":"tool_type","mapping":{"flowmodule":"#/components/schemas/FlowModuleTool","mcp":"#/components/schemas/McpToolValue","websearch":"#/components/schemas/WebsearchToolValue"}}},"FlowModuleTool":{"description":"A tool implemented as a flow module (script, flow, etc.). The AI can call this like any other flow module","allOf":[{"type":"object","properties":{"tool_type":{"type":"string","enum":["flowmodule"]}},"required":["tool_type"]},{"$ref":"#/components/schemas/FlowModuleValue"}]},"WebsearchToolValue":{"type":"object","description":"A tool implemented as a websearch tool. The AI can call this like any other websearch tool","properties":{"tool_type":{"type":"string","enum":["websearch"]}},"required":["tool_type"]},"McpToolValue":{"type":"object","description":"Reference to an external MCP (Model Context Protocol) tool. The AI can call tools from MCP servers","properties":{"tool_type":{"type":"string","enum":["mcp"]},"resource_path":{"type":"string","description":"Path to the MCP resource/server configuration"},"include_tools":{"type":"array","description":"Whitelist of specific tools to include from this MCP server","items":{"type":"string"}},"exclude_tools":{"type":"array","description":"Blacklist of tools to exclude from this MCP server","items":{"type":"string"}}},"required":["tool_type","resource_path"]},"AiAgent":{"type":"object","description":"AI agent step that can use tools to accomplish tasks. The agent receives inputs and can call any of its configured tools to complete the task","properties":{"input_transforms":{"type":"object","description":"Input parameters for the AI agent mapped to their values","properties":{"provider":{"$ref":"#/components/schemas/ProviderTransform"},"output_type":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Output format type.\nValid values: 'text' (default) - plain text response, 'image' - image generation\n"},"user_message":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"The user's prompt/message to the AI agent. Supports variable interpolation with\nflow.input syntax. Required unless memory is off and `previous_messages` supplies\nthe prompt; image output always needs it.\n"},"system_prompt":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"System instructions that guide the AI's behavior, persona, and response style. Optional."},"streaming":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Boolean. If true, stream the AI response incrementally.\nStreaming events include: token_delta, reasoning_token_delta, tool_call, tool_call_arguments, tool_execution, tool_result\n"},"memory":{"$ref":"#/components/schemas/MemoryTransform"},"memory_id":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"String. Names the memory this step reads and writes, overriding the memory id the run\nwas started with (the chat conversation, an app chat session or the `memory_id` run\nparameter). Leave unset to use the run's memory id. A fixed value shares one memory\nacross every run; an expression such as `flow_input.customer_id` keeps one memory per\nkey. When it evaluates to an empty value the agent runs without memory. Read only\nwhile `memory` is `window` or `compaction`: it is ignored when memory is off, and an\nolder `auto` or `manual` memory reads neither history input.\n"},"previous_messages":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Array of MemoryMessage. History supplied by the flow, sent between the system prompt\nand the user message. Read only while `memory` is off or absent: managed memory\nignores it, and an older `auto` or `manual` memory reads neither history input.\n"},"output_schema":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"JSON Schema object defining structured output format. Used when you need the AI to return data in a specific shape.\nSupports standard JSON Schema properties: type, properties, required, items, enum, pattern, minLength, maxLength, minimum, maximum, etc.\nExample: { type: 'object', properties: { name: { type: 'string' }, age: { type: 'integer' } }, required: ['name'] }\n"},"user_attachments":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Array of file references (images or PDFs) for the AI agent.\nFormat: Array<{ bucket: string, key: string }> - S3 object references\nExample: [{ bucket: 'my-bucket', key: 'documents/report.pdf' }]\n"},"enabled_tools":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Array of strings naming which of the tools configured in `tools` the agent may call\nthis run. Leaving it unset carries every one of them; an empty array carries none.\nA tool is named as the model is shown it. An entry the model is shown nothing of is\nnamed by what identifies it instead: an MCP server by its resource path, carrying\nevery tool it exposes (which of them stays that entry's include_tools/exclude_tools),\nand a websearch entry by the reserved name '__wm_web_search', whatever summary it carries\n(no tool may take that name).\nExample: ['get_user', 'u/admin/github_mcp', '__wm_web_search']\n"},"max_completion_tokens":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Integer. Maximum number of tokens the AI will generate in its response.\nRange: 1 to 4,294,967,295. Typical values: 256-4096 for most use cases.\n"},"temperature":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Float. Controls randomness/creativity of responses.\nRange: 0.0 to 2.0 (provider-dependent)\n- 0.0 = deterministic, focused responses\n- 0.7 = balanced (common default)\n- 1.0+ = more creative/random\n"},"max_iterations":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Number. Limits how many times the agent can loop through reasoning and tool use.\nRange: 1-1000.\n"},"model":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"String. Only on a step linked to a saved agent (see `agent`): replaces the model\nsaved on the agent for this step's runs, on the agent's own provider resource. An\nempty value keeps the saved model. Set it to an expression such as\n`flow_input.model` to choose the model per run.\n"},"reasoning_effort":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"String. Only on a step linked to a saved agent (see `agent`): replaces the reasoning\neffort saved on the agent for this step's runs, as a provider-native token (e.g.\n'low', 'high', 'none'). An empty value sends no effort, so the model runs at its\ndefault. Leave the input out to keep the saved effort, which holds only while the\nstep runs the saved model. A step that is not linked sets both inside `provider`.\n"}}},"tools":{"type":"array","description":"Array of tools the agent can use. The agent decides which tools to call based on the task","items":{"$ref":"#/components/schemas/AgentTool"}},"type":{"type":"string","enum":["aiagent"]},"tag":{"type":"string","description":"Worker group tag for execution routing. If not set, the AI agent step runs on the flow's tag (default `flow`)"},"omit_output_from_conversation":{"type":"boolean","default":false,"description":"If true, this AI agent step does not persist its assistant or tool messages to the flow conversation when chat mode is enabled."},"agent":{"type":"string","description":"Path of a reusable `ai_agent` resource (hybrid linking). When set, the agent brain\nconfig (provider/model/system prompt/etc.) and tool set are resolved at runtime from\nthat resource; the module's input_transforms then only carry the flow-local inputs\n(user_message, user_attachments, enabled_tools and the history inputs memory_id and previous_messages)\nand, optionally, the `model` and `reasoning_effort` overrides of what the agent saved.\n"},"tool_inputs":{"type":"object","description":"Host-local wiring for an agent's tool inputs, keyed by tool id then input key. Binds the\nreferenced agent's tools to this flow's context (flow_input/results) without mutating the\nshared resource; overlaid onto the tools' input_transforms at runtime \u2014 including when\n`agent` is unset, since a step forked for editing keeps these overrides until it is saved\nback or unlinked.\n","additionalProperties":{"type":"object","additionalProperties":{"$ref":"#/components/schemas/InputTransform"}}},"parallel":{"type":"boolean","description":"If true, the agent can execute multiple tool calls in parallel"}},"required":["type","input_transforms"]},"AiDecision":{"type":"object","description":"AI decision step: one call to a decision model (TypeSafe's Jev, Cloudflare's\nJev-compatible Clef, or OpenAI's Decisions API) that answers typed questions about a\nstate with calibrated probabilities, instead of generating text.\nPrefer it over an AI agent to classify, route, score or check something: it is fast,\ncheap and its answers are structured. Its result is { output: { <question name>: answer },\nmodel, usage }, so a later step reads e.g. results.<id>.output.intent.choice. To route on\nthe answers, follow it with a branchone whose branch exprs read\nresults.<id>.output.<question>.choice. Usable as an AI agent tool, where the calling agent\nsupplies the state.\n","properties":{"input_transforms":{"type":"object","description":"Input parameters for the decision mapped to their values","properties":{"provider":{"$ref":"#/components/schemas/ProviderTransform"},"state":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"What the questions are asked about: a string, an object or an array of strings.\nAn object with descriptive keys holding only what the questions need works best.\nExample: { message: flow_input.message, plan: results.a.plan }\n"},"questions":{"allOf":[{"$ref":"#/components/schemas/InputTransform"}],"description":"Object mapping each question name to { type, instructions, criteria }, where type is:\n- 'choice': criteria maps each option to its description (up to 255); the answer\n has choice, probabilities and confidence\n- 'score': criteria is an ordered array of 2 to 10 level descriptions; the answer\n has score, legend, probabilities and confidence\n- 'noul': yes/no, criteria optionally { true, false } descriptions; the answer has\n noul, the probability of yes (0 to 1)\nExample: { intent: { type: 'choice', instructions: 'What does the customer want?',\ncriteria: { refund: 'Money back', bug: 'Something is broken' } } }\n"}},"required":["provider","state","questions"]},"type":{"type":"string","enum":["aidecision"]},"tag":{"type":"string","description":"Worker group tag for execution routing. If not set, the step runs on the flow's tag (default `flow`)"}},"required":["type","input_transforms"]},"Identity":{"type":"object","description":"Pass-through module that returns its input unchanged. Useful for flow structure or as a placeholder","properties":{"type":{"type":"string","enum":["identity"]},"flow":{"type":"boolean","description":"If true, marks this as a flow identity (special handling)"}},"required":["type"]},"FlowStatus":{"type":"object","properties":{"step":{"type":"integer"},"modules":{"type":"array","items":{"$ref":"#/components/schemas/FlowStatusModule"}},"user_states":{"additionalProperties":true},"preprocessor_module":{"allOf":[{"$ref":"#/components/schemas/FlowStatusModule"}]},"failure_module":{"allOf":[{"$ref":"#/components/schemas/FlowStatusModule"},{"type":"object","properties":{"parent_module":{"type":"string"}}}]},"retry":{"type":"object","properties":{"fail_count":{"type":"integer"},"failed_jobs":{"type":"array","items":{"type":"string","format":"uuid"}}}}},"required":["step","modules","failure_module"]},"FlowStatusModule":{"type":"object","properties":{"type":{"type":"string","enum":["WaitingForPriorSteps","WaitingForEvents","WaitingForExecutor","InProgress","Success","Failure"]},"id":{"type":"string"},"job":{"type":"string","format":"uuid"},"count":{"type":"integer"},"progress":{"type":"integer"},"iterator":{"type":"object","properties":{"index":{"type":"integer"},"itered":{"type":"array","items":{}},"itered_len":{"type":"integer"},"args":{}}},"flow_jobs":{"type":"array","items":{"type":"string"}},"flow_jobs_success":{"type":"array","items":{"type":"boolean"}},"flow_jobs_duration":{"type":"object","properties":{"started_at":{"type":"array","items":{"type":"string"}},"duration_ms":{"type":"array","items":{"type":"integer"}}}},"branch_chosen":{"type":"object","properties":{"type":{"type":"string","enum":["branch","default"]},"branch":{"type":"integer"}},"required":["type"]},"branchall":{"type":"object","properties":{"branch":{"type":"integer"},"len":{"type":"integer"}},"required":["branch","len"]},"approvers":{"type":"array","items":{"type":"object","properties":{"resume_id":{"type":"integer"},"approver":{"type":"string"}},"required":["resume_id","approver"]}},"failed_retries":{"type":"array","items":{"type":"string","format":"uuid"}},"skipped":{"type":"boolean"},"agent_actions":{"type":"array","items":{"type":"object","oneOf":[{"type":"object","properties":{"job_id":{"type":"string","format":"uuid"},"function_name":{"type":"string"},"type":{"type":"string","enum":["tool_call"]},"module_id":{"type":"string"}},"required":["job_id","function_name","type","module_id"]},{"type":"object","properties":{"call_id":{"type":"string","format":"uuid"},"function_name":{"type":"string"},"resource_path":{"type":"string"},"type":{"type":"string","enum":["mcp_tool_call"]},"arguments":{"type":"object"}},"required":["call_id","function_name","resource_path","type"]},{"type":"object","properties":{"type":{"type":"string","enum":["web_search"]}},"required":["type"]},{"type":"object","properties":{"type":{"type":"string","enum":["message"]}},"required":["content","type"]}]}},"agent_actions_success":{"type":"array","items":{"type":"boolean"}}},"required":["type"]}} diff --git a/system_prompts/auto-generated/skills/write-pipeline/SKILL.md b/system_prompts/auto-generated/skills/write-pipeline/SKILL.md index 064dc600ac..4c339e6222 100644 --- a/system_prompts/auto-generated/skills/write-pipeline/SKILL.md +++ b/system_prompts/auto-generated/skills/write-pipeline/SKILL.md @@ -12,10 +12,48 @@ A **data pipeline** is NOT a flow. A flow is one runnable that orchestrates step A pipeline node that produces a table should almost always be a **`duckdb`** node that materializes its output into a **DuckLake** table with `-- materialize ducklake://<name>/<table>` (in a DuckDB node the annotation uses SQL `--` comment syntax; write the body as a bare `SELECT` and let the runtime do the write). DuckLake is the default lakehouse store for pipelines and is the shape the pipeline editor is built around, so prefer it unless the work specifically calls for something else: - `postgresql` / data tables — only for row-level, OLTP-style mutations against an existing Postgres data table (frequent single-row upserts/updates, transactional reads that an app queries live). -- `bun` / `python3` — only for non-tabular work that doesn't map to SQL: calling an external API, wrangling files, arbitrary glue. When such a node still produces tabular data for downstream steps, land it in DuckLake (write it with the wmill SDK / ducklake helpers) rather than inventing a parallel store. +- `bun` / `python3` — only for work that doesn't map to SQL: calling an external API, wrangling files, arbitrary glue. When such a node produces tabular data for downstream steps, write it **straight into DuckLake** (or a data table) from the same script — see "Ingesting from Python / TypeScript" below — rather than inventing a parallel store. Do not spread a pipeline across postgres, S3, and DuckLake when one DuckLake lake would do; a consistent DuckLake lakehouse is the goal. +## Ingesting from Python / TypeScript + +A node that fetches data in code (an API, a SaaS export, a scraper) writes the rows **directly** into their DuckLake table with `wmill.ducklake()`, or into a data table with `wmill.datatable()`. DuckLake already stores every table as parquet files in the workspace object storage, so **never stage the raw payload first** — no intermediate JSON / CSV / parquet file in S3 and no second "load the raw file" node. One ingestion node, one table. + +Pass the rows as a query argument (a list of dicts / array of objects is sent as JSON) and let SQL unnest them; declare the column types so the table gets a real schema: + +```python +# pipeline +# on schedule +import wmill + +def main(): + rows = fetch_charges() # list[dict] + lake = wmill.ducklake() + lake.query(""" + CREATE OR REPLACE TABLE stripe_charges AS + SELECT unnest(from_json($rows, '[{"id":"VARCHAR","amount":"BIGINT","created":"BIGINT"}]'), recursive := true) + """, rows=rows).fetch() +``` + +```ts +// pipeline +// on schedule +import * as wmill from "windmill-client" + +export async function main() { + const rows = await fetchCharges() + const lake = wmill.ducklake() + await lake`CREATE OR REPLACE TABLE stripe_charges AS + SELECT unnest(from_json(${rows}, '[{"id":"VARCHAR","amount":"BIGINT","created":"BIGINT"}]'), recursive := true)`.fetch() +} +``` + +- Use `INSERT INTO <table> SELECT ...` instead of `CREATE OR REPLACE` to append (an incremental pull), with a one-time `CREATE TABLE IF NOT EXISTS` first. +- Assign the client to a variable (`lake = wmill.ducklake()`) and keep the SQL a **string literal** (Python) or a template without `sql.raw` (TS): that is what lets the graph record the node's write to `ducklake://main/<table>`. A chained `wmill.ducklake().query(...)` or SQL built in a variable records no output, so the downstream edge never forms. +- `wmill.ducklake("<name>")` targets a non-default catalog; `wmill.datatable("<name>")` writes a Postgres data table the same way (Python `db.query(sql, *args)` with `$1` placeholders, TS the same template form) — use it only when the data belongs in Postgres (see above). +- The downstream node triggers on the table itself: `-- on ducklake://main/stripe_charges`. + ## Storage prerequisites A DuckLake pipeline only runs once the workspace has **object storage** (S3 / Azure Blob / GCS) **and a DuckLake catalog** configured — DuckLake tables and `s3://` assets can't be materialized or read without it. Check which DuckLake catalogs the workspace has before you build. @@ -59,7 +97,7 @@ The key must be a **string literal** — the graph parser is static and cannot f ## Materialize (the managed output) -> **A MANAGED `// materialize` is DuckDB-only**, and its target must be a DuckLake table (`ducklake://<name>/<table>`). Deploy **rejects** a `ducklake://` `// materialize` on any other language (`python3`, `bun`, `postgresql`). For a non-DuckDB node writing the lake, do **not** use `// materialize` — write the output via the SDK (`wmill.writeS3File(...)`, ducklake helpers, …) and let it be inferred. Use `duckdb` when a node should materialize a DuckLake table. +> **A MANAGED `// materialize` is DuckDB-only**, and its target must be a DuckLake table (`ducklake://<name>/<table>`). Deploy **rejects** a `ducklake://` `// materialize` on any other language (`python3`, `bun`, `postgresql`). For a non-DuckDB node writing the lake, do **not** use `// materialize` — write the table itself with `wmill.ducklake()` (see "Ingesting from Python / TypeScript") and let the output be inferred. Use `duckdb` when a node should materialize a DuckLake table. > > The one target ANY language may declare (except a dbt script, whose writes come from its manifest) is a **warehouse relation**: `// materialize manual dbt://<warehouse>/<schema>/<name>`, where `<warehouse>` is a warehouse the workspace configures under Settings → dbt. `manual` is the only mode it has — nothing generates warehouse DDL, so the node issues its own write (a postgresql `CREATE TABLE` / `INSERT`, an SDK load, …) and the annotation records the outcome. Use it on an ingestion node whose output a dbt project reads as a `source`: the declared relation and the dbt model land on ONE graph node, and a downstream `// on dbt://<warehouse>/<schema>/<name>` fires when the ingestion node completes. diff --git a/system_prompts/auto-generated/skills/write-script-ansible/SKILL.md b/system_prompts/auto-generated/skills/write-script-ansible/SKILL.md index 9bb87cb4a1..e67e8fc30c 100644 --- a/system_prompts/auto-generated/skills/write-script-ansible/SKILL.md +++ b/system_prompts/auto-generated/skills/write-script-ansible/SKILL.md @@ -53,6 +53,9 @@ Use `wmill resource-type list --schema` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_<name>`, which keeps it apart from a hub type synced later: the parameter takes `RT.C<Name>` in TypeScript, a `c_<name>` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run `wmill resource-type list`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments - Where the language has a Windmill client (`wmill`), use it to interact with the platform diff --git a/system_prompts/auto-generated/skills/write-script-bash/SKILL.md b/system_prompts/auto-generated/skills/write-script-bash/SKILL.md index 0c4634b775..c1e9274a7a 100644 --- a/system_prompts/auto-generated/skills/write-script-bash/SKILL.md +++ b/system_prompts/auto-generated/skills/write-script-bash/SKILL.md @@ -53,6 +53,9 @@ Use `wmill resource-type list --schema` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_<name>`, which keeps it apart from a hub type synced later: the parameter takes `RT.C<Name>` in TypeScript, a `c_<name>` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run `wmill resource-type list`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments - Where the language has a Windmill client (`wmill`), use it to interact with the platform diff --git a/system_prompts/auto-generated/skills/write-script-bigquery/SKILL.md b/system_prompts/auto-generated/skills/write-script-bigquery/SKILL.md index 497336b001..97cf31976e 100644 --- a/system_prompts/auto-generated/skills/write-script-bigquery/SKILL.md +++ b/system_prompts/auto-generated/skills/write-script-bigquery/SKILL.md @@ -53,6 +53,9 @@ Use `wmill resource-type list --schema` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_<name>`, which keeps it apart from a hub type synced later: the parameter takes `RT.C<Name>` in TypeScript, a `c_<name>` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run `wmill resource-type list`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments - Where the language has a Windmill client (`wmill`), use it to interact with the platform diff --git a/system_prompts/auto-generated/skills/write-script-bun/SKILL.md b/system_prompts/auto-generated/skills/write-script-bun/SKILL.md index 21b2f382c3..9b31261bb8 100644 --- a/system_prompts/auto-generated/skills/write-script-bun/SKILL.md +++ b/system_prompts/auto-generated/skills/write-script-bun/SKILL.md @@ -53,6 +53,9 @@ Use `wmill resource-type list --schema` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_<name>`, which keeps it apart from a hub type synced later: the parameter takes `RT.C<Name>` in TypeScript, a `c_<name>` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run `wmill resource-type list`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments - Where the language has a Windmill client (`wmill`), use it to interact with the platform @@ -392,6 +395,14 @@ async setProgress(percent: number, jobId?: any): Promise<void> */ async getProgress(jobId?: any): Promise<number | null> +/** + * Whether the worker running this job has received its shutdown signal. + * A draining worker waits for its current job to finish before exiting, so a + * long-running script can poll this and return early to let the worker be replaced. + * @param jobId? Job to check, defaults to the current job + */ +async workerIsDraining(jobId?: string): Promise<boolean> + /** * Set a flow user state * @param key key of the state @@ -651,6 +662,9 @@ async sleep(seconds: number): Promise<void> * `fn`'s result is encoded as JSON and decoded back before it is returned, so * the round that runs the body sees the same types every replay sees: a `Date` * comes back as a string, a `Map` as `{}`. {@link Jsonified} is that shape. + * + * Called from inside a task body, `fn` runs in place and nothing is + * checkpointed: a task is a single job and is never replayed. */ async step<T>(name: string, fn: () => T | Promise<T>,): Promise<Jsonified<Awaited<T>>> diff --git a/system_prompts/auto-generated/skills/write-script-bunnative/SKILL.md b/system_prompts/auto-generated/skills/write-script-bunnative/SKILL.md index f9e902fe78..1c7c1294a6 100644 --- a/system_prompts/auto-generated/skills/write-script-bunnative/SKILL.md +++ b/system_prompts/auto-generated/skills/write-script-bunnative/SKILL.md @@ -53,6 +53,9 @@ Use `wmill resource-type list --schema` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_<name>`, which keeps it apart from a hub type synced later: the parameter takes `RT.C<Name>` in TypeScript, a `c_<name>` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run `wmill resource-type list`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments - Where the language has a Windmill client (`wmill`), use it to interact with the platform @@ -121,7 +124,7 @@ export async function main(url: string) { ## Pure computation: `//no_network` -A native script that only transforms its inputs can declare `//no_network` in its leading comment block (right after `//native`). The runtime then refuses every connection the script attempts: `fetch` to any host, the Windmill API (so `windmill-client` calls fail too), raw sockets and unix sockets, and `WM_TOKEN` is not set. It only takes effect on native scripts: without `//native` it is ignored. Use it only when the script needs no external data beyond its arguments: +A native script that only transforms its inputs can declare `//no_network` in its leading comment block (right after `//native`). The runtime then refuses every connection the script attempts: `fetch` to any host, the Windmill API (so `windmill-client` calls fail too), raw sockets and unix sockets, and `WM_TOKEN` is not set. Without `//native` it means something else: the script must run in an nsjail sandbox (`//sandbox`, or instance-wide sandboxing), which then loses its network, and it fails to run otherwise. Use it only when the script needs no external data beyond its arguments: ```typescript //native @@ -404,6 +407,14 @@ async setProgress(percent: number, jobId?: any): Promise<void> */ async getProgress(jobId?: any): Promise<number | null> +/** + * Whether the worker running this job has received its shutdown signal. + * A draining worker waits for its current job to finish before exiting, so a + * long-running script can poll this and return early to let the worker be replaced. + * @param jobId? Job to check, defaults to the current job + */ +async workerIsDraining(jobId?: string): Promise<boolean> + /** * Set a flow user state * @param key key of the state @@ -663,6 +674,9 @@ async sleep(seconds: number): Promise<void> * `fn`'s result is encoded as JSON and decoded back before it is returned, so * the round that runs the body sees the same types every replay sees: a `Date` * comes back as a string, a `Map` as `{}`. {@link Jsonified} is that shape. + * + * Called from inside a task body, `fn` runs in place and nothing is + * checkpointed: a task is a single job and is never replayed. */ async step<T>(name: string, fn: () => T | Promise<T>,): Promise<Jsonified<Awaited<T>>> diff --git a/system_prompts/auto-generated/skills/write-script-csharp/SKILL.md b/system_prompts/auto-generated/skills/write-script-csharp/SKILL.md index 389c683f7c..2759e58b26 100644 --- a/system_prompts/auto-generated/skills/write-script-csharp/SKILL.md +++ b/system_prompts/auto-generated/skills/write-script-csharp/SKILL.md @@ -53,6 +53,9 @@ Use `wmill resource-type list --schema` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_<name>`, which keeps it apart from a hub type synced later: the parameter takes `RT.C<Name>` in TypeScript, a `c_<name>` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run `wmill resource-type list`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments - Where the language has a Windmill client (`wmill`), use it to interact with the platform diff --git a/system_prompts/auto-generated/skills/write-script-deno/SKILL.md b/system_prompts/auto-generated/skills/write-script-deno/SKILL.md index 71608cd16e..8325315dfe 100644 --- a/system_prompts/auto-generated/skills/write-script-deno/SKILL.md +++ b/system_prompts/auto-generated/skills/write-script-deno/SKILL.md @@ -53,6 +53,9 @@ Use `wmill resource-type list --schema` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_<name>`, which keeps it apart from a hub type synced later: the parameter takes `RT.C<Name>` in TypeScript, a `c_<name>` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run `wmill resource-type list`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments - Where the language has a Windmill client (`wmill`), use it to interact with the platform @@ -394,6 +397,14 @@ async setProgress(percent: number, jobId?: any): Promise<void> */ async getProgress(jobId?: any): Promise<number | null> +/** + * Whether the worker running this job has received its shutdown signal. + * A draining worker waits for its current job to finish before exiting, so a + * long-running script can poll this and return early to let the worker be replaced. + * @param jobId? Job to check, defaults to the current job + */ +async workerIsDraining(jobId?: string): Promise<boolean> + /** * Set a flow user state * @param key key of the state @@ -653,6 +664,9 @@ async sleep(seconds: number): Promise<void> * `fn`'s result is encoded as JSON and decoded back before it is returned, so * the round that runs the body sees the same types every replay sees: a `Date` * comes back as a string, a `Map` as `{}`. {@link Jsonified} is that shape. + * + * Called from inside a task body, `fn` runs in place and nothing is + * checkpointed: a task is a single job and is never replayed. */ async step<T>(name: string, fn: () => T | Promise<T>,): Promise<Jsonified<Awaited<T>>> diff --git a/system_prompts/auto-generated/skills/write-script-duckdb/SKILL.md b/system_prompts/auto-generated/skills/write-script-duckdb/SKILL.md index 2ffcf4607c..471a22217a 100644 --- a/system_prompts/auto-generated/skills/write-script-duckdb/SKILL.md +++ b/system_prompts/auto-generated/skills/write-script-duckdb/SKILL.md @@ -53,6 +53,9 @@ Use `wmill resource-type list --schema` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_<name>`, which keeps it apart from a hub type synced later: the parameter takes `RT.C<Name>` in TypeScript, a `c_<name>` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run `wmill resource-type list`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments - Where the language has a Windmill client (`wmill`), use it to interact with the platform diff --git a/system_prompts/auto-generated/skills/write-script-go/SKILL.md b/system_prompts/auto-generated/skills/write-script-go/SKILL.md index 1707fcda4c..4573fa816a 100644 --- a/system_prompts/auto-generated/skills/write-script-go/SKILL.md +++ b/system_prompts/auto-generated/skills/write-script-go/SKILL.md @@ -53,6 +53,9 @@ Use `wmill resource-type list --schema` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_<name>`, which keeps it apart from a hub type synced later: the parameter takes `RT.C<Name>` in TypeScript, a `c_<name>` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run `wmill resource-type list`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments - Where the language has a Windmill client (`wmill`), use it to interact with the platform diff --git a/system_prompts/auto-generated/skills/write-script-graphql/SKILL.md b/system_prompts/auto-generated/skills/write-script-graphql/SKILL.md index c928dea3bc..225c0e928f 100644 --- a/system_prompts/auto-generated/skills/write-script-graphql/SKILL.md +++ b/system_prompts/auto-generated/skills/write-script-graphql/SKILL.md @@ -53,6 +53,9 @@ Use `wmill resource-type list --schema` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_<name>`, which keeps it apart from a hub type synced later: the parameter takes `RT.C<Name>` in TypeScript, a `c_<name>` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run `wmill resource-type list`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments - Where the language has a Windmill client (`wmill`), use it to interact with the platform diff --git a/system_prompts/auto-generated/skills/write-script-java/SKILL.md b/system_prompts/auto-generated/skills/write-script-java/SKILL.md index a768a5faa5..8712ee27c3 100644 --- a/system_prompts/auto-generated/skills/write-script-java/SKILL.md +++ b/system_prompts/auto-generated/skills/write-script-java/SKILL.md @@ -53,6 +53,9 @@ Use `wmill resource-type list --schema` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_<name>`, which keeps it apart from a hub type synced later: the parameter takes `RT.C<Name>` in TypeScript, a `c_<name>` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run `wmill resource-type list`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments - Where the language has a Windmill client (`wmill`), use it to interact with the platform diff --git a/system_prompts/auto-generated/skills/write-script-mssql/SKILL.md b/system_prompts/auto-generated/skills/write-script-mssql/SKILL.md index 9215f06906..195aff374b 100644 --- a/system_prompts/auto-generated/skills/write-script-mssql/SKILL.md +++ b/system_prompts/auto-generated/skills/write-script-mssql/SKILL.md @@ -53,6 +53,9 @@ Use `wmill resource-type list --schema` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_<name>`, which keeps it apart from a hub type synced later: the parameter takes `RT.C<Name>` in TypeScript, a `c_<name>` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run `wmill resource-type list`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments - Where the language has a Windmill client (`wmill`), use it to interact with the platform diff --git a/system_prompts/auto-generated/skills/write-script-mysql/SKILL.md b/system_prompts/auto-generated/skills/write-script-mysql/SKILL.md index d682cce351..8acf52e23a 100644 --- a/system_prompts/auto-generated/skills/write-script-mysql/SKILL.md +++ b/system_prompts/auto-generated/skills/write-script-mysql/SKILL.md @@ -53,6 +53,9 @@ Use `wmill resource-type list --schema` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_<name>`, which keeps it apart from a hub type synced later: the parameter takes `RT.C<Name>` in TypeScript, a `c_<name>` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run `wmill resource-type list`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments - Where the language has a Windmill client (`wmill`), use it to interact with the platform diff --git a/system_prompts/auto-generated/skills/write-script-php/SKILL.md b/system_prompts/auto-generated/skills/write-script-php/SKILL.md index 16c68834dc..2ed0b477ea 100644 --- a/system_prompts/auto-generated/skills/write-script-php/SKILL.md +++ b/system_prompts/auto-generated/skills/write-script-php/SKILL.md @@ -53,6 +53,9 @@ Use `wmill resource-type list --schema` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_<name>`, which keeps it apart from a hub type synced later: the parameter takes `RT.C<Name>` in TypeScript, a `c_<name>` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run `wmill resource-type list`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments - Where the language has a Windmill client (`wmill`), use it to interact with the platform diff --git a/system_prompts/auto-generated/skills/write-script-postgresql/SKILL.md b/system_prompts/auto-generated/skills/write-script-postgresql/SKILL.md index b0e14a6b12..f98cffd2b6 100644 --- a/system_prompts/auto-generated/skills/write-script-postgresql/SKILL.md +++ b/system_prompts/auto-generated/skills/write-script-postgresql/SKILL.md @@ -53,6 +53,9 @@ Use `wmill resource-type list --schema` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_<name>`, which keeps it apart from a hub type synced later: the parameter takes `RT.C<Name>` in TypeScript, a `c_<name>` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run `wmill resource-type list`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments - Where the language has a Windmill client (`wmill`), use it to interact with the platform diff --git a/system_prompts/auto-generated/skills/write-script-powershell/SKILL.md b/system_prompts/auto-generated/skills/write-script-powershell/SKILL.md index 540776c68a..f60d0b531d 100644 --- a/system_prompts/auto-generated/skills/write-script-powershell/SKILL.md +++ b/system_prompts/auto-generated/skills/write-script-powershell/SKILL.md @@ -53,6 +53,9 @@ Use `wmill resource-type list --schema` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_<name>`, which keeps it apart from a hub type synced later: the parameter takes `RT.C<Name>` in TypeScript, a `c_<name>` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run `wmill resource-type list`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments - Where the language has a Windmill client (`wmill`), use it to interact with the platform diff --git a/system_prompts/auto-generated/skills/write-script-python3/SKILL.md b/system_prompts/auto-generated/skills/write-script-python3/SKILL.md index decb356ba6..3afa72e5a9 100644 --- a/system_prompts/auto-generated/skills/write-script-python3/SKILL.md +++ b/system_prompts/auto-generated/skills/write-script-python3/SKILL.md @@ -53,6 +53,9 @@ Use `wmill resource-type list --schema` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_<name>`, which keeps it apart from a hub type synced later: the parameter takes `RT.C<Name>` in TypeScript, a `c_<name>` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run `wmill resource-type list`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments - Where the language has a Windmill client (`wmill`), use it to interact with the platform @@ -448,6 +451,18 @@ def set_progress(value: int, job_id: Optional[str] = None) # Progress value (0-100) or None if not set def get_progress(job_id: Optional[str] = None) -> Any +# Whether the worker running the job has received its shutdown signal. +# +# A draining worker waits for its current job to finish before exiting. A long-running +# script can poll this and return early so the worker can be replaced. +# +# Args: +# job_id: Job ID (defaults to current WM_JOB_ID) +# +# Returns: +# True if the worker running the job is draining +def worker_is_draining(job_id: Optional[str] = None) -> bool + # Set the user state of a flow at a given key def set_flow_user_state(key: str, value: Any) -> None @@ -461,15 +476,31 @@ def get_flow_user_state(key: str) -> Any def version() # Convenient helpers that takes an S3 resource as input and returns the settings necessary to -# initiate an S3 connection from DuckDB +# initiate an S3 connection from DuckDB. +# +# Without a resource path, the connection goes to the workspace storage through Windmill's +# S3 proxy when that storage is S3: address it as ``s3://<bucket>/<key>`` with the +# storage's own bucket, returned as ``s3_bucket``. Pass the resource path to connect with +# the storage's own credentials instead. def get_duckdb_connection_settings(s3_resource_path: str = '') -> DuckDbConnectionSettings | None # Convenient helpers that takes an S3 resource as input and returns the settings necessary to -# initiate an S3 connection from Polars +# initiate an S3 connection from Polars. +# +# Without a resource path, the connection goes to the workspace storage through Windmill's +# S3 proxy when that storage is S3: address it as ``s3://<bucket>/<key>`` with the +# storage's own bucket, returned as ``s3_bucket``. Pass the resource path to connect with +# the storage's own credentials instead. def get_polars_connection_settings(s3_resource_path: str = '') -> PolarsConnectionSettings # Convenient helpers that takes an S3 resource as input and returns the settings necessary to -# initiate an S3 connection using boto3 +# initiate an S3 connection using boto3. +# +# Without a resource path, the connection goes to the workspace storage through Windmill's +# S3 proxy when that storage is S3: pass the storage's own bucket as ``Bucket``. The proxy +# serves object reads, writes, deletes, listing and multipart uploads of that bucket only; +# presigned URLs, other buckets and bucket-level APIs need the storage's own credentials, +# which passing the resource path returns. def get_boto3_connection_settings(s3_resource_path: str = '') -> Boto3ConnectionSettings # Load a file from the workspace s3 bucket and returns its content as bytes. @@ -865,7 +896,9 @@ def parse_sql_client_name(name: str) -> tuple[str, Optional[str]] # # - **v2 (inside @workflow)**: dispatches as a checkpoint step. # - **v1 (WM_JOB_ID set, no @workflow)**: dispatches via HTTP API. -# - **Standalone**: executes the function body directly. +# - **Standalone, or called from inside another v2 task**: executes the +# function body directly. A task runs as a single job, so the tasks it +# calls run in that same job, without their own options. # # A task runs as its own job, so its result is always encoded as JSON and # decoded back before the caller sees it: a ``datetime`` comes back as a @@ -951,12 +984,15 @@ def workflow(func) # ``fn``'s result is encoded as JSON and decoded back before it is returned, # so the round that runs the body sees the same types every replay sees: # a ``datetime`` comes back as a string, a tuple as a list. +# +# Called from inside a task body, ``fn`` runs in place and nothing is +# checkpointed: a task is a single job and is never replayed. async def step(name: str, fn) # Server-side sleep — suspend the workflow for the given duration without holding a worker. # # Inside a @workflow, the parent job suspends and auto-resumes after ``seconds``. -# Outside a workflow, falls back to ``asyncio.sleep``. +# Outside a workflow, or inside a task body, falls back to ``asyncio.sleep``. async def sleep(seconds: int) # Suspend the workflow and wait for an external approval. diff --git a/system_prompts/auto-generated/skills/write-script-rlang/SKILL.md b/system_prompts/auto-generated/skills/write-script-rlang/SKILL.md index 061e1dcc45..636bc100e3 100644 --- a/system_prompts/auto-generated/skills/write-script-rlang/SKILL.md +++ b/system_prompts/auto-generated/skills/write-script-rlang/SKILL.md @@ -53,6 +53,9 @@ Use `wmill resource-type list --schema` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_<name>`, which keeps it apart from a hub type synced later: the parameter takes `RT.C<Name>` in TypeScript, a `c_<name>` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run `wmill resource-type list`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments - Where the language has a Windmill client (`wmill`), use it to interact with the platform diff --git a/system_prompts/auto-generated/skills/write-script-rust/SKILL.md b/system_prompts/auto-generated/skills/write-script-rust/SKILL.md index d9b599dffa..2b9280aa46 100644 --- a/system_prompts/auto-generated/skills/write-script-rust/SKILL.md +++ b/system_prompts/auto-generated/skills/write-script-rust/SKILL.md @@ -53,6 +53,9 @@ Use `wmill resource-type list --schema` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_<name>`, which keeps it apart from a hub type synced later: the parameter takes `RT.C<Name>` in TypeScript, a `c_<name>` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run `wmill resource-type list`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments - Where the language has a Windmill client (`wmill`), use it to interact with the platform diff --git a/system_prompts/auto-generated/skills/write-script-snowflake/SKILL.md b/system_prompts/auto-generated/skills/write-script-snowflake/SKILL.md index 8c438e7038..3e38ebc728 100644 --- a/system_prompts/auto-generated/skills/write-script-snowflake/SKILL.md +++ b/system_prompts/auto-generated/skills/write-script-snowflake/SKILL.md @@ -53,6 +53,9 @@ Use `wmill resource-type list --schema` to discover available resource types. ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_<name>`, which keeps it apart from a hub type synced later: the parameter takes `RT.C<Name>` in TypeScript, a `c_<name>` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration +- Before relying on a resource type, a hub script's included, run `wmill resource-type list`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments - Where the language has a Windmill client (`wmill`), use it to interact with the platform @@ -84,6 +87,27 @@ Name the parameters by adding comments before the statement: SELECT * FROM users WHERE name = ? AND age > ?; ``` +## Array parameters + +Declare a list with a `[]` suffix on the element type (`(varchar[])`, +`(int[])`), or `(array)` for an untyped one. Snowflake cannot bind an array +directly, so Windmill binds the list as JSON text: wrap the placeholder with +`PARSE_JSON(?)`, and cast to `ARRAY` where a function expects one. + +```sql +-- ? groups (varchar[]) +SELECT o.* FROM orders o +WHERE ARRAY_CONTAINS(o.owner_group::VARIANT, PARSE_JSON(?)::ARRAY); +``` + +Or join on the elements with `FLATTEN`: + +```sql +-- ? groups (varchar[]) +SELECT o.* FROM orders o +JOIN TABLE(FLATTEN(input => PARSE_JSON(?))) g ON g.value::STRING = o.owner_group; +``` + ## Receiving an S3Object as a script parameter Declare the arg with type `(s3object)`. Windmill renders an S3 file picker for diff --git a/system_prompts/auto-generated/skills/write-workflow-as-code/SKILL.md b/system_prompts/auto-generated/skills/write-workflow-as-code/SKILL.md index 13d305c74e..09789b388a 100644 --- a/system_prompts/auto-generated/skills/write-workflow-as-code/SKILL.md +++ b/system_prompts/auto-generated/skills/write-workflow-as-code/SKILL.md @@ -143,6 +143,8 @@ async def enrich(customer_id: str): In TypeScript, prefer assigning each task to a named top-level const. In Python, prefer top-level async functions decorated with `@task()` or `@task`. +Only the workflow body dispatches steps. A task runs as a single job, so a task or `step()` called from inside a task body runs in place in that job, as a plain function call: no child job, no checkpoint, and its task options (retry, timeout, tag) do not apply. `sleep()` there waits in the job, and `taskScript()` / `taskFlow()` / `waitForApproval()` (`task_script()` / `task_flow()` / `wait_for_approval()`) throw. To get separate jobs, call the tasks one after another from the workflow body and pass results between them. + For existing scripts: ```typescript @@ -308,8 +310,9 @@ export async function getResumeUrls(approver?: string, flowLevel?: boolean): Pro * const call_api = task(fetchOrders, { retry: { attempts: 3, delay: 30, multiplier: 2 } }); * * Inside a `workflow()`, calling a task dispatches it as a step. - * Outside a workflow, the function body executes directly and - * {@link TaskOptions} — retry included — does not apply. + * Outside a workflow, or called from inside another task, the function body + * executes directly and {@link TaskOptions} — retry included — does not apply: + * a task runs as a single job, so the tasks it calls run in that same job. * * A task runs as its own job, so its result is always encoded as JSON and * decoded back before the caller sees it: a `Date` comes back as a string, a @@ -353,6 +356,9 @@ export function workflow<T>(fn: (...args: any[]) => Promise<T>) * `fn`'s result is encoded as JSON and decoded back before it is returned, so * the round that runs the body sees the same types every replay sees: a `Date` * comes back as a string, a `Map` as `{}`. {@link Jsonified} is that shape. + * + * Called from inside a task body, `fn` runs in place and nothing is + * checkpointed: a task is a single job and is never replayed. */ export async function step<T>(name: string, fn: () => T | Promise<T>,): Promise<Jsonified<Awaited<T>>> @@ -451,7 +457,9 @@ def get_resume_urls(approver: str = None, flow_level: bool = None) -> dict # # - **v2 (inside @workflow)**: dispatches as a checkpoint step. # - **v1 (WM_JOB_ID set, no @workflow)**: dispatches via HTTP API. -# - **Standalone**: executes the function body directly. +# - **Standalone, or called from inside another v2 task**: executes the +# function body directly. A task runs as a single job, so the tasks it +# calls run in that same job, without their own options. # # A task runs as its own job, so its result is always encoded as JSON and # decoded back before the caller sees it: a ``datetime`` comes back as a @@ -537,12 +545,15 @@ def workflow(func) # ``fn``'s result is encoded as JSON and decoded back before it is returned, # so the round that runs the body sees the same types every replay sees: # a ``datetime`` comes back as a string, a tuple as a list. +# +# Called from inside a task body, ``fn`` runs in place and nothing is +# checkpointed: a task is a single job and is never replayed. async def step(name: str, fn) # Server-side sleep — suspend the workflow for the given duration without holding a worker. # # Inside a @workflow, the parent job suspends and auto-resumes after ``seconds``. -# Outside a workflow, falls back to ``asyncio.sleep``. +# Outside a workflow, or inside a task body, falls back to ``asyncio.sleep``. async def sleep(seconds: int) # Suspend the workflow and wait for an external approval. diff --git a/system_prompts/base/datatable.md b/system_prompts/base/datatable.md new file mode 100644 index 0000000000..87a583e881 --- /dev/null +++ b/system_prompts/base/datatable.md @@ -0,0 +1,44 @@ +# Data tables: schema changes, migrations and permissions + +A data table is a PostgreSQL database managed by Windmill and shared by the whole workspace: scripts, flows and apps reach it by name, `main` being the default. It is configured in the workspace settings (Data Tables), never created by SQL. + +## Changing the schema + +A data table with migrations enabled keeps its schema as an ordered list of versioned SQL migrations, each an `up` and an optional `down`. That list is what git sync and a workspace merge carry, and what rebuilds the schema in another workspace. So first find out whether migrations are enabled on the data table: + +- **Enabled**: make every schema change (CREATE, ALTER, DROP, anything but row data) as a new migration. A change made with plain SQL exists in that one database only, and the history no longer describes it. +- **Not enabled**: schema changes are plain SQL. Enabling migrations is a workspace admin's decision, made in the Data Tables settings, not a step to take on the way to something else. + +Writing a migration: + +- Wrap the statements in `BEGIN; ... END;` so it applies atomically. Leave the frame out only for a statement that cannot run in a transaction, such as `CREATE INDEX CONCURRENTLY`: such a migration can fail half applied. +- Give it a `down` that undoes the `up` whenever the change is reversible. Without one it cannot be rolled back. +- Declare the schemas it changes on a leading line of its `up`, `-- schemas sales, billing`, and qualify every name with its schema (`sales.orders`). A migration waits only on earlier migrations whose schemas overlap its own. One that declares none applies to the whole database and every later migration waits for it, so leave the line out only for a change that really spans the database, such as an extension. +- Migrations apply oldest first. One that is applied is not edited: correct it with a new migration. +- Row data is not schema. Insert, update and delete rows with plain SQL, migrations or not. +<!-- cli-only --> + +`wmill datatable migrate new <name>` scaffolds `migrations/datatable/<datatable>/<timestamp>_<name>.up.sql` and `.down.sql`, `wmill datatable migrate up` pushes the local files and applies what is pending, `wmill datatable migrate down` rolls back the most recent one and `wmill datatable migrate status` lists them. All take `-d <datatable>` and default to `main`. `migrate new --schemas sales,billing` writes the `-- schemas` line, and `migrate up --schema sales` applies only the pending migrations declaring that schema. +<!-- /cli-only --> + +## A migration is not a draft + +A migration is saved to the workspace and changes the database as soon as it is applied, for everything that reads those tables. To try a schema out without touching tables already in use: + +- put the new tables in a schema of their own, created by the same migration (`CREATE SCHEMA IF NOT EXISTS`), and point what you are building at it. A raw app names its schema in its `data` config, which is why a new app gets a new schema by default; +- or work in a workspace fork whose data table was cloned when the fork was created ("Clone schema only" or "Clone schema and data"): migrations applied there change that copy alone, and reach the parent workspace when the fork is merged. A fork that kept the original data table points at the parent's database, so a migration applied in it changes the parent's tables at once. + +Altering or dropping a table other scripts or apps use is neither of those: say what depends on it before doing it. + +## Roles and permissions + +Data table roles are a self-hosted Enterprise Edition feature, for data tables on managed Postgres (the instance database or the external managed instance). Without them, and always on a data table backed by a Postgres resource, everyone who can use the data table reaches all of it: there is no per-user, per-schema or per-row access to promise. + +A data table under roles is reached as a Postgres role, and Postgres enforces what that role was granted: + +- roles are assigned, per data table, to users, groups or folders. `admin` is the connection the data table had before roles: it owns the existing objects and ignores grants; +- a connection either names a role (`wmill.datatable('main', { role: 'analyst' })`, `role='analyst'` in Python, `datatable://main?role=analyst`) and holds that role alone, or names none and is resolved from the data table's default role; +- `permission denied` means the role in use lacks a grant. Say which role and which object: the grant is a data table admin's to give, in the roles drawer of the Database Manager. Do not switch to `admin` to get past it; +- a migration runs as the role its SQL declares on its first line, `-- role <name>`, the same one in its `down`. One that declares none runs as `admin`, which only those who may use `admin` can do. + +Read the Permissions section of https://www.windmill.dev/docs/core_concepts/persistent_storage/data_tables before designing who reaches what: it covers tenants, grants, the default role and the roles a connection that names none ends up holding, rows that differ per viewer through row-level security, and how forks and raw apps behave under roles. diff --git a/system_prompts/base/flow-base.md b/system_prompts/base/flow-base.md index ff10f38062..80a83e948a 100644 --- a/system_prompts/base/flow-base.md +++ b/system_prompts/base/flow-base.md @@ -149,6 +149,10 @@ needs becomes unreachable. references. A spread, a call or a computed key leaves the composer unable to tell which input feeds which field, so it offers no control at all — a bare `flow_input.x` for the whole object is read instead as that one input carrying every field +- A step linked to a saved agent (`agent` set) has no `provider` of its own. It exposes the same + two controls through its `model` and `reasoning_effort` inputs, which replace what the agent + saved: `"model": { "type": "javascript", "expr": "flow_input.model" }`. An empty model keeps the + saved one, an empty effort sends none, and the provider resource always stays the agent's - `memory` is what lets the agent see earlier turns; without it every message starts from nothing - `streaming` on makes the answer and its thinking appear token by token instead of all at once - `user_attachments` points at a flow input typed as an array of s3 objects @@ -598,6 +602,14 @@ In the flow schema, set the property type to `"object"` with format `"resource-{ } ``` +### When No Resource Type Fits + +A connection still comes in as one resource input, not as separate string inputs (a URL, a token) or a variable read inside a step: type the input `resource-c_<name>` with a custom resource type holding the service's connection fields, its secret in a variable the resource references. The `c_` prefix of custom types keeps one apart from a hub type synced later under the same name. + +- If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. +- Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it. +- A plain variable is fine when the user asks for it. + ### As Step Input (Static Reference) Reference a specific resource using `$res:` prefix: diff --git a/system_prompts/base/pipeline-base.md b/system_prompts/base/pipeline-base.md index 01e9797e32..59924faf41 100644 --- a/system_prompts/base/pipeline-base.md +++ b/system_prompts/base/pipeline-base.md @@ -7,10 +7,48 @@ A **data pipeline** is NOT a flow. A flow is one runnable that orchestrates step A pipeline node that produces a table should almost always be a **`duckdb`** node that materializes its output into a **DuckLake** table with `-- materialize ducklake://<name>/<table>` (in a DuckDB node the annotation uses SQL `--` comment syntax; write the body as a bare `SELECT` and let the runtime do the write). DuckLake is the default lakehouse store for pipelines and is the shape the pipeline editor is built around, so prefer it unless the work specifically calls for something else: - `postgresql` / data tables — only for row-level, OLTP-style mutations against an existing Postgres data table (frequent single-row upserts/updates, transactional reads that an app queries live). -- `bun` / `python3` — only for non-tabular work that doesn't map to SQL: calling an external API, wrangling files, arbitrary glue. When such a node still produces tabular data for downstream steps, land it in DuckLake (write it with the wmill SDK / ducklake helpers) rather than inventing a parallel store. +- `bun` / `python3` — only for work that doesn't map to SQL: calling an external API, wrangling files, arbitrary glue. When such a node produces tabular data for downstream steps, write it **straight into DuckLake** (or a data table) from the same script — see "Ingesting from Python / TypeScript" below — rather than inventing a parallel store. Do not spread a pipeline across postgres, S3, and DuckLake when one DuckLake lake would do; a consistent DuckLake lakehouse is the goal. +## Ingesting from Python / TypeScript + +A node that fetches data in code (an API, a SaaS export, a scraper) writes the rows **directly** into their DuckLake table with `wmill.ducklake()`, or into a data table with `wmill.datatable()`. DuckLake already stores every table as parquet files in the workspace object storage, so **never stage the raw payload first** — no intermediate JSON / CSV / parquet file in S3 and no second "load the raw file" node. One ingestion node, one table. + +Pass the rows as a query argument (a list of dicts / array of objects is sent as JSON) and let SQL unnest them; declare the column types so the table gets a real schema: + +```python +# pipeline +# on schedule +import wmill + +def main(): + rows = fetch_charges() # list[dict] + lake = wmill.ducklake() + lake.query(""" + CREATE OR REPLACE TABLE stripe_charges AS + SELECT unnest(from_json($rows, '[{"id":"VARCHAR","amount":"BIGINT","created":"BIGINT"}]'), recursive := true) + """, rows=rows).fetch() +``` + +```ts +// pipeline +// on schedule +import * as wmill from "windmill-client" + +export async function main() { + const rows = await fetchCharges() + const lake = wmill.ducklake() + await lake`CREATE OR REPLACE TABLE stripe_charges AS + SELECT unnest(from_json(${rows}, '[{"id":"VARCHAR","amount":"BIGINT","created":"BIGINT"}]'), recursive := true)`.fetch() +} +``` + +- Use `INSERT INTO <table> SELECT ...` instead of `CREATE OR REPLACE` to append (an incremental pull), with a one-time `CREATE TABLE IF NOT EXISTS` first. +- Assign the client to a variable (`lake = wmill.ducklake()`) and keep the SQL a **string literal** (Python) or a template without `sql.raw` (TS): that is what lets the graph record the node's write to `ducklake://main/<table>`. A chained `wmill.ducklake().query(...)` or SQL built in a variable records no output, so the downstream edge never forms. +- `wmill.ducklake("<name>")` targets a non-default catalog; `wmill.datatable("<name>")` writes a Postgres data table the same way (Python `db.query(sql, *args)` with `$1` placeholders, TS the same template form) — use it only when the data belongs in Postgres (see above). +- The downstream node triggers on the table itself: `-- on ducklake://main/stripe_charges`. + ## Storage prerequisites A DuckLake pipeline only runs once the workspace has **object storage** (S3 / Azure Blob / GCS) **and a DuckLake catalog** configured — DuckLake tables and `s3://` assets can't be materialized or read without it. Check which DuckLake catalogs the workspace has before you build. @@ -56,7 +94,7 @@ The key must be a **string literal** — the graph parser is static and cannot f ## Materialize (the managed output) -> **A MANAGED `// materialize` is DuckDB-only**, and its target must be a DuckLake table (`ducklake://<name>/<table>`). Deploy **rejects** a `ducklake://` `// materialize` on any other language (`python3`, `bun`, `postgresql`). For a non-DuckDB node writing the lake, do **not** use `// materialize` — write the output via the SDK (`wmill.writeS3File(...)`, ducklake helpers, …) and let it be inferred. Use `duckdb` when a node should materialize a DuckLake table. +> **A MANAGED `// materialize` is DuckDB-only**, and its target must be a DuckLake table (`ducklake://<name>/<table>`). Deploy **rejects** a `ducklake://` `// materialize` on any other language (`python3`, `bun`, `postgresql`). For a non-DuckDB node writing the lake, do **not** use `// materialize` — write the table itself with `wmill.ducklake()` (see "Ingesting from Python / TypeScript") and let the output be inferred. Use `duckdb` when a node should materialize a DuckLake table. > > The one target ANY language may declare (except a dbt script, whose writes come from its manifest) is a **warehouse relation**: `// materialize manual dbt://<warehouse>/<schema>/<name>`, where `<warehouse>` is a warehouse the workspace configures under Settings → dbt. `manual` is the only mode it has — nothing generates warehouse DDL, so the node issues its own write (a postgresql `CREATE TABLE` / `INSERT`, an SDK load, …) and the annotation records the outcome. Use it on an ingestion node whose output a dbt project reads as a `source`: the declared relation and the dbt model land on ONE graph node, and a downstream `// on dbt://<warehouse>/<schema>/<name>` fires when the ingestion node completes. diff --git a/system_prompts/base/raw-app-cli.md b/system_prompts/base/raw-app-cli.md index 59ef0acb58..8bd1a23cf0 100644 --- a/system_prompts/base/raw-app-cli.md +++ b/system_prompts/base/raw-app-cli.md @@ -12,7 +12,7 @@ You need three values to run the command: 1. **summary** — a short description of the app 2. **path** — the windmill path, e.g. `f/folder/my_app` or `u/username/my_app` -3. **framework** — one of `react19` (recommended), `react18`, `svelte5`, `vue` +3. **framework** — one of `react19` (recommended), `react18`, `svelte5` **summary and path**: if the user's request did not supply them, ask. Do not guess values and do not invent paths. @@ -84,7 +84,7 @@ my_app__raw_app/ ├── DATATABLES.md # Database schemas (run 'wmill app generate-agents' to refresh) ├── raw_app.yaml # App configuration (summary, path, data settings) ├── index.tsx # Frontend entry point -├── App.tsx # Main React/Svelte/Vue component +├── App.tsx # Main React/Svelte component ├── index.css # Styles ├── package.json # Frontend dependencies ├── wmill.ts # Auto-generated backend type definitions (DO NOT EDIT) @@ -147,6 +147,8 @@ fields: value: "default_user" ``` +`viewer_data_access: true` makes an inline runnable read data tables and object storage as the person using the app instead of as the app's identity (see "Reading data as the viewer"). + ### Referencing existing scripts To use an existing Windmill script instead of inline code: @@ -183,7 +185,7 @@ data: - `<datatable>/<table>` — Specific table in public schema - `<datatable>/<schema>:<table>` — Table in specific schema -**Roles:** when a datatable is under roles, its queries run as a role, which only reaches what it was granted. `roles` records the role the app uses each datatable through; the app's code must pass the same role: `wmill.datatable('main', { role: 'analyst' })` in TypeScript, `wmill.datatable('main', role='analyst')` in Python. A datatable without an entry is used as its default role. +**Roles:** when a datatable is under roles, its queries run as a role, which only reaches what it was granted. `roles` records the role the app uses each datatable through; the app's code must pass the same role: `wmill.datatable('main', { role: 'analyst' })` in TypeScript, `wmill.datatable('main', role='analyst')` in Python. A datatable without an entry is used as its default role, if it has one, plus the roles of the app's identity, or of whoever is using the app for a runnable with `viewer_data_access: true`, unless that default is `admin`. ## SQL Migrations (sql_to_apply/) diff --git a/system_prompts/base/raw-app.md b/system_prompts/base/raw-app.md index 03bde6ec71..dc70d0b94d 100644 --- a/system_prompts/base/raw-app.md +++ b/system_prompts/base/raw-app.md @@ -1,6 +1,6 @@ # Windmill Raw Apps -Raw apps let you build custom frontends with React, Svelte, or Vue that connect to Windmill backend runnables and datatables. +Raw apps let you build custom frontends with React or Svelte that connect to Windmill backend runnables and datatables. ## App shape @@ -16,7 +16,7 @@ A new app gets the setup Windmill's own new-app dialog gives one: a framework, t ### Framework -Use the framework the user named. When they named none, follow what there is to follow: the app being edited, or the apps the request points at. With nothing to follow, use **React 19**, the recommended default, **without asking**. React 18, Svelte 5 and Vue are for when they are asked for. +Use the framework the user named. When they named none, follow what there is to follow: the app being edited, or the apps the request points at. With nothing to follow, use **React 19**, the recommended default, **without asking**. React 18 and Svelte 5 are for when they are asked for. These three are the only frameworks the raw app bundler builds. When the user asks to build or convert an app in another framework, write no code in it: say it is not available and offer these three instead. ### Data setup @@ -54,7 +54,7 @@ An app the user just started from the new-app dialog is already set up: its file ### Entrypoint -The entrypoint is `index.tsx` for React and `index.ts` for Svelte and Vue. It is both the bundling entrypoint (the bundler is esbuild) and the **mount** entrypoint: the preview executes the bundle against an empty `<div id="root">` and auto-renders nothing, so the entrypoint must mount a top-level `App` itself. Keep the UI in `App.tsx` / `App.svelte` / `App.vue` and keep the entrypoint as the mount shim. +The entrypoint is `index.tsx` for React and `index.ts` for Svelte. It is both the bundling entrypoint (the bundler is esbuild) and the **mount** entrypoint: the preview executes the bundle against an empty `<div id="root">` and auto-renders nothing, so the entrypoint must mount a top-level `App` itself. Keep the UI in `App.tsx` / `App.svelte` and keep the entrypoint as the mount shim. React (`index.tsx`): @@ -66,10 +66,12 @@ import App from './App' createRoot(document.getElementById('root')!).render(<App />) ``` -Svelte (`index.ts`): `mount(App, { target: document.getElementById('root')! })`. Vue (`index.ts`): `createApp(App).mount('#root')`. +Svelte (`index.ts`): `mount(App, { target: document.getElementById('root')! })`. **Never replace the entrypoint with a bare component** (`export default function App() { ... }` and no mount call). A component that is defined but never mounted renders a blank screen with **no error thrown** — it never executes, so nothing reaches the console or the error overlay. If an app renders blank, check that the entrypoint still mounts `App` into `#root`. +**Set the browser tab title with `document.title = '...'`** (or a `<title>` the framework renders into `<head>`). The app has no `index.html` of its own, so a `<title>` written there is never served; the deployed app's page shows whatever `document.title` holds, and follows it when it changes. + **Always begin every React file (`.tsx`/`.jsx`) that uses JSX with `import React from 'react'`.** esbuild uses the classic JSX transform, so `React` must be in scope wherever JSX appears — a missing import compiles fine but throws `React is not defined` at runtime, leaving a blank screen. ### Generated bindings (`wmill.d.ts` / `wmill.ts`) @@ -139,16 +141,16 @@ Apply it to customer data, internal notes and anything else a viewer of the demo ### Chat UIs over a flow in chat mode -A flow deployed with chat mode on is a chat backend (streaming answer, tool calls, memory, conversation history). Do not drive it through a runnable: add `windmill-chat` to `package.json` and use it directly, it detects the app's Windmill and credential. +A flow deployed with chat mode on is a chat backend (streaming answer, tool calls, memory, conversation history). Do not drive it through a runnable: add `@windmill-labs/chat-sdk` to `package.json` and use it directly, it detects the app's Windmill and credential. ```tsx -import { useWindmillChat } from 'windmill-chat/react' +import { useWindmillChat } from '@windmill-labs/chat-sdk/react' const chat = useWindmillChat({ flowPath: 'f/support/assistant' }) // chat.messages ({ role, content, pending, success, tool? }), chat.status, chat.sendMessage(text), chat.stop() ``` -`windmill-chat/ai-sdk` gives a `ChatTransport` for the Vercel AI SDK's `useChat`, `windmill-chat/assistant-ui` a runtime for assistant-ui. The flow must be deployed, not a draft. A sandboxed app needs `jobs:run` in its frontend SDK scopes, plus `flow_conversations:write` for the conversation sidebar; without them the chat keeps history in the browser. +`@windmill-labs/chat-sdk/ai-sdk` gives a `ChatTransport` for the Vercel AI SDK's `useChat`, `@windmill-labs/chat-sdk/assistant-ui` a runtime for assistant-ui. The flow must be deployed, not a draft. A sandboxed app needs `jobs:run` in its frontend SDK scopes, plus `flow_conversations:write` for the conversation sidebar; without them the chat keeps history in the browser. ## Backend runnables @@ -191,6 +193,10 @@ def main(user_id: str): return user ``` +#### Sharing code between runnables + +An inline runnable can import another inline runnable of the same app by its id, as a relative import: `import { getDb } from './shared'` (TypeScript, Bun) or `from .shared import get_db` (Python). This works across TypeScript (Bun) runnables and across Python runnables, not between the two. The imported runnable's own dependencies are picked up, and it can import further runnables in turn. A runnable that only holds helpers needs no `main`; the frontend just never calls it. A TypeScript runnable whose id is `main` cannot be imported, because that name is taken by the entrypoint file of every TypeScript job: give shared code any other id. + #### The `wmill` client is already authenticated An inline runnable runs as an ordinary Windmill job. `import * as wmill from 'windmill-client'` (TypeScript) and `import wmill` (Python) are already pointed at this instance and this workspace — there is nothing to configure. @@ -238,6 +244,39 @@ Either one lets those people run the app's backend runnables, so never open an a <!-- chat-only --> When a deploy widens who may open the app, tell the user in plain words. <!-- /chat-only --> +<!-- cli-only --> + +An app's custom URL is not in `raw_app.yaml`: each workspace has its own file next to the app folder, `<app path>.<workspace>.custom_path.yaml` (for example `f/sales/dashboard.prod.custom_path.yaml` holding `custom_path: dashboard`), where `<workspace>` is the workspace's name in `wmill.yaml`, or its id. A push applies only the target workspace's file and leaves the deployed custom URL alone when there is none, so deleting the file does not remove the URL: `custom_path: ''` does. Setting or clearing one takes a workspace admin. +<!-- /cli-only --> + +## Sandbox isolation and frontend API access + +New apps are sandboxed: the frontend is isolated from the viewer's own Windmill session and reaches Windmill only through its backend runnables, plus whatever frontend API scopes the app declares, which each viewer approves before the app runs. With isolation turned off, the frontend runs with the viewer's full session. The scopes are `jobs:run`, `jobs:read`, `resources:read`, `variables:read`, `flow_conversations:read` and `flow_conversations:write`; grant only the ones the frontend calls. The viewer's identity needs no scope: it is in `window.ctx`, and whoami works with any of them. + +Inside the sandbox, IndexedDB is unavailable, third-party sign-in and OAuth redirects fail, and requests to other services carry `Origin: null`, which an API that checks the origin rejects. Work around these first: call the service from a backend runnable, keep state in a data table or `localStorage`, or grant the frontend API scope the code needs. Suggest turning isolation off only when none of that works, and say plainly that it is a security risk: the app's code, and any XSS bug in it, then runs with the full Windmill permissions of everyone who opens the app. +<!-- chat-only --> +You cannot turn isolation off; the user does it in the app's deploy settings. +<!-- /chat-only --> +<!-- cli-only --> +In `raw_app.yaml`: + +```yaml +sandbox: true +frontend_api: [jobs:run] +``` + +A file with a `sandbox` key states both settings: `sandbox: false` turns isolation off, and a missing `frontend_api` means no scopes. A file without the key leaves the deployed app's isolation and scopes as they are, so removing `sandbox: true` does not unsandbox it. `frontend_api` needs `sandbox: true`; the push fails otherwise. +<!-- /cli-only --> + +## Reading data as the viewer + +A backend runnable reads data as the app's identity (the publisher in publisher mode), the same for every viewer. An inline runnable can instead read data as the person using the app: its data table connections that name no role hold that viewer's roles, and object storage permission rules (which paths may be listed, read, written) are checked against the viewer. Resources, variables and everything else stay the app's, and an anonymous viewer is refused. Turn it on only when what the runnable reads should differ per viewer: row-level security on a data table, or per-user paths in object storage. Both are Enterprise Edition features. +<!-- chat-only --> +Set it with `viewerDataAccess: true` on the backend runnable. +<!-- /chat-only --> +<!-- cli-only --> +Set it with `viewer_data_access: true` in the runnable's `backend/<id>.yaml`. +<!-- /cli-only --> ## Data Tables @@ -250,6 +289,7 @@ Data tables are PostgreSQL databases managed by Windmill. Backend runnables quer 3. **No DDL inside runnables**: runnables only read and write rows (SELECT, INSERT, UPDATE, DELETE) on existing tables. Never CREATE, ALTER or DROP a table from a runnable. 4. **Qualify table names**: an unqualified name means the `public` schema, so write every other table as `schema.table`, in table creation and queries alike. The app's `data` config sets the default datatable and schema its tables go in; use them consistently across runnables. 5. **Pass the role**: when the app's `data.roles` gives a data table a role, every `wmill.datatable` call on it passes that role (`wmill.datatable('main', { role: 'analyst' })` in TypeScript, `wmill.datatable('main', role='analyst')` in Python). The role only reaches what it was granted, so a query outside it fails with `permission denied`. +6. **Per-viewer rows**: a data table with no entry in `data.roles` is called with no role. Unless its default role is `admin`, the connection then holds the default role, if it may use it, plus every role it is a tenant of, and is refused when that is none. Whose roles those are follows the runnable's identity (see "Reading data as the viewer"). Row-level security policies written as `pg_has_role(current_user, '<role>', 'member')` then return the right rows with nothing added to the code. A role pins the connection to that one role either way, so a data table whose rows should differ per viewer gets no `data.roles` entry. Data table roles are an Enterprise Edition feature, self-hosted only. <!-- cli-only --> `wmill datatable list` lists the workspace's data tables. Create or change tables with a migration in `sql_to_apply/` (see "SQL Migrations" above), then add them to `data.tables` in `raw_app.yaml`. @@ -305,4 +345,4 @@ def main(user_id: str): 7. **Mark sensitive UI with `data-wm-no-record`** — it is what keeps that data out of a recorded demo; passwords are handled for you. 8. **Reach for `backendAsync` + `waitJob`** for long work — never a hand-written job-polling runnable. 9. **Deploy what a path runnable points at** — a path runnable aimed at a draft fails at runtime; tell the user what needs deploying. -10. **Use `windmill-chat` for a chat over a chat-mode flow** — never a runnable that runs the flow and polls its stream. +10. **Use `@windmill-labs/chat-sdk` for a chat over a chat-mode flow** — never a runnable that runs the flow and polls its stream. diff --git a/system_prompts/base/resources.md b/system_prompts/base/resources.md index 2929051a03..652bec1964 100644 --- a/system_prompts/base/resources.md +++ b/system_prompts/base/resources.md @@ -31,6 +31,12 @@ Example: `f/databases/postgres_prod.resource.json` - `value` - Object containing the resource configuration - `resource_type` - Name of the resource type (e.g., "postgresql", "slack") +## Agents + +An agent, as the Agents page lists it, is a resource of type `ai_agent`. Its value holds the +agent's provider, system prompt, tools and memory settings, and a flow step uses a saved agent by +linking its path. + ## Variable References Reference variables in resource values: @@ -213,13 +219,23 @@ The prefix must be on the string itself. } ``` +## When No Resource Type Fits + +The Windmill Hub publishes resource types for most services, and an instance gets them by syncing with the hub. When none fits the service: + +- If the instance is reported as not having synced the hub's types, mention that a superadmin can sync them: the hub most likely has one for the service. That holds for a type a hub script takes too: it is missing here until the sync, so say so before asking for a resource of it. Create one of your own only if the user still wants it, since after a sync the workspace would hold both. +- Otherwise, or when the user prefers it to syncing, propose a custom resource type named `c_<name>` holding the service's connection fields (base URL, account or region identifiers, credentials), as in "Custom Resource Types" below, and ask the user before creating it: every resource of that type and every script taking one depends on its fields. +- A plain variable instead of a resource is fine when the user asks for it; without that, default to the resource, its secret in a variable it references. + ## Custom Resource Types +A custom type's name starts with `c_`: the hub's types reach every instance under their plain names, so the prefix keeps a custom type from clashing with one synced later. Scripts and flows refer to the full name: `format: resource-c_custom_api`, `RT.CCustomApi` in TypeScript, a `c_custom_api` TypedDict in Python. + Create custom resource types with JSON Schema: ```json { - "name": "custom_api", + "name": "c_custom_api", "schema": { "type": "object", "properties": { @@ -233,7 +249,7 @@ Create custom resource types with JSON Schema: } ``` -Save as: `custom_api.resource-type.json` +Save as: `c_custom_api.resource-type.json` ## OAuth Resources diff --git a/system_prompts/base/script-base.md b/system_prompts/base/script-base.md index 9bd878ea9b..0a9f313228 100644 --- a/system_prompts/base/script-base.md +++ b/system_prompts/base/script-base.md @@ -3,6 +3,11 @@ ## General Principles - A script's inputs are its parameters. Credentials and configuration come in as resource-typed parameters, never hard-coded or read from the environment; the language section below shows how that language declares parameters +- When no resource type exists for a service, still take its connection as one resource-typed parameter, of a custom type holding the connection fields (base URL, account identifiers, credentials), its secret in a variable the resource references. A custom type is named `c_<name>`, which keeps it apart from a hub type synced later: the parameter takes `RT.C<Name>` in TypeScript, a `c_<name>` TypedDict in Python. A plain string parameter or a variable read inside the code only when the user asks for it: the resource keeps a connection's fields together, lets whoever runs the script pick an existing connection, and keeps the secret out of the arguments a run records. If the instance is reported as not having synced the Windmill Hub's resource types, mention that a superadmin can sync them, since the hub has types for most services. Otherwise, or when the user prefers it to syncing, propose the resource type and ask before creating it +- A Windmill Hub script takes a resource type the hub publishes, so on an instance that has not synced the hub's types that type is missing: say so, and that a superadmin can sync them, before asking for a resource of it. Hub scripts often declare the type inline (`type Stripe = { token: string }`), which is still the `stripe` resource type; in code you write, name it the way the language section shows (`RT.Stripe` in TypeScript) rather than copying the inline declaration +<!-- cli-only --> +- Before relying on a resource type, a hub script's included, run `wmill resource-type list`: it shows whether the workspace has the type, and warns when the instance has not synced the hub's types +<!-- /cli-only --> - Libraries are installed automatically - do not show installation instructions - In a language with an entrypoint function (TypeScript, Python, Go, Rust, PHP, R, …), name it `main` (`Main` in C#) and do not call it; in TypeScript it must be async. SQL, GraphQL, Bash, PowerShell and Ansible scripts have no `main`: their language section shows how they take arguments - Where the language has a Windmill client (`wmill`), use it to interact with the platform diff --git a/system_prompts/base/workflow-as-code.md b/system_prompts/base/workflow-as-code.md index 0e529f6803..efc29df360 100644 --- a/system_prompts/base/workflow-as-code.md +++ b/system_prompts/base/workflow-as-code.md @@ -95,6 +95,8 @@ async def enrich(customer_id: str): In TypeScript, prefer assigning each task to a named top-level const. In Python, prefer top-level async functions decorated with `@task()` or `@task`. +Only the workflow body dispatches steps. A task runs as a single job, so a task or `step()` called from inside a task body runs in place in that job, as a plain function call: no child job, no checkpoint, and its task options (retry, timeout, tag) do not apply. `sleep()` there waits in the job, and `taskScript()` / `taskFlow()` / `waitForApproval()` (`task_script()` / `task_flow()` / `wait_for_approval()`) throw. To get separate jobs, call the tasks one after another from the workflow body and pass results between them. + For existing scripts: ```typescript diff --git a/system_prompts/base/workspace-settings.md b/system_prompts/base/workspace-settings.md new file mode 100644 index 0000000000..ba4e863b85 --- /dev/null +++ b/system_prompts/base/workspace-settings.md @@ -0,0 +1,81 @@ +# Workspace settings + +Everything an admin sets on the Workspace settings page is one document: a mapping of top-level +keys, the same layout as the `settings.yaml` file `wmill sync` keeps. Only a workspace admin can +read or change it. + +## Applying a document + +- A partial document changes only the keys it states; every key it omits is left as it is. +- Each key is replaced whole, so read its current value and send it back edited: a nested object + given with one field replaces the stored object with that one field. +- A key set to `null` clears that setting; an on/off switch cleared this way reads as `false`. +- Each setting is written through the same path the settings page uses, with the same validation + and audit log. The writes are not one transaction: when one fails the apply stops, and the + error says what was already written. +- A dry run reports the changes, as `before` / `after` per key, without writing anything. +- `name` is never applied: rename a workspace on the settings page. `color` is applied only when + set to a value, so `null` does not clear it. +- A key the server does not know is ignored and named in the warnings: check them, since a typo + otherwise reads as "nothing to change". +- A setting this edition does not offer (Enterprise only) is refused, by the dry run too. + +## Secrets + +`slack_oauth_client_secret` is the one secret. A read shows `__SENSITIVE_AND_UNCHANGED__` in place +of a set secret; sending that placeholder back keeps the stored value. A value starting with +`$encrypted:` is decrypted with the workspace key, and one encrypted with another workspace's key +is left unchanged with a warning; any other value is taken as plaintext. Never +write a secret you were not given: keep the placeholder. + +## Keys + +| Key | Value | +|---|---| +| `auto_invite` | `{ enabled, mode: invite \| add, operator, instance_groups?, instance_groups_roles? }`. The instance groups are managed only when `instance_groups` is stated; clearing a group removes the members it added. | +| `error_handler` / `success_handler` | `{ path, extra_args?, muted_on_cancel?, muted_on_user_path? }`, `path` being `script/<path>` or `flow/<path>`. | +| `error_handler_fallback_to_instance_alerts` | Report failures to the instance critical alert channels when no error handler is set. | +| `webhook` | URL POSTed a JSON event on every change to the workspace's items. | +| `ai_config` | Providers, default and completion models, custom prompts, `copilot_disabled`. | +| `large_file_storage` | Workspace object storage: `{ type, s3_resource_path \| azure_blob_resource_path \| gcs_resource_path, public_resource?, secondary_storage?, advanced_permissions? }`. | +| `git_sync` | `{ repositories: [...] }`, each with `git_repo_resource_path`, `script_path` and `settings` (include/exclude paths and types). Server-owned fields (webhook secrets, sync state, credentials) are never read nor written. | +| `datatable` | `{ datatables: { <name>: { database: { resource_type, resource_path? } } } }`. Role permissions are `datatable_permissions`. | +| `datatable_permissions` | `{ <data table>: { default_role, roles: { <role>: [tenants] } } }`: who may connect to each data table as which role. Tenants are `u/<user>`, `g/<group>`, `f/<folder>` or `*`; `admin` is always a role, and `default_role: null` means no default. A data table the value omits is no longer under roles. Only a data table on a cluster Windmill manages can be. | +| `protection_rules` | `{ <rule name>: { rules: [...], bypass_groups: [...], bypass_users: [...] } }`, rules among `DisableDirectDeployment`, `DisableWorkspaceForking`, `RestrictDeployToDeployers`, `RestrictAnonymousAppDeployment`, `RestrictPublicRunSharing`, `RestrictGuestAppDeployment`, `RequireIsolatedForks`. A rule the value omits is deleted. The dev workspace lock is not listed and cannot be set here. | +| `ducklake` | `{ ducklakes: { <name>: { catalog, storage, ... } } }`. | +| `dbt_warehouses` | dbt warehouse connections. | +| `default_app` | Path of the app shown as the workspace home. | +| `default_scripts` | `{ order?, hidden?, default_script_content? }` for the script language picker. | +| `deploy_ui` | `{ include_path?, include_type? }`: what the deploy-to-workspace UI offers. | +| `operator_settings` | What operators see and do: page visibility flags (`runs`, `schedules`, `resources`, `variables`, `assets`, `audit_logs`, `groups`, `folders`, `workers`, `triggers`) and write rights (`manage_schedules`, `manage_triggers`, `builder_flows`, `builder_apps`). A write right the value omits keeps its stored value. | +| `mute_critical_alerts` | Mute the workspace's critical alerts. | +| `slack_team_id`, `slack_name` | Read only: set by connecting Slack on the settings page. | +| `slack_command_script` / `teams_command_script` | Script or flow handling the Slack / Teams command. | +| `slack_oauth_client_id` / `slack_oauth_client_secret` | The workspace's own Slack OAuth app. Clearing either removes both. | +| `public_app_execution_limit_per_minute` | Rate limit for public apps, `null` for none. | +| `guest_access_enabled`, `guest_jwt_public_key`, `guest_jwt_jwks_url` | Guest access to public apps and the key that signs guest JWTs. | +| `add_admins_and_developers_to_forks` | Add the workspace's admins and developers to each fork. | +| `color` | Workspace color, `#rrggbb`. | +<!-- cli-only --> + +## From the command line + +`wmill workspace get-settings` prints the document (`--encrypted` for secrets encrypted with the +workspace key, `--json` for JSON). `wmill workspace apply-settings <file>` applies a partial +document from a YAML or JSON file: it shows the changes and asks before writing (`--dry-run` to +only show them, `-y` to skip the question, `--replace` to clear what the file omits). + +## In a synced repository + +With `includeSettings: true` in `wmill.yaml`, `wmill sync pull` writes the document to +`settings.yaml`, secrets encrypted with the workspace key (plaintext only with `plainSecrets`), and +`wmill sync push` applies it. Unlike a partial apply, a push treats the file as the whole +document: a setting the file omits is cleared, except `operator_settings`, `color`, the auto-invite +instance groups, and the keys `ducklake`, `dbt_warehouses`, `deploy_ui`, `teams_command_script`, +`public_app_execution_limit_per_minute`, `guest_access_enabled`, `guest_jwt_public_key`, +`guest_jwt_jwks_url`, `error_handler_fallback_to_instance_alerts` and +`add_admins_and_developers_to_forks`, which are managed only when the file states them. +`datatable_permissions` is pushed only with `includeDatatablePermissions: true` (or +`--include-datatable-permissions`). A push ignores `protection_rules`: `protection-rules.yaml` and +`wmill protection-rules push` sync them. +<!-- /cli-only --> diff --git a/system_prompts/generate.py b/system_prompts/generate.py index 918deef0fb..7249954d01 100644 --- a/system_prompts/generate.py +++ b/system_prompts/generate.py @@ -1696,6 +1696,18 @@ TOPICS: dict[str, dict] = { 'chat_helper': 'getPipelinePrompt', 'parts': ['pipeline-base.md'], }, + 'datatable': { + 'skill': 'datatables', + 'description': "MUST use when changing a data table's schema, writing or running its migrations, or working with its roles and permissions.", + 'chat_helper': 'getDatatablePrompt', + 'parts': ['datatable.md'], + }, + 'workspace_settings': { + 'skill': 'workspace-settings', + 'description': 'MUST use when reading or changing workspace settings, or the settings.yaml file `wmill sync` keeps.', + 'chat_helper': 'getWorkspaceSettingsPrompt', + 'parts': ['workspace-settings.md'], + }, 'cli_commands': { 'skill': 'cli-commands', 'description': 'MUST use when using the CLI, including debugging job failures and inspecting run history via `wmill job`.', @@ -1715,6 +1727,8 @@ CHAT_CONSTANTS = { 'resources.md': 'RESOURCES_BASE', 'raw-app.md': 'RAW_APP_BASE', 'pipeline-base.md': 'PIPELINE_BASE', + 'datatable.md': 'DATATABLE_BASE', + 'workspace-settings.md': 'WORKSPACE_SETTINGS_BASE', 'workflow-as-code.md': 'WORKFLOW_AS_CODE_BASE', 'flow-chat-special-modules.md': 'FLOW_CHAT_SPECIAL_MODULES', } @@ -2650,6 +2664,16 @@ export function getPipelinePrompt(): string { __RETURN_pipeline__ } +// Helper for data table schema changes, migrations and permissions (chat consumers) +export function getDatatablePrompt(): string { + __RETURN_datatable__ +} + +// Helper for the workspace settings document (chat consumers) +export function getWorkspaceSettingsPrompt(): string { + __RETURN_workspace_settings__ +} + // Helper to get the datatable SQL SDK reference (wmill.datatable()). // Pass a language to get only that SDK; omit it to get both. export function getDatatableSdkReference(language?: string): string { @@ -2711,6 +2735,8 @@ export declare function getFlowPrompt(): string; export declare function getResourcePrompt(): string; export declare function getRawAppPrompt(language?: string): string; export declare function getPipelinePrompt(): string; +export declare function getDatatablePrompt(): string; +export declare function getWorkspaceSettingsPrompt(): string; export declare function getDatatableSdkReference(language?: string): string; export declare function getWorkflowAsCodePrompt(language?: string): string; """ diff --git a/system_prompts/languages/bunnative.md b/system_prompts/languages/bunnative.md index af9055f01d..3d5e7bccbc 100644 --- a/system_prompts/languages/bunnative.md +++ b/system_prompts/languages/bunnative.md @@ -49,7 +49,7 @@ export async function main(url: string) { ## Pure computation: `//no_network` -A native script that only transforms its inputs can declare `//no_network` in its leading comment block (right after `//native`). The runtime then refuses every connection the script attempts: `fetch` to any host, the Windmill API (so `windmill-client` calls fail too), raw sockets and unix sockets, and `WM_TOKEN` is not set. It only takes effect on native scripts: without `//native` it is ignored. Use it only when the script needs no external data beyond its arguments: +A native script that only transforms its inputs can declare `//no_network` in its leading comment block (right after `//native`). The runtime then refuses every connection the script attempts: `fetch` to any host, the Windmill API (so `windmill-client` calls fail too), raw sockets and unix sockets, and `WM_TOKEN` is not set. Without `//native` it means something else: the script must run in an nsjail sandbox (`//sandbox`, or instance-wide sandboxing), which then loses its network, and it fails to run otherwise. Use it only when the script needs no external data beyond its arguments: ```typescript //native diff --git a/system_prompts/languages/snowflake.md b/system_prompts/languages/snowflake.md index 8ded76eb3c..b7798e3461 100644 --- a/system_prompts/languages/snowflake.md +++ b/system_prompts/languages/snowflake.md @@ -10,6 +10,27 @@ Name the parameters by adding comments before the statement: SELECT * FROM users WHERE name = ? AND age > ?; ``` +## Array parameters + +Declare a list with a `[]` suffix on the element type (`(varchar[])`, +`(int[])`), or `(array)` for an untyped one. Snowflake cannot bind an array +directly, so Windmill binds the list as JSON text: wrap the placeholder with +`PARSE_JSON(?)`, and cast to `ARRAY` where a function expects one. + +```sql +-- ? groups (varchar[]) +SELECT o.* FROM orders o +WHERE ARRAY_CONTAINS(o.owner_group::VARIANT, PARSE_JSON(?)::ARRAY); +``` + +Or join on the elements with `FLATTEN`: + +```sql +-- ? groups (varchar[]) +SELECT o.* FROM orders o +JOIN TABLE(FLATTEN(input => PARSE_JSON(?))) g ON g.value::STRING = o.owner_group; +``` + ## Receiving an S3Object as a script parameter Declare the arg with type `(s3object)`. Windmill renders an S3 file picker for diff --git a/typescript-client/build.jsr.sh b/typescript-client/build.jsr.sh index 92e11640f3..41a8eac37e 100755 --- a/typescript-client/build.jsr.sh +++ b/typescript-client/build.jsr.sh @@ -22,6 +22,6 @@ cp "${script_dirpath}/sqlUtils.ts" "${script_dirpath}/src/" echo "" >> "${script_dirpath}/src/index.ts" echo 'export type { DenoS3LightClientSettings } from "./s3Types";' >> "${script_dirpath}/src/index.ts" echo "" >> "${script_dirpath}/src/index.ts" -echo 'export { type Base64, setClient, getWorkspace, workerHasInternalServer, SHARED_FOLDER, getStatePath, getInternalState, setInternalState, getResumeEndpoints, getResult, getResultMaybe, resolveDefaultResource, databaseUrlFromResource, base64ToUint8Array, uint8ArrayToBase64, getVariable, setVariable, getResource, setResource, getResumeUrls, setState, setProgress, getProgress, getState, getIdToken, denoS3LightClientSettings, cancelJob, loadS3FileStream, loadS3File, writeS3File, deleteS3File, signS3Objects, signS3Object, getPresignedS3PublicUrls, getPresignedS3PublicUrl, task, runScript, runScriptAsync, runScriptByPath, runScriptByHash, runScriptByPathAsync, runScriptByHashAsync, type RunScriptAsyncOptions, runFlow, runFlowAsync, waitJob, getRootJobId, setFlowUserState, getFlowUserState, usernameToEmail, requestInteractiveSlackApproval, type Sql, requestInteractiveTeamsApproval, appendToResultStream, streamResult, datatable, ducklake, upsertPartition, appendPartition, type DucklakeMaterializeOptions, type SqlStatement, type DatatableSqlTemplateFunction, type SqlTemplateFunction, type S3Object, type S3ObjectRecord, type S3ObjectURI } from "./client";' >> "${script_dirpath}/src/index.ts" +echo 'export { type Base64, setClient, getWorkspace, workerHasInternalServer, SHARED_FOLDER, getStatePath, getInternalState, setInternalState, getResumeEndpoints, getResult, getResultMaybe, resolveDefaultResource, databaseUrlFromResource, base64ToUint8Array, uint8ArrayToBase64, getVariable, setVariable, getResource, setResource, getResumeUrls, setState, setProgress, getProgress, workerIsDraining, getState, getIdToken, denoS3LightClientSettings, cancelJob, loadS3FileStream, loadS3File, writeS3File, deleteS3File, signS3Objects, signS3Object, getPresignedS3PublicUrls, getPresignedS3PublicUrl, task, runScript, runScriptAsync, runScriptByPath, runScriptByHash, runScriptByPathAsync, runScriptByHashAsync, type RunScriptAsyncOptions, runFlow, runFlowAsync, waitJob, getRootJobId, setFlowUserState, getFlowUserState, usernameToEmail, requestInteractiveSlackApproval, type Sql, requestInteractiveTeamsApproval, appendToResultStream, streamResult, datatable, ducklake, upsertPartition, appendPartition, type DucklakeMaterializeOptions, type SqlStatement, type DatatableSqlTemplateFunction, type SqlTemplateFunction, type S3Object, type S3ObjectRecord, type S3ObjectURI } from "./client";' >> "${script_dirpath}/src/index.ts" diff --git a/typescript-client/build.sh b/typescript-client/build.sh index 127afe2154..f927acd26e 100755 --- a/typescript-client/build.sh +++ b/typescript-client/build.sh @@ -46,7 +46,7 @@ cp "${script_dirpath}/sqlUtils.ts" "${script_dirpath}/src/" echo "" >> "${script_dirpath}/src/index.ts" echo 'export type { DenoS3LightClientSettings } from "./s3Types";' >> "${script_dirpath}/src/index.ts" echo "" >> "${script_dirpath}/src/index.ts" -echo 'export { type Base64, setClient, getWorkspace, workerHasInternalServer, SHARED_FOLDER, getStatePath, getInternalState, setInternalState, getResumeEndpoints, getResult, getResultMaybe, resolveDefaultResource, databaseUrlFromResource, base64ToUint8Array, uint8ArrayToBase64, getVariable, setVariable, getResource, setResource, getResumeUrls, setState, setProgress, getProgress, getState, getIdToken, denoS3LightClientSettings, cancelJob, loadS3FileStream, loadS3File, writeS3File, deleteS3File, signS3Objects, signS3Object, getPresignedS3PublicUrls, getPresignedS3PublicUrl, task, taskScript, taskFlow, workflow, step, sleep, parallel, waitForApproval, getApprovalUrls, type TaskOptions, type TaskRetry, type Jsonified, type JsonifiedFn, WorkflowCtx, _workflowCtx, setWorkflowCtx, StepSuspend, runScript, runScriptAsync, runScriptByPath, runScriptByHash, runScriptByPathAsync, runScriptByHashAsync, type RunScriptAsyncOptions, runFlow, runFlowAsync, waitJob, getRootJobId, setFlowUserState, getFlowUserState, usernameToEmail, requestInteractiveSlackApproval, type Sql, requestInteractiveTeamsApproval, appendToResultStream, streamResult, datatable, ducklake, upsertPartition, appendPartition, type DucklakeMaterializeOptions, type SqlStatement, type DatatableSqlTemplateFunction, type SqlTemplateFunction, type S3Object, type S3ObjectRecord, type S3ObjectURI, commitKafkaOffsets } from "./client";' >> "${script_dirpath}/src/index.ts" +echo 'export { type Base64, setClient, getWorkspace, workerHasInternalServer, SHARED_FOLDER, getStatePath, getInternalState, setInternalState, getResumeEndpoints, getResult, getResultMaybe, resolveDefaultResource, databaseUrlFromResource, base64ToUint8Array, uint8ArrayToBase64, getVariable, setVariable, getResource, setResource, getResumeUrls, setState, setProgress, getProgress, workerIsDraining, getState, getIdToken, denoS3LightClientSettings, cancelJob, loadS3FileStream, loadS3File, writeS3File, deleteS3File, signS3Objects, signS3Object, getPresignedS3PublicUrls, getPresignedS3PublicUrl, task, taskScript, taskFlow, workflow, step, sleep, parallel, waitForApproval, getApprovalUrls, type TaskOptions, type TaskRetry, type Jsonified, type JsonifiedFn, WorkflowCtx, _workflowCtx, setWorkflowCtx, StepSuspend, runScript, runScriptAsync, runScriptByPath, runScriptByHash, runScriptByPathAsync, runScriptByHashAsync, type RunScriptAsyncOptions, runFlow, runFlowAsync, waitJob, getRootJobId, setFlowUserState, getFlowUserState, usernameToEmail, requestInteractiveSlackApproval, type Sql, requestInteractiveTeamsApproval, appendToResultStream, streamResult, datatable, ducklake, upsertPartition, appendPartition, type DucklakeMaterializeOptions, type SqlStatement, type DatatableSqlTemplateFunction, type SqlTemplateFunction, type S3Object, type S3ObjectRecord, type S3ObjectURI, commitKafkaOffsets } from "./client";' >> "${script_dirpath}/src/index.ts" # Build default export by combining client utilities + services # This preserves backward compatibility for `import wmill from "windmill-client"` @@ -63,6 +63,7 @@ import { setState, setProgress, getProgress, + workerIsDraining, getState, getIdToken, denoS3LightClientSettings, @@ -153,6 +154,7 @@ const wmill = { setState, setProgress, getProgress, + workerIsDraining, getState, getIdToken, denoS3LightClientSettings, diff --git a/typescript-client/client.ts b/typescript-client/client.ts index 4ec07d6fa6..dbb667a3aa 100644 --- a/typescript-client/client.ts +++ b/typescript-client/client.ts @@ -137,7 +137,9 @@ export async function getResource( return undefined; } else { throw Error( - `Resource not found at ${path} or not visible to you: ${e.body}` + e.status === undefined + ? `Could not reach the Windmill API to get resource ${path}: ${e.message ?? e}` + : `Resource not found at ${path} or not visible to you: ${e.body}` ); } } @@ -724,6 +726,19 @@ export async function getProgress(jobId?: any): Promise<number | null> { }); } +/** + * Whether the worker running this job has received its shutdown signal. + * A draining worker waits for its current job to finish before exiting, so a + * long-running script can poll this and return early to let the worker be replaced. + * @param jobId? Job to check, defaults to the current job + */ +export async function workerIsDraining(jobId?: string): Promise<boolean> { + return await JobService.workerIsDraining({ + id: jobId ?? getEnv("WM_JOB_ID") ?? "NO_JOB_ID", + workspace: getWorkspace(), + }); +} + /** * Set a flow user state * @param key key of the state @@ -818,7 +833,9 @@ export async function getVariable(path: string): Promise<string> { return await VariableService.getVariableValue({ workspace, path }); } catch (e: any) { throw Error( - `Variable not found at ${path} or not visible to you: ${e.body}` + e.status === undefined + ? `Could not reach the Windmill API to get variable ${path}: ${e.message ?? e}` + : `Variable not found at ${path} or not visible to you: ${e.body}` ); } } @@ -1819,6 +1836,52 @@ export function setWorkflowCtx(ctx: WorkflowCtx | null) { Reflect.set(globalThis, "__wmill_wf_ctx", ctx); } +type TaskBodyScope = { run<R>(store: true, fn: () => R): R; getStore(): true | undefined }; + +/** Marks the async context of a task body running in its child job. A flag on + * the ctx cannot stand in: the workflow body keeps replaying beside the task + * body (`Promise.all([a(), b()])`), and its calls must still park rather than + * run a sibling task's body in this job. Kept on `globalThis`, like the ctx, + * so a bundle holding two copies of this module shares one scope. Resolved + * through `process.getBuiltinModule` because a `node:` import would break + * browser bundles of this package. */ +function taskBodyScope(): TaskBodyScope | null { + const existing = Reflect.get(globalThis, "__wmill_wf_task_body"); + if (existing !== undefined) return existing; + let scope: TaskBodyScope | null = null; + try { + const AsyncLocalStorage = (globalThis as any).process?.getBuiltinModule?.("node:async_hooks")?.AsyncLocalStorage; + if (AsyncLocalStorage) scope = new AsyncLocalStorage(); + } catch {} + Reflect.set(globalThis, "__wmill_wf_task_body", scope); + return scope; +} + +function runTaskBody<R>(fn: () => R): R { + const scope = taskBodyScope(); + return scope ? scope.run(true, fn) : fn(); +} + +function insideTaskBody(): boolean { + return taskBodyScope()?.getStore() === true; +} + +/** The ctx SDK calls dispatch through, or null where they run in place: outside + * a workflow, and inside a task body, which is one job and has no rounds of its + * own to dispatch or checkpoint a step in. */ +function dispatchCtx(): WorkflowCtx | null { + if (insideTaskBody()) return null; + return _workflowCtx ?? Reflect.get(globalThis, "__wmill_wf_ctx"); +} + +function assertNotInsideTaskBody(what: string): void { + if (insideTaskBody()) { + throw new Error( + `${what} cannot be called from inside a task: a task runs as a single job and cannot suspend or dispatch steps. Call it from the workflow() body instead.`, + ); + } +} + export class WorkflowCtx { private completed: Record<string, any>; @@ -2291,11 +2354,11 @@ export class WorkflowCtx { } export async function sleep(seconds: number): Promise<void> { - const ctx: WorkflowCtx | null = _workflowCtx ?? Reflect.get(globalThis, "__wmill_wf_ctx"); + const ctx = dispatchCtx(); if (ctx) { return ctx._sleep(seconds) as Promise<void>; } - // Outside workflow context, just wait locally + // Outside a workflow, or inside a task body, just wait locally await new Promise((r) => setTimeout(r, seconds * 1000)); } @@ -2306,12 +2369,15 @@ export async function sleep(seconds: number): Promise<void> { * `fn`'s result is encoded as JSON and decoded back before it is returned, so * the round that runs the body sees the same types every replay sees: a `Date` * comes back as a string, a `Map` as `{}`. {@link Jsonified} is that shape. + * + * Called from inside a task body, `fn` runs in place and nothing is + * checkpointed: a task is a single job and is never replayed. */ export async function step<T>( name: string, fn: () => T | Promise<T>, ): Promise<Jsonified<Awaited<T>>> { - const ctx: WorkflowCtx | null = _workflowCtx ?? Reflect.get(globalThis, "__wmill_wf_ctx"); + const ctx = dispatchCtx(); if (ctx) { return ctx._runInlineStep(name, fn) as Promise<Jsonified<Awaited<T>>>; } @@ -2329,8 +2395,9 @@ export async function step<T>( * const call_api = task(fetchOrders, { retry: { attempts: 3, delay: 30, multiplier: 2 } }); * * Inside a `workflow()`, calling a task dispatches it as a step. - * Outside a workflow, the function body executes directly and - * {@link TaskOptions} — retry included — does not apply. + * Outside a workflow, or called from inside another task, the function body + * executes directly and {@link TaskOptions} — retry included — does not apply: + * a task runs as a single job, so the tasks it calls run in that same job. * * A task runs as its own job, so its result is always encoded as JSON and * decoded back before the caller sees it: a `Date` comes back as a string, a @@ -2364,7 +2431,7 @@ export function task<T extends (...args: any[]) => Promise<any>>( // .then() which throws StepSuspend and empties pending before the caller // can flush. const wrapper = function (...args: any[]) { - const ctx: WorkflowCtx | null = _workflowCtx ?? Reflect.get(globalThis, "__wmill_wf_ctx"); + const ctx = dispatchCtx(); if (ctx) { // Inside a workflow with checkpoint/replay context — dispatch as step const script = taskPath ?? taskName; @@ -2384,7 +2451,7 @@ export function task<T extends (...args: any[]) => Promise<any>>( return (async () => { let result: any; try { - result = await fn(...args); + result = await runTaskBody(() => fn(...args)); } catch (e) { if (isSuspendSignal(e, StepSuspend)) throw e; ctx._raiseStepFailure(e); @@ -2393,7 +2460,7 @@ export function task<T extends (...args: any[]) => Promise<any>>( })(); } return stepResult; - } else if (getEnv("WM_JOB_ID") && !getEnv("WM_FLOW_JOB_ID")) { + } else if (!insideTaskBody() && getEnv("WM_JOB_ID") && !getEnv("WM_FLOW_JOB_ID")) { // Inside a Windmill root job without checkpoint context — v1 HTTP dispatch // WM_FLOW_JOB_ID is set on child jobs, so we skip dispatch for those return (async () => { @@ -2443,7 +2510,8 @@ export function taskScript(path: string, options?: TaskOptions): (...args: any[] assertUsableRetry(options?.retry); const name = path.split("/").pop() || path; const wrapper = function (...args: any[]) { - const ctx: WorkflowCtx | null = _workflowCtx ?? Reflect.get(globalThis, "__wmill_wf_ctx"); + assertNotInsideTaskBody(`taskScript("${path}")`); + const ctx = dispatchCtx(); if (ctx) { const kwargs = args.length === 1 && typeof args[0] === "object" && args[0] !== null ? args[0] @@ -2469,7 +2537,8 @@ export function taskFlow(path: string, options?: TaskOptions): (...args: any[]) assertUsableRetry(options?.retry); const name = path.split("/").pop() || path; const wrapper = function (...args: any[]) { - const ctx: WorkflowCtx | null = _workflowCtx ?? Reflect.get(globalThis, "__wmill_wf_ctx"); + assertNotInsideTaskBody(`taskFlow("${path}")`); + const ctx = dispatchCtx(); if (ctx) { const kwargs = args.length === 1 && typeof args[0] === "object" && args[0] !== null ? args[0] @@ -2522,7 +2591,8 @@ export function waitForApproval(options?: { skin?: "detailed" | "minimal"; description?: string | object; }): PromiseLike<{ value: any; approver: string; approved: boolean }> { - const ctx: WorkflowCtx | null = _workflowCtx ?? Reflect.get(globalThis, "__wmill_wf_ctx"); + assertNotInsideTaskBody("waitForApproval()"); + const ctx = dispatchCtx(); if (!ctx) { throw new Error("waitForApproval can only be called inside a workflow()"); } diff --git a/typescript-client/jsr.json b/typescript-client/jsr.json index 615e7885eb..4fe0db6362 100644 --- a/typescript-client/jsr.json +++ b/typescript-client/jsr.json @@ -1,6 +1,6 @@ { "name": "@windmill/windmill", - "version": "1.827.0", + "version": "1.841.0", "exports": "./src/index.ts", "publish": { "exclude": ["!src", "./s3Types.ts", "./sqlUtils.ts", "./client.ts", "./wacError.ts"] diff --git a/typescript-client/package.json b/typescript-client/package.json index 59f4b98719..28d7c1a372 100644 --- a/typescript-client/package.json +++ b/typescript-client/package.json @@ -1,7 +1,7 @@ { "name": "windmill-client", "description": "Windmill SDK client for browsers and Node.js", - "version": "1.827.0", + "version": "1.841.0", "author": "Ruben Fiszel", "license": "Apache 2.0", "homepage": "https://github.com/windmill-labs/windmill/tree/main/typescript-client#readme", diff --git a/typescript-client/tests/workflow_nested_task.test.ts b/typescript-client/tests/workflow_nested_task.test.ts new file mode 100644 index 0000000000..39ac2185d8 --- /dev/null +++ b/typescript-client/tests/workflow_nested_task.test.ts @@ -0,0 +1,91 @@ +/** + * A task body runs as one child job, so the SDK calls it makes cannot be + * dispatched as steps of their own. Against the real client. + * + * Run with: bun test typescript-client/tests/workflow_nested_task.test.ts + */ +import { expect, test, describe, mock, afterEach } from "bun:test"; + +mock.module("../services.gen", () => ({ + ResourceService: {}, + VariableService: {}, + JobService: {}, + HelpersService: {}, + AppService: {}, + MetricsService: {}, + OidcService: {}, + UserService: {}, + KafkaTriggerService: {}, +})); +mock.module("../core/OpenAPI", () => ({ + OpenAPI: { BASE: "http://localhost:8000/api", TOKEN: "tok" }, +})); + +const { WorkflowCtx, StepSuspend, task, taskScript, step, setWorkflowCtx } = await import( + "../client.ts" +); + +let ran: string[] = []; + +const inner = task(async function inner(x: string) { + ran.push("inner"); + return `inner:${x}`; +}); + +const outer = task(async function outer(x: string) { + ran.push("outer"); + await Promise.resolve(); + const viaTask = await inner(x); + const viaStep = await step("s", () => "stepped"); + return `${viaTask}+${viaStep}`; +}); + +const dispatching = task(async function dispatching() { + return await taskScript("f/other/script")({}); +}); + +/** Run `body` as the child round executing `key`, and hand back what it raised. */ +async function childRound(key: string, body: () => Promise<unknown>): Promise<any> { + setWorkflowCtx(new WorkflowCtx({ completed_steps: {}, _executing_key: key })); + const hung = new Promise((r) => setTimeout(() => r("hung"), 500)); + return await Promise.race([body().then(() => "returned", (e) => e), hung]); +} + +afterEach(() => { + ran = []; + setWorkflowCtx(null); +}); + +describe("SDK calls inside a task body", () => { + test("a nested task and step run in the task's own job", async () => { + const raised = await childRound("outer", async () => { + await outer("a"); + }); + + expect(raised).toBeInstanceOf(StepSuspend); + expect(raised.dispatchInfo).toMatchObject({ + mode: "step_complete", + result: "inner:a+stepped", + }); + }); + + // The workflow body keeps replaying beside the task body, and its own calls + // must stay parked: running them would execute a sibling task in this job. + test("a sibling task of the workflow body is not run", async () => { + const raised = await childRound("outer", async () => { + await Promise.all([outer("a"), inner("sibling")]); + }); + + expect(raised.dispatchInfo).toMatchObject({ mode: "step_complete" }); + expect(ran).toEqual(["outer", "inner"]); + }); + + test("a step that would need a dispatch fails instead of hanging", async () => { + const raised = await childRound("dispatching", async () => { + await dispatching(); + }); + + expect(raised).toBeInstanceOf(Error); + expect(raised.message).toContain("cannot be called from inside a task"); + }); +}); diff --git a/version.txt b/version.txt index 35d501b3a8..d3f2471c1f 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -1.827.0 +1.841.0 diff --git a/windmill-yaml-validator/package-lock.json b/windmill-yaml-validator/package-lock.json index 295ba3e97a..7dd2fc2d48 100644 --- a/windmill-yaml-validator/package-lock.json +++ b/windmill-yaml-validator/package-lock.json @@ -1,12 +1,12 @@ { "name": "windmill-yaml-validator", - "version": "1.827.0", + "version": "1.841.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "windmill-yaml-validator", - "version": "1.827.0", + "version": "1.841.0", "license": "Apache 2.0", "dependencies": { "@stoplight/yaml": "^4.3.0", diff --git a/windmill-yaml-validator/package.json b/windmill-yaml-validator/package.json index 05ba30630f..ea082c2268 100644 --- a/windmill-yaml-validator/package.json +++ b/windmill-yaml-validator/package.json @@ -1,6 +1,6 @@ { "name": "windmill-yaml-validator", - "version": "1.827.0", + "version": "1.841.0", "description": "YAML validator for Windmill flow, schedule, and trigger files", "main": "dist/index.js", "types": "dist/index.d.ts",